Skip to content

历史记录

历史记录看似简单,但做好了是个体力活。去重、大文件存储、跨会话查询……Claude Code 的方案不花哨但够用。

数据结构

三个核心类型:

LogEntry(磁盘格式)

typescript
interface LogEntry {
  displayText: string       // 显示文本
  pastedContent?: ref[]     // 粘贴内容引用
  timestamp: number         // 时间戳
  projectId: string         // 项目标识
  sessionId?: string        // 会话 ID
}

HistoryEntry(内存格式)

反序列化后的表示,加上一些运行时计算字段。

StoredPastedContent

大段粘贴内容的存储结构,支持 inline 和 hash 引用两种模式。小内容直接存,大内容算 hash 存到独立文件。

核心函数

getHistory()

异步生成器,逐条产出历史记录:

typescript
async function* getHistory() {
  // 优先当前会话的记录
  // 然后按时间倒序返回其他记录
}

用 generator 而不是一次性返回数组,是因为历史可能很长,按需加载更省内存。

addToHistory()

同步函数,支持字符串或 HistoryEntry:

typescript
addToHistory(entry: string | HistoryEntry): void

注意:环境变量 CLAUDE_CODE_SKIP_PROMPT_HISTORY=true 时跳过记录。CI/CD 环境下不需要记历史。

存储架构

~/.claude/
├── history.jsonl          # 历史记录,JSONL 格式
└── paste-store/           # 大内容存储
    ├── abc123.txt         # 按 hash 命名
    └── def456.txt

JSONL(每行一个 JSON)是个好选择——追加写入快,不用解析整个文件就能读最新记录。

去重

基于 displayText 做去重,确保用户看到的历史列表没有重复项。