Git

Git 与并行会话

使用 Claude Code worktrees、checkpoints、git 操作和隔离分支,安全地并行开发。

内置 Git 感知

Claude Code 会读取 git 状态、理解分支上下文,并协助 commits、branches、diffs 和 PR。它能区分 staged / unstaged changes,查看历史,并遵守 .gitignore

常用 prompts:

text
Summarize the diff since main and suggest a PR title.
Commit only the files related to the auth fix.
Review my staged changes for bugs and missing tests.

如果 worktree 里可能有别人或你之前留下的无关改动,委托 commit 前一定先看 git status

Checkpoints 与 Rewind

Claude Code 会围绕文件编辑创建 checkpoints。在输入框为空时按 Esc Esc 打开 rewind,可以选择恢复代码、恢复对话、两者都恢复,或围绕某个时间点做摘要。

Checkpoints 不是 git commits。实验用 checkpoints;可 review 的持久历史用 git commits。

Claude Code Worktrees

创建隔离并行会话最简单的方法:

bash
claude --worktree

Claude Code 会创建 git worktree,进入它,并在那里启动会话。每个 worktree 都有自己的目录、分支、工作区和 Claude 上下文。

适合场景:

  • 探索高风险重构,不影响主 checkout。
  • 在独立任务上运行第二个 Claude session。
  • 让 subagent 或 teammate 编辑文件时不撞到主工作区。
  • 同时比较两种方案再选择。

用 .worktreeinclude 带上额外文件

Worktrees 通常共享仓库历史,但不会自动复制每个 untracked 本地文件。如果项目需要把本地文件复制到新 worktrees,使用 .worktreeinclude

.worktreeinclude
.env.example
.claude/settings.local.json
local-fixtures/

不要包含 secrets,除非你确定新 worktree 处在同样的信任边界内。

手工 Worktrees

如果你想精确控制分支名或目录名,手工 git worktrees 仍然有用:

bash
git worktree add ../project-feature-auth feature/auth
git worktree add ../project-fix-perf fix/performance

cd ../project-feature-auth
claude

完成后清理:

bash
git worktree list
git worktree remove ../project-feature-auth

Subagents 与 Worktree 隔离

Subagents 隔离上下文。Worktrees 隔离文件。并行编辑时要组合使用。

自定义 subagents 可以要求 worktree isolation:

.claude/agents/test-fixer.md
---
name: test-fixer
description: Fix isolated test failures in a separate worktree.
tools: Read, Edit, Bash
isolation: worktree
---

Subagent 没有改动时,worktree 可以清理。有改动时,保留 worktree 供人 review 后再合并。

Agent Teams 与 Worktrees

Agent teams 负责协调独立 Claude Code 实例。Worktrees 负责避免文件编辑冲突。

明确 ownership:

text
Use an agent team with worktree isolation.
Teammate A owns API routes.
Teammate B owns UI components.
Teammate C owns tests and verification.
No teammate should edit files outside its lane without asking.

除非只是研究,不要让多个 agents 同时编辑同一批文件。

CI 和 Headless Git 任务

CI 中做只读 review:

bash
git diff origin/main...HEAD | claude -p \
  "Review this diff for bugs, security risks, and missing tests. Output JSON." \
  --output-format json

只有在 sandboxed 环境中,且输入和文件系统影响范围可控时,才使用 --dangerously-skip-permissions

实用工作流

  1. 从干净主 worktree 开始:git status
  2. 创建隔离 worktree:claude --worktree
  3. 让 Claude 在 plan mode 中制定计划。
  4. 在 worktree 中实现。
  5. 跑测试并 review diff。
  6. 把有用改动 merge 或 cherry-pick 回来。
  7. 移除不再使用的 worktrees。

延伸阅读

继续实践

Git 与并行会话 的核心概念已经读完

如果你想把理解变成可复用的能力,可以到 AgentWay 继续练习