coding-agent-internals

代码编辑 — 实现方式对比

三个层次

Level 1: 纯文本替换

Agent 用字符串匹配定位目标代码,执行 str_replace。

Agent 实现方式
Claude Code Read/Write 工具,纯文本替换
Codex 纯文本替换
Hermes 纯文本替换
OpenCode 纯文本替换
Cursor 基于 VS Code 编辑 API

典型失败场景:

Level 2: Diff(search/replace 块)

Agent 生成 diff 形式的编辑块,由工具自己的 patcher 应用。

Agent 实现方式
Aider SEARCH/REPLACE 块(另有可选 unified diff,--edit-format udiff);Aider 自己应用编辑,不使用 git apply

优点:只输出改动部分,比整文件重写省 token,且能一次改多处 缺点:锚点文本仍需精确匹配,缩进不一致时会失败

来源:https://aider.chat/docs/more/edit-formats.html

Level 3: Hash 锚定 + AST 感知

用内容的 hash 值作为锚点定位代码,结合 AST 理解代码结构。

Agent 实现方式
omp Hash 锚定编辑(hashline)+ ast_edit + ast_grep

Hash 锚定原理:

  1. 读取文件时,为每行生成内容 hash
  2. 编辑时,模型引用 hash 而非行号或文本
  3. 如果文件已被修改(hash 不匹配),拒绝执行 patch,防止覆盖
  4. omp 上游 README 自报数据:Grok 4 Fast 输出 token −61%(厂商数据,非本仓库实测)——https://github.com/can1357/oh-my-pi#readme

AST 感知编辑:

对比总结

维度 纯文本替换 Diff(search/replace) Hash+AST
精确度 低 中 高
whitespace 问题 严重 中等 无
stale file 保护 无 无 有(hash 校验)
token 效率 低 中 高(hash 短于文本)
实现复杂度 低 中 高
支持 agent 数量 大多数 少数 仅 omp

待补充