使用 Git 提交作为 Claude Code 的记忆

发布: (2026年4月21日 GMT+8 17:47)
4 分钟阅读
原文: Dev.to

Source: Dev.to

问题

Claude Code 的上下文窗口是个隐患。会话运行时间越长,你就越需要付费重新读取自己的对话历史,模型在早期上下文上漂移的可能性也越大。

  • 上下文快速累积 在长任务中。
  • 早期的决策被埋没。
  • 令牌成本上升。
  • /clear 会清除所有内容,包括有用的状态。
  • 在同一会话中切换任务会导致上下文泄漏。

大多数人要么让会话膨胀,要么使用 /clear 丢失所有内容。

解决方案:将 Git 作为记忆层

将 Git 提交信息视为免费、持久、可搜索的上下文。编写良好的提交正文可以成为会话摘要,能够在 /clear 后仍然保留,存储成本为零,并自然融入你的工作流。

1. 一个任务 → 一个 worktree → 一个分支

git worktree add ../task-foo -b task/foo

每个任务拥有自己的分支和工作目录,防止上下文泄漏。 在该 worktree 中打开 Claude Code。

2. 提交正文会话摘要

在每个会话结束时使用丰富的提交格式:

feat: add user auth flow

what: JWT‑based auth with refresh token rotation
why: existing session cookie approach didn't work cross‑subdomain
tried: httpOnly cookie sharing — blocked by Safari ITP
next: wire up logout endpoint (separate task)

triednext 字段捕获代码之外的推理。 你不需要手动编写——让 Claude Code 执行 commit,它会自动遵循该格式(见下文的“提交格式”章节)。

3. 会话启动定位

当你在 worktree 中打开 Claude Code 时,它会自动运行:

git log -5 --format="%s%n%b"

这会读取最近的提交信息,在提出任何问题之前为模型定位。

处理特殊情况

  • 没有提交的探索性会话 – 创建 NOTES.mdSCRATCH.md 文件,进行一次提交,其正文为会话摘要。
  • 细微信息 – 在 worktree 中保留 CONTEXT.md,将其加入 .gitignore,这样它永远不会进入仓库;它仅本地存在,删除 worktree 时即消失。
  • 多会话任务 – 每个会话添加自己的提交;一系列提交正文形成持续的日志。

提交格式(必备)

type: short summary

what: what changed
why: motivation
tried: dead ends / rejected approaches
next: follow‑up tasks (if any)

完整工作流图

git worktree add ../task-name -b task/name

Open Claude Code in that worktree
  → Claude reads `git log`, orients automatically

Work on the task

Tell Claude Code: "commit"
  → Claude writes the rich commit message, you review and confirm

/clear  (or close the session)

git worktree remove ../task-name  (when merged)

好处

  • 令牌高效 – 新会话保持小体积。
  • 持久 – 上下文在 /clear 和机器重启后仍然存在。
  • 可搜索git log --grep="auth" 能找到过去的决策。
  • 强制自律 – 编写提交迫使你阐述所做的工作。
  • 零开销工具 – 这仅仅是 Git。

结束语

将提交信息视为下一个 Claude Code 会话的简报文档,而不仅仅是变更日志条目。

你有不同的 Claude Code 上下文管理方法吗?我很想听听你的想法。

0 浏览
Back to Blog

相关文章

阅读更多 »