using-git-worktrees

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

使用 Git 工作树

Using Git Worktrees

概述

Overview

确保工作发生在隔离的工作区中。优先使用你的平台的原生 worktree 工具。仅在没有原生工具可用时,再回退到手动 git worktree。
核心原则: 先检测现有隔离。然后用原生工具。再回退到 git。绝不与 harness 对抗。
开始时宣布: "我正在使用 using-git-worktrees 技能来建立一个隔离的工作区。"
Ensure work happens in an isolated workspace. Prioritize your platform's native worktree tools. Only fall back to manual git worktree when no native tools are available.
Core Principle: Detect existing isolation first. Then use native tools. Then fall back to git. Never fight the harness.
Announce at the start: "I am using the using-git-worktrees skill to set up an isolated workspace."

步骤 0:检测现有隔离

Step 0: Detect Existing Isolation

创建任何东西之前,先检查你是否已经在一个隔离的工作区里。
bash
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
BRANCH=$(git branch --show-current)
Submodule 守卫: 在 git submodule 内
GIT_DIR != GIT_COMMON
也为真。在判定"已经在 worktree 内"之前,先确认你不在 submodule 里:
bash
undefined
Before creating anything, check if you're already in an isolated workspace.
bash
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
BRANCH=$(git branch --show-current)
Submodule Guard:
GIT_DIR != GIT_COMMON
is also true inside a git submodule. Before determining "already in worktree", confirm you're not in a submodule:
bash
undefined

如果这条命令返回路径,说明你在 submodule 里,不是 worktree —— 按普通仓库处理

If this command returns a path, you're in a submodule, not a worktree — treat as a normal repo

git rev-parse --show-superproject-working-tree 2>/dev/null

**如果 `GIT_DIR != GIT_COMMON`(且不是 submodule):** 你已经在一个 linked worktree 内。跳到步骤 3(项目设置)。**不要**再创建一个 worktree。

按分支状态报告:

- 在某个分支上:"已经在隔离工作区 `<path>`,分支 `<name>`。"
- 分离 HEAD:"已经在隔离工作区 `<path>`(分离 HEAD,由外部管理)。完成时需要创建分支。"

**如果 `GIT_DIR == GIT_COMMON`(或在 submodule 内):** 你在一个普通的仓库检出里。

用户是否已经在你的 instructions 里表明过 worktree 偏好?如果没有,创建 worktree 之前先征求同意:

> "你希望我搭一个隔离的 worktree 吗?它能保护你当前分支不被改动。"

如果用户已声明过偏好,直接遵循,不再询问。如果用户拒绝同意,原地工作并跳到步骤 3。
git rev-parse --show-superproject-working-tree 2>/dev/null

**If `GIT_DIR != GIT_COMMON` (and not in a submodule):** You're already inside a linked worktree. Skip to Step 3 (Project Setup). **Do NOT** create another worktree.

Report based on branch status:

- On a branch: "Already in isolated workspace `<path>`, branch `<name>`."
- Detached HEAD: "Already in isolated workspace `<path>` (detached HEAD, managed externally). Need to create a branch when done."

**If `GIT_DIR == GIT_COMMON` (or in a submodule):** You're in a normal repo checkout.

Has the user already indicated a worktree preference in your instructions? If not, ask for consent before creating a worktree:

> "Would you like me to set up an isolated worktree? It protects your current branch from being modified."

If the user has stated a preference, follow it directly without asking. If the user declines consent, work in place and skip to Step 3.

步骤 1:创建隔离工作区

Step 1: Create Isolated Workspace

你有两种机制。按这个顺序尝试。
You have two mechanisms. Try in this order.

1a. 原生 Worktree 工具(首选)

1a. Native Worktree Tools (Preferred)

用户已经请求隔离工作区(步骤 0 已获同意)。你是否已经有创建 worktree 的方法?可能是名为
EnterWorktree
WorktreeCreate
的工具、
/worktree
命令,或
--worktree
标志。如果有,用它,然后跳到步骤 3。
原生工具自动处理目录放置、分支创建和清理。在你已经有原生工具的情况下使用
git worktree add
,会创建你的 harness 看不到也无法管理的"幻影状态"。
只有在没有原生 worktree 工具可用时,才进入步骤 1b。
The user has requested an isolated workspace (consented in Step 0). Do you already have a method to create worktrees? It could be tools named
EnterWorktree
,
WorktreeCreate
,
/worktree
command, or
--worktree
flag. If yes, use it, then skip to Step 3.
Native tools automatically handle directory placement, branch creation, and cleanup. Using
git worktree add
when you have native tools will create "phantom state" that your harness can't see or manage.
Only proceed to Step 1b if no native worktree tools are available.

1b. Git Worktree 回退

1b. Git Worktree Fallback

只在步骤 1a 不适用时使用 —— 你没有可用的原生 worktree 工具。手动用 git 创建 worktree。
Only use when Step 1a is not applicable — you have no native worktree tools available. Manually create a worktree with git.

目录选择

Directory Selection

按以下优先级。明确的用户偏好始终优先于观察到的文件系统状态。
  1. 检查你的 instructions 里是否声明过 worktree 目录偏好。 如果用户已指定,不再询问直接用。
  2. 检查是否存在项目本地的 worktree 目录:
    bash
    ls -d .worktrees 2>/dev/null     # 首选(隐藏目录)
    ls -d worktrees 2>/dev/null      # 备选
    找到就用。如果两者都存在,
    .worktrees
    优先。
  3. 检查是否存在全局目录:
    bash
    project=$(basename "$(git rev-parse --show-toplevel)")
    ls -d ~/.config/superpowers/worktrees/$project 2>/dev/null
    找到就用(兼容老的全局路径)。
  4. 如果没有其他可参考的信息,默认用项目根目录下的
    .worktrees/
Follow these priorities. Explicit user preferences always take precedence over observed filesystem state.
  1. Check if a worktree directory preference is declared in your instructions. If specified by the user, use it without asking.
  2. Check for project-local worktree directories:
    bash
    ls -d .worktrees 2>/dev/null     # Preferred (hidden directory)
    ls -d worktrees 2>/dev/null      # Alternative
    Use if found. If both exist,
    .worktrees
    takes priority.
  3. Check for global directory:
    bash
    project=$(basename "$(git rev-parse --show-toplevel)")
    ls -d ~/.config/superpowers/worktrees/$project 2>/dev/null
    Use if found (compatible with old global paths).
  4. If no other references exist, default to
    .worktrees/
    in the project root.

安全验证(仅项目本地目录)

Security Validation (Project-Local Directories Only)

创建 worktree 前必须验证目录已被忽略:
bash
git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null
如果未被忽略: 添加到 .gitignore,提交该改动,然后继续。
为什么关键: 防止 worktree 内容被意外提交到仓库。
全局目录(
~/.config/superpowers/worktrees/
)无需验证。
Must verify the directory is ignored before creating worktree:
bash
git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null
If not ignored: Add to .gitignore, commit the change, then proceed.
Why it's critical: Prevent worktree content from being accidentally committed to the repo.
Global directories (
~/.config/superpowers/worktrees/
) don't need validation.

创建工作树

Create Worktree

bash
project=$(basename "$(git rev-parse --show-toplevel)")
bash
project=$(basename "$(git rev-parse --show-toplevel)")

根据选定位置确定路径

Determine path based on selected location

项目本地:path="$LOCATION/$BRANCH_NAME"

Project-local: path="$LOCATION/$BRANCH_NAME"

全局:path="~/.config/superpowers/worktrees/$project/$BRANCH_NAME"

Global: path="~/.config/superpowers/worktrees/$project/$BRANCH_NAME"

git worktree add "$path" -b "$BRANCH_NAME" cd "$path"

**沙盒回退:** 如果 `git worktree add` 因权限错误(沙盒拒绝)失败,告诉用户沙盒阻止了 worktree 创建,你将在当前目录原地工作。然后原地运行 setup 和基线测试。
git worktree add "$path" -b "$BRANCH_NAME" cd "$path"

**Sandbox Fallback:** If `git worktree add` fails due to permission errors (sandbox denial), inform the user that the sandbox prevented worktree creation, and you will work in the current directory. Then run setup and baseline tests in place.

步骤 3:项目设置

Step 3: Project Setup

自动检测并运行相应的设置命令:
bash
undefined
Automatically detect and run the corresponding setup commands:
bash
undefined

Node.js

Node.js

if [ -f package.json ]; then npm install; fi
if [ -f package.json ]; then npm install; fi

Rust

Rust

if [ -f Cargo.toml ]; then cargo build; fi
if [ -f Cargo.toml ]; then cargo build; fi

Python

Python

if [ -f requirements.txt ]; then pip install -r requirements.txt; fi if [ -f pyproject.toml ]; then poetry install; fi
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi if [ -f pyproject.toml ]; then poetry install; fi

Go

Go

if [ -f go.mod ]; then go mod download; fi
undefined
if [ -f go.mod ]; then go mod download; fi
undefined

步骤 4:验证基线干净

Step 4: Verify Clean Baseline

运行测试确保工作区初始状态干净:
bash
undefined
Run tests to ensure the initial workspace state is clean:
bash
undefined

使用项目对应的命令

Use project-specific commands

npm test / cargo test / pytest / go test ./...

**如果测试失败:** 报告失败,询问是继续还是排查。

**如果测试通过:** 报告就绪。
npm test / cargo test / pytest / go test ./...

**If tests fail:** Report the failure and ask whether to continue or troubleshoot.

**If tests pass:** Report readiness.

报告

Report

工作树已就绪:<full-path>
测试通过(<N> 个测试,0 个失败)
准备实现 <feature-name>
Worktree ready: <full-path>
Tests passed (<N> tests, 0 failures)
Ready to implement <feature-name>

快速参考

Quick Reference

情况操作
已在 linked worktree 内跳过创建(步骤 0)
在 submodule 内按普通仓库处理(步骤 0 守卫)
有原生 worktree 工具用它(步骤 1a)
没有原生工具git worktree 回退(步骤 1b)
.worktrees/
存在
用它(验证已忽略)
worktrees/
存在
用它(验证已忽略)
两者都存在
.worktrees/
都不存在检查 instructions 文件,再默认
.worktrees/
全局路径存在用它(向后兼容)
目录未被忽略添加到 .gitignore + 提交
创建时权限错误沙盒回退,原地工作
基线测试失败报告失败 + 询问
无 package.json/Cargo.toml跳过依赖安装
ScenarioAction
Already in linked worktreeSkip creation (Step 0)
Inside a submoduleTreat as normal repo (Step 0 guard)
Native worktree tools availableUse them (Step 1a)
No native toolsUse git worktree fallback (Step 1b)
.worktrees/
exists
Use it (verify ignored)
worktrees/
exists
Use it (verify ignored)
Both existUse
.worktrees/
Neither existsCheck instructions file, then default to
.worktrees/
Global path existsUse it (backward compatibility)
Directory not ignoredAdd to .gitignore + commit
Permission error during creationSandbox fallback, work in place
Baseline tests failReport failure + ask
No package.json/Cargo.tomlSkip dependency installation

常见错误

Common Errors

与 harness 对抗

Fighting the Harness

  • 问题: 平台已经提供隔离的情况下还在用
    git worktree add
  • 修复: 步骤 0 检测现有隔离。步骤 1a 让位给原生工具。
  • Problem: Using
    git worktree add
    when the platform already provides isolation
  • Fix: Detect existing isolation in Step 0. Defer to native tools in Step 1a.

跳过检测

Skipping Detection

  • 问题: 在已有的 worktree 内嵌套创建另一个 worktree
  • 修复: 创建任何东西之前都先跑步骤 0
  • Problem: Nested creation of another worktree inside an existing one
  • Fix: Always run Step 0 before creating anything

跳过忽略验证

Skipping Ignore Validation

  • 问题: worktree 内容被跟踪,污染 git status
  • 修复: 创建项目本地 worktree 前始终使用
    git check-ignore
  • Problem: Worktree content is tracked, polluting git status
  • Fix: Always use
    git check-ignore
    before creating project-local worktrees

假设目录位置

Assuming Directory Location

  • 问题: 造成不一致、违反项目约定
  • 修复: 遵循优先级:现有目录 > 全局历史路径 > instructions 文件 > 默认
  • Problem: Causes inconsistency, violates project conventions
  • Fix: Follow priorities: existing directories > global historical paths > instructions file > default

带着失败的测试继续

Continuing with Failed Tests

  • 问题: 无法区分新 bug 和已有问题
  • 修复: 报告失败,获得明确许可后再继续
  • Problem: Can't distinguish new bugs from pre-existing issues
  • Fix: Report failure and get explicit permission before continuing

红线

Red Lines

绝不:
  • 步骤 0 已检测到现有隔离时还创建 worktree
  • 在已有原生 worktree 工具(如
    EnterWorktree
    )的情况下还用
    git worktree add
    。这是 #1 错误——有就用。
  • 跳过步骤 1a 直接跳到步骤 1b 的 git 命令
  • 不验证已忽略就创建项目本地 worktree
  • 跳过基线测试验证
  • 不询问就带着失败的测试继续
始终:
  • 先跑步骤 0 检测
  • 优先原生工具,其次 git 回退
  • 遵循目录优先级:现有目录 > 全局历史路径 > instructions 文件 > 默认
  • 项目本地目录验证已忽略
  • 自动检测并运行项目设置
  • 验证测试基线干净
Never:
  • Create a worktree when Step 0 detects existing isolation
  • Use
    git worktree add
    when native worktree tools (like
    EnterWorktree
    ) are available. This is the #1 mistake — use what's available.
  • Skip Step 1a and jump directly to git commands in Step 1b
  • Create project-local worktrees without verifying they're ignored
  • Skip baseline test validation
  • Continue with failed tests without asking
Always:
  • Run Step 0 detection first
  • Prioritize native tools, then git fallback
  • Follow directory priorities: existing directories > global historical paths > instructions file > default
  • Verify project-local directories are ignored
  • Automatically detect and run project setup
  • Verify clean test baseline

集成

Integration

被以下技能调用:
  • brainstorming(阶段 4)- 设计通过且需要实现时必需
  • subagent-driven-development - 执行任何任务前必需
  • executing-plans - 执行任何任务前必需
  • 任何需要隔离工作区的技能
配合使用:
  • finishing-a-development-branch - 工作完成后清理时必需
Called by these skills:
  • brainstorming (Phase 4) - Required when design is approved and implementation is needed
  • subagent-driven-development - Required before executing any tasks
  • executing-plans - Required before executing any tasks
  • Any skill that requires an isolated workspace
Used with:
  • finishing-a-development-branch - Required for cleanup when work is completed