git-worktree

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Worktrees for Parallel Agents

用于并行Agent的Git Worktrees

Start here (before any task work)

从这里开始(任务工作前)

Detect where you are:
bash
[ "$(git rev-parse --path-format=absolute --git-dir)" = "$(git rev-parse --path-format=absolute --git-common-dir)" ] \
  && echo "primary checkout" || echo "worktree"
  • Primary checkout → do NOT start editing here. Create a worktree named after the task, bootstrap it (see "Making the worktree complete"),
    cd
    into it, and do ALL task work there.
  • Worktree (e.g. Cursor already started you in one) → proceed with the task.
检测当前所在环境:
bash
[ "$(git rev-parse --path-format=absolute --git-dir)" = "$(git rev-parse --path-format=absolute --git-common-dir)" ] \
  && echo "primary checkout" || echo "worktree"
  • 主检出环境 → 请勿在此处开始编辑。创建一个以任务命名的worktree,完成初始化(参见「让worktree环境完整」),
    cd
    进入该目录,所有任务工作都在此处进行。
  • Worktree(例如Cursor已将你带入其中)→ 继续执行任务。

What a worktree is

Worktree是什么

One repo, multiple folders.
git worktree add
creates an extra checkout of the same repository in a separate directory, on its own branch. All worktrees share one
.git
history, but each has its own files. Two agents in two worktrees physically cannot overwrite each other's work.
单个仓库,多个文件夹。
git worktree add
会在单独的目录中创建同一仓库的额外检出版本,位于独立分支上。所有worktree共享同一个
.git
历史,但各自拥有独立的文件。两个Agent在不同worktree中操作时,不会互相覆盖彼此的工作。

The working model

工作模式

  • One task = one worktree = one agent session. Never let two agents share a working directory.
  • The primary checkout is the integration point. It stays on the main branch and is used only to review, merge, and push. It is not a scratchpad.
  • Nothing auto-merges. The human reviews each worktree's diff, then merges it into main (or discards it), then deletes the worktree.
  • Worktree branches are local and short-lived. Never push them unless the user explicitly asks. Only main gets pushed.
  • Merge one worktree at a time. Rebase a stale worktree onto main before merging if main moved.
  • 一个任务 = 一个worktree = 一个Agent会话。绝不让两个Agent共享同一个工作目录。
  • 主检出环境是集成点。它始终处于main分支,仅用于审查、合并和推送,不作为临时工作区。
  • 无自动合并。由人工审查每个worktree的差异,然后将其合并到main分支(或丢弃),再删除该worktree。
  • Worktree分支为本地且短期存在。除非用户明确要求,否则不要推送这些分支。仅推送main分支。
  • 一次合并一个worktree。如果main分支有更新,在合并前将过时的worktree分支变基到main分支上。

Creating and removing

创建与删除

bash
git worktree add ../myrepo-task-x          # new worktree + branch "myrepo-task-x"
git worktree add ../fix-y -b fix-y main    # explicit branch off main
git worktree list                          # see all worktrees
git worktree remove ../myrepo-task-x       # delete when merged/abandoned
git worktree prune                         # clean up stale registrations
Note: a branch can only be checked out in ONE worktree at a time (including main).
In Cursor: start agents in worktrees via the Agents Window, or
/worktree <task>
in a chat.
/apply-worktree
merges the result into your main checkout;
/delete-worktree
discards;
/best-of-n model1,model2 <task>
runs the same task in parallel worktrees, one per model. Cursor auto-deletes older worktrees (default cap 25 per machine), so merge or push results promptly.
bash
git worktree add ../myrepo-task-x          # 新建worktree + 分支「myrepo-task-x」
git worktree add ../fix-y -b fix-y main    # 基于main分支显式创建分支「fix-y」
git worktree list                          # 查看所有worktree
git worktree remove ../myrepo-task-x       # 合并或放弃后删除worktree
git worktree prune                         # 清理过期的worktree注册信息
注意:一个分支只能在一个worktree中检出(包括main分支)。
在Cursor中:通过Agents窗口在worktree中启动Agent,或在聊天中输入
/worktree <task>
/apply-worktree
将结果合并到主检出环境;
/delete-worktree
丢弃worktree;
/best-of-n model1,model2 <task>
在并行worktree中运行同一任务,每个模型对应一个worktree。Cursor会自动删除旧的worktree(默认每台机器最多保留25个),因此请及时合并或推送结果。

Making the worktree complete

让worktree环境完整

A fresh worktree contains ONLY tracked files. Everything gitignored is missing. An agent dropped into a bare worktree will fail confusingly, so replicate:
  1. Env/secret files — copy
    .env
    ,
    .env.local
    , and similar from the primary checkout. Copy, never symlink (an agent editing a symlinked env file would corrupt the original).
  2. Dependencies — run the install (
    npm ci
    ,
    pnpm install
    ,
    uv sync
    ,
    bundle install
    ). Never symlink
    node_modules
    ; it breaks builds in both checkouts.
  3. Local databases and services — decide per service:
    • Shared server (e.g. one Postgres container): pin the identity so worktrees don't spawn duplicates fighting over the same port. For Docker Compose, set a top-level
      name:
      in the compose file — otherwise the project name comes from the folder name and every worktree starts its own container on the same port.
    • Per-worktree state (e.g. SQLite files): copy or re-seed it.
  4. Ports — dev servers, test servers, and debuggers bind fixed ports. Either run one at a time across all worktrees, or make the port configurable per worktree.
  5. Generated files and caches — rebuild in the worktree (
    npm run build
    , codegen); build output is gitignored and won't be there.
  6. Git hooks
    core.hooksPath
    and
    .git/config
    are shared across worktrees automatically; verify hook scripts don't assume the primary checkout's path.
新创建的worktree仅包含被追踪的文件,所有被git忽略的文件都缺失。如果Agent进入一个不完整的worktree,会出现难以排查的错误,因此需要复制以下内容:
  1. 环境/密钥文件 — 从主检出环境复制
    .env
    .env.local
    等类似文件。请复制而非创建符号链接(Agent编辑符号链接的环境文件会损坏原始文件)。
  2. 依赖项 — 执行安装命令(
    npm ci
    pnpm install
    uv sync
    bundle install
    )。切勿符号链接
    node_modules
    ;这会破坏两个检出环境的构建。
  3. 本地数据库与服务 — 根据服务类型决定:
    • 共享服务器(例如一个Postgres容器):固定标识,避免worktree启动重复实例占用同一端口。对于Docker Compose,在compose文件中设置顶级
      name:
      — 否则项目名称会来自文件夹名称,每个worktree都会在同一端口启动自己的容器。
    • 每个worktree独立的状态(例如SQLite文件):复制或重新初始化数据。
  4. 端口 — 开发服务器、测试服务器和调试器绑定固定端口。要么在所有worktree中一次只运行一个,要么让端口可按worktree配置。
  5. 生成文件与缓存 — 在worktree中重新构建(
    npm run build
    、代码生成);构建输出被git忽略,不会出现在新worktree中。
  6. Git钩子
    core.hooksPath
    .git/config
    会自动在所有worktree间共享;请验证钩子脚本未假设主检出环境的路径。

Automate the setup

自动化初始化

Codify the checklist so every worktree bootstraps itself. In Cursor,
.cursor/worktrees.json
runs on worktree creation (
$ROOT_WORKTREE_PATH
= the primary checkout):
json
{
  "setup-worktree": [
    "npm ci",
    "cp $ROOT_WORKTREE_PATH/.env.local .env.local"
  ]
}
Without Cursor, keep a
scripts/setup-worktree.sh
in the repo and run it as the first command in any new worktree. Inside a worktree, the primary checkout's path is:
bash
dirname "$(git rev-parse --path-format=absolute --git-common-dir)"
将检查清单编码,让每个worktree自动完成初始化。在Cursor中,
.cursor/worktrees.json
会在worktree创建时执行(
$ROOT_WORKTREE_PATH
= 主检出环境路径):
json
{
  "setup-worktree": [
    "npm ci",
    "cp $ROOT_WORKTREE_PATH/.env.local .env.local"
  ]
}
如果不使用Cursor,可在仓库中保留
scripts/setup-worktree.sh
,并在任何新worktree中首先执行该脚本。在worktree内部,主检出环境的路径为:
bash
dirname "$(git rev-parse --path-format=absolute --git-common-dir)"

Merging back

合并回主分支

bash
undefined
bash
undefined

from the primary checkout, after reviewing the worktree's diff:

在主检出环境中,审查完worktree的差异后:

git merge --no-ff task-branch # or: git merge --squash task-branch git worktree remove ../myrepo-task-x git branch -d task-branch

Or in Cursor, simply `/apply-worktree` from the agent's chat, review, commit.
git merge --no-ff task-branch # 或:git merge --squash task-branch git worktree remove ../myrepo-task-x git branch -d task-branch

或者在Cursor中,只需在Agent聊天中输入`/apply-worktree`,审查后提交即可。

Gotchas

注意事项

  • Gitignored files silently missing is the #1 failure — always bootstrap before the agent starts.
  • Disk: each worktree duplicates the working files plus its own
    node_modules
    . Delete merged worktrees; don't hoard them.
  • Long-lived worktrees rot. If a task stalls for days, rebase onto main or restart it.
  • Uncommitted work in a deleted worktree is gone. Commit in the worktree early and often; the commits live in the shared repo even after the folder is removed.
  • One shared stash list, one shared config, one shared refs namespace — worktrees isolate files, not git state.
  • 被git忽略的文件悄悄缺失是最常见的失败原因 — 务必在Agent启动前完成初始化。
  • 磁盘占用:每个worktree会复制工作文件加上自己的
    node_modules
    。合并后删除worktree;不要囤积。
  • 长期存在的worktree会失效。如果任务停滞数天,将其变基到main分支或重新启动任务。
  • 删除worktree时,未提交的工作会丢失。请尽早并经常在worktree中提交;即使文件夹被删除,提交记录仍会保存在共享仓库中。
  • 共享的暂存列表、配置和引用命名空间 — worktree隔离的是文件,而非git状态。