Worktrees 与会话管理
20.1 Git worktree 是什么
Section titled “20.1 Git worktree 是什么”Git worktree 是 Git 的原生功能,允许同一仓库的多个工作目录同时存在,各自有独立的分支和工作区。
Codex 中 worktree 的价值:让多个 live thread 同时改同一批文件而不互相踩。
20.2 为什么需要 worktree
Section titled “20.2 为什么需要 worktree”官方 best practices 在“常见误区”中明确:
Running live threads on the same files without using git worktrees.
如果你同时开两个 Codex thread,都在改 src/auth/ 下的文件,会:
- 互相覆盖
- diff 混乱
- 测试结果不可信
用 worktree 隔离后,每个 thread 在独立目录工作,完成后合并即可。
20.3 何时用 worktree
Section titled “20.3 何时用 worktree”- 多个 live thread 改同一批文件
- Automation 在后台跑,你同时在前台开发
- Sub-agent 并行探索多个方案
- 想试验一个改动但不影响当前工作区
20.4 在 Codex App 中创建 worktree
Section titled “20.4 在 Codex App 中创建 worktree”Codex App UI 让 worktree 管理最简单:
- 在 thread 界面创建 worktree
- pin thread 方便后续找到
20.5 CLI 下手动创建 worktree
Section titled “20.5 CLI 下手动创建 worktree”# 在仓库根目录git worktree add ../codex-feature-x -b feature-x
# 进入 worktree 工作cd ../codex-feature-x
# 在这里启动 Codexcodex
# 完成后回到主仓库合并cd -git merge feature-x
# 清理 worktreegit worktree remove ../codex-feature-x20.6 会话管理原则
Section titled “20.6 会话管理原则”官方 best practices:
Keep one thread per coherent unit of work. If the work is still part of the same problem, staying in the same thread is often better because it preserves the reasoning trail. Fork only when the work truly branches.
核心原则:一个 session 对应一个相对完整的任务。
| 情况 | 建议 |
|---|---|
| 任务还在同一问题里 | 留在同一线程(保留推理过程) |
| 任务分叉 | fork 新线程 |
| 探索性子任务 | 用 subagent |
| 一个项目所有任务混在一起 | ❌ 不要这样,上下文会臃肿 |
20.7 关键会话命令
Section titled “20.7 关键会话命令”| 命令 | 作用 |
|---|---|
/resume |
恢复已保存的对话 |
/fork |
从当前对话分叉新线程(保留原 transcript) |
/compact |
精简长对话,生成摘要版本 |
/status |
查看当前 session 状态 |
/export session.json |
导出会话 |
/load session.json |
加载会话 |
注:Codex 也会自动 compact,但你可以在对话变长时手动
/compact。
20.8 长任务 session 管理
Section titled “20.8 长任务 session 管理”长任务(如跨天重构)的会话管理建议:
- 每天结束时
/export session.json保存 - 第二天
/load session.json继续 - 上下文臃肿时
/compact - 任务分叉时
/fork - 主线只推进核心判断,子任务用 subagent
20.9 Codex App 的 thread 管理
Section titled “20.9 Codex App 的 thread 管理”Codex App UI 让 thread 管理最方便:
- pin thread:重要线程置顶
- 创建 worktree:每个 thread 独立工作区
- 可视化切换:比 CLI 直观
- OpenAI 官方 Codex best practices——session 管理、worktree、常见误区
- 官方 git worktrees 文档
- CSDN《Codex 完整指南(四)》——
/resume/fork/compact/status命令 - 编程指北 csguide.cn——
/export/load会话持久化