병렬 에이전트용 Claude Code worktree: worktree 스킬
Dmitriy Solodukha, Caprock 개발자 · 게시일
Claude Code와 Codex에서 테스트
Claude Code worktree로 여러 에이전트가 한 저장소에서 병렬로 작업합니다. worktree 스킬은 설정, 상태 확인, 원래 브랜치로의 병합, 정리를 수행하며 --force는 절대 사용하지 않습니다.
Claude Code worktree는 하나의 저장소에서 각 에이전트에 전용 폴더와 브랜치를 제공합니다. worktree 스킬은 Claude Code, Codex, OpenCode, Cursor에서 같은 방식으로 설정과 정리를 수행합니다. 작업 하나에 브랜치 하나, 폴더 하나를 사용합니다. 최신 기준 브랜치에서 worktree를 만들고, 프로젝트에 필요한 환경 파일을 복사하며, 각각에 전용 포트나 데이터베이스를 할당합니다. 기본 동작을 점검하고 상태를 하나의 표로 보고한 뒤 원래 브랜치로 병합하며, 변경 사항이 없고 병합된 것만 삭제합니다.
worktree 스킬 설치
에이전트마다 명령어 하나로 설치합니다. 스킬은 SKILL.md 파일 하나이며, 설치 시 실행되는 것은 없습니다.
스킬 아홉 가지 전체를 플러그인으로 설치합니다. Claude Code 안에서 다음을 입력합니다:
이 스킬만 설치하려면 터미널에서 프로젝트 폴더로 이동한 뒤 다음을 실행합니다:
추가 옵션: -g 모든 프로젝트에 설치하려면 앞의 옵션을 추가합니다.
터미널에서 프로젝트 폴더로 이동한 뒤 다음을 실행합니다:
추가 옵션: -g 모든 프로젝트에 설치하려면 앞의 옵션을 추가합니다.
터미널에서 프로젝트 폴더로 이동한 뒤 다음을 실행합니다:
추가 옵션: -g 모든 프로젝트에 설치하려면 앞의 옵션을 추가합니다. 아직 OpenCode에서 테스트하지 않았습니다. 이 스킬은 개방형 형식의 일반 지침이지만, OpenCode에서 실행해 검증한 적은 없습니다.
터미널에서 프로젝트 폴더로 이동한 뒤 다음을 실행합니다:
추가 옵션: -g 모든 프로젝트에 설치하려면 앞의 옵션을 추가합니다. 아직 Cursor에서 테스트하지 않았습니다. 이 스킬은 개방형 형식의 일반 지침이지만, Cursor에서 실행해 검증한 적은 없습니다.
worktree 스킬을 사용하는 프롬프트
요청이 스킬 설명과 일치하면 에이전트가 해당 스킬을 선택합니다. 이름을 명시하면 확실하게 선택할 수 있습니다. 프롬프트를 클릭하면 복사됩니다.
worktree 스킬의 Claude Code worktree 실행 방식
- 생성 전:
git worktree list와 변경 사항 없는 main 체크아웃. Caprock을 사용하면recent_sessions가 실행 중인 세션에서 사용 중인 브랜치를 보여 줍니다. - 생성: 작업 이름을 kebab-case로 지정한
git worktree add -b <task> ../<repo>.worktrees/<task> main. - 실행 가능한 형태로 작성: Git에서 무시하는 환경 파일을 심볼릭 링크 대신 복사하고, 작업에 빌드가 필요하면 프로젝트 자체 설정을 실행합니다. 포트와 데이터베이스를 분리하고 간단한 확인을 한 번 수행합니다.
- 언제든 상태 확인:
git worktree list -v,git -C <path> status --short, main보다 앞선 커밋. - 기본 체크아웃에서 원래 브랜치로 병합하거나 PR을 엽니다. 충돌이 발생하면 중단합니다.
git merge-base --is-ancestor에서 병합되었다고 표시한 뒤에만 제거. 병합되지 않은 작업을 거부하는git worktree remove와git branch -d를 사용합니다.
스킬의 모든 Git 명령은 Git 자체 도움말로 확인했습니다(git 2.54.0, 2026년 11월 29일).
실행한 내용과 에이전트의 수행 결과
각 스킬은 2026년 11월 29일에 해당 스킬용으로 만든 임시 저장소에서 프로젝트 스킬로 설치해 실행했습니다. 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를 만든 뒤 각각 스모크 테스트를 실행하고 스킬의 표 형식으로 보고했습니다. calc.py가 .env를 읽지 않으므로 복사하지 않기로 했으며, 그 이유를 밝혔습니다.
| 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는 스킬 규칙을 근거로 거부했으며 --force를 사용하지 않았습니다.
테스트한 에이전트
- Claude Code:
.claude/skills/에 프로젝트 스킬로 설치한 상태에서 2026년 11월 29일에claude -p --model sonnet으로 테스트했습니다. - Codex: 2026년 11월 29일에 Codex 0.163.0(
codex exec)로 테스트했으며, 스킬은.agents/skills/에 설치했습니다. - OpenCode와 Cursor: 테스트하지 않았습니다. 스킬은 공개 Agent Skills 형식의 일반 지침이지만, 어느 쪽에서도 실행하여 확인하지 않았습니다.
한도
- 작업에 빌드나 테스트가 필요한 경우에만 의존성을 설치합니다. 네트워크에서 가져오며, 스킬은 이를 먼저 알립니다.
- worktree 안에서 수정한 Git 무시 파일은 폴더를 삭제할 때 함께 삭제됩니다. 스킬은 먼저 파일을 밖으로 복사하라고 안내합니다.
- 검증한 기능이 없어 Codex 전용 worktree 기능은 설명하지 않습니다.
Caprock을 사용할 때와 사용하지 않을 때
Caprock MCP 서버가 연결되면 스킬이 해당 저장소의 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 스킬 관련 질문
- Claude Code worktree는 어떻게 작동하나요?
- `claude --worktree <name>`(또는 `-w`)은 새 브랜치 `worktree-<name>`에 `.claude/worktrees/<name>/`을 만들고 그곳에서 세션을 시작합니다. `.worktreeinclude` 파일에는 `.env`처럼 Git에서 무시하지만 복사해 넣을 파일을 나열합니다.
- worktree 스킬은 Claude Code worktree에 무엇을 추가하나요?
- 주변 작업을 처리합니다. 별도의 포트와 데이터베이스, 스모크 테스트, 모든 worktree를 담은 하나의 상태 표, 안전한 병합, 변경 사항이 있거나 잠겼거나 병합되지 않은 worktree의 정리를 거부하는 기능입니다. Claude Code가 삭제하지 않는 `claude -p` 실행 후 남은 worktree도 정리합니다.
- worktree 스킬이 작업 내용을 삭제할 수 있나요?
- 그렇게 하지 않도록 작성되어 있습니다. `--force`, `git branch -D`, `rm -rf`를 사용하지 않으며, 커밋하지 않았거나 추적되지 않는 파일이 있는 worktree는 삭제하지 않고 보고합니다.
- Codex에서도 작동하나요?
- 네, 일반 Git으로 가능합니다. Codex 0.163.0은 2026년 11월 29일 테스트에서 이 스킬로 worktree를 정리했으며, 변경 사항이 있는 worktree는 정리를 거부했습니다.