Codex Worktrees:从建立到安全清理
用独立目录并行开发或审查,实际核对分支占用、暂存隔离以及清理条件。
学完这一章,你能够
- 用独立目录并行开发或审查,实际核对分支占用、暂存隔离以及清理条件。
为开发、修复和审查选定工作目录
一个 Git 仓库可以同时有主工作树和附加工作树。各目录持有自己的文件和暂存区,仍共享对象库及普通分支引用。可让主目录留在基线,在一个附加目录做功能,在另一个目录从相同提交审查。
工作树提供的是 Git 工作目录隔离。应用端口、数据库、依赖缓存以及系统环境仍可能共享。需要两个服务同时运行时,为每个目录分别选择端口和数据位置。
从 Codex 桌面或 Git 创建
应用当前流程是在新聊天的输入区选择 Worktree,再选基线分支并提交任务。Codex 通常创建 detached HEAD 工作树。之后可用 Create branch here 将改动放到命名分支,或按应用流程交接至 Local。旧界面中的 New 到 Worktree 及预先填写分支名,按当前界面入口核对。
使用 Git 也能创建附加工作树。例如在主仓库运行 git worktree add -b topic/catalog ../topic main,再用 git worktree add --detach ../review main 建立独立审查目录。本机试图把同一个已经检出的分支再挂到第三个目录时,Git 拒绝并且没有创建目录。
保留成果后清理
用 git worktree list 检查目录、分支与分离状态,并在对应目录运行 git status。练习只在功能目录暂存 notes.txt,另一工作树和主工作树暂存区都保持空。
完成后提交需保留的改动,并在清理前检查未跟踪和未提交文件。git worktree remove 默认会拒绝有未提交改动的目录。本站练习先观察拒绝,保存进功能分支后普通清理。清理目录后仍可读取功能分支的提交。

用能说明任务的分支名。Codex 管理的工作树另有快照与清理流程。应用创建、交接和恢复在对应界面复查,本站本轮实测的是原生 Git 命令。
本地两种任务模式
| 模式 | 对应工作目录 |
|---|---|
| Local | 使用项目已选择的本地工作目录。 |
| Worktree | 从明确基线创建附加 Git 工作树,单独保留自己的文件与暂存区。 |
实际创建并清理两个 Git 工作树
"""Test worktree creation, shared refs, detached reviews, and ordinary removal."""
from hashlib import sha256
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
def main():
codex = shutil.which("codex.exe") or shutil.which("codex")
git = shutil.which("git")
if not codex or not git:
raise SystemExit("Install Codex CLI and Git and add both to PATH.")
observations = []
with TemporaryDirectory(prefix="mbsky-worktree-lifecycle-") as temporary:
root = Path(temporary).resolve()
repo = root / "repo"
repo.mkdir()
topic = root / "topic"
review = root / "review"
conflict = root / "duplicate"
env = {k:v for k,v in os.environ.items() if not k.startswith(("GIT_", "CODEX_"))}
env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, CODEX_HOME=str(root/"diagnostic-profile"))
def run(cwd, *args, binary=git, check=True):
result = subprocess.run([binary,*args], cwd=cwd, env=env, capture_output=True,
encoding="utf8", check=check, timeout=15)
return result if not check else result.stdout.strip()
def verify(name, inputs, operation, expected, actual):
assert expected == actual, (name, expected, actual)
observations.append(dict(name="worktrees_"+name,input=inputs,operation=operation,
expected=expected,actual=actual))
def listed():
return run(repo,"worktree","list","--porcelain").count("worktree ")
run(repo,"init","--quiet","--initial-branch=main","--template=")
run(repo,"config","core.autocrlf","false")
run(repo,"config","commit.gpgsign","false")
(repo/"notes.txt").write_bytes(b"catalog=ready\n")
run(repo,"add","notes.txt")
run(repo,"-c","user.name=Tutorial Lab","-c","user.email=fixture@example.invalid","commit","--quiet","-m","Baseline")
verify("initial","fresh repository","Observe the initial worktree listing",1,listed())
run(repo,"worktree","add","--quiet","-b","topic/catalog",str(topic),"main")
run(repo,"worktree","add","--quiet","--detach",str(review),"main")
verify("add",["topic/catalog","detached main"],"Observe listing after adding two fixtures",3,listed())
verify("detached","main base commit","Compare HEADs and check detached branch name",
[True,""],[run(review,"rev-parse","HEAD")==run(repo,"rev-parse","HEAD"),run(review,"branch","--show-current")])
occupied = run(repo,"worktree","add",str(conflict),"topic/catalog",check=False)
verify("occupied","topic/catalog","Attempt a second checkout of an occupied branch",
[True,False],[occupied.returncode != 0,conflict.exists()])
(topic/"notes.txt").write_bytes(b"catalog=draft\n")
run(topic,"add","notes.txt")
verify("index","notes.txt staged only in topic","Read each index and file contents",
[["","notes.txt",""],["catalog=ready","catalog=draft","catalog=ready"]],
[[run(path,"diff","--cached","--name-only") for path in (repo,topic,review)],
[(path/"notes.txt").read_text().strip() for path in (repo,topic,review)]])
refusal = run(repo,"worktree","remove",str(topic),check=False)
verify("dirty_remove","staged change","Attempt ordinary removal from the owning repository",
[True,True],[refusal.returncode != 0,topic.exists()])
run(topic,"-c","user.name=Tutorial Lab","-c","user.email=fixture@example.invalid","commit","--quiet","-m","Update catalog")
for target in (review,topic):
assert target.parent.resolve() == root
run(repo,"worktree","remove",str(target))
verify("cleanup","saved branch and clean worktrees","Remove the two fixtures, then read the branch ref",
[1,"catalog=draft"],[listed(),run(repo,"show","topic/catalog:notes.txt")])
print(json.dumps(dict(version={"python":sys.version.split()[0],"codex":run(repo,"--version",binary=codex),
"git":run(repo,"--version")},codex_sha256=sha256(Path(codex).read_bytes()).hexdigest(),cases=observations)))
if __name__ == "__main__":
main()
- 初始一个目录,添加后有三个。普通清理拒绝已暂存改动,提交并清理后保留功能分支上的内容。
所需环境:Windows、Python 3.12.14、git version 2.54.0.windows.1。
当前源码 SHA256:ff71be6f4edbeedb332887693275c0d81b0ce4dff76ddc845771f6c93c565295
工作树练习 ZIP
含离线 Git 实验、说明和实际结果页。
所需环境:Windows、Python 3.12.14、git version 2.54.0.windows.1。
ZIP SHA256:b950ffb907588517108fc168a82dc9da6119ab059b5f514a32b87794dc538047
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在审查目录对notes.txt做编辑。先读两处 git status,再决定保留改动的方式。
展开参考解答
只有审查目录显示新编辑,普通清理会拒绝删除有改动的目录。