Skip to content

edit 工具稳定性改进:4 重防护机制 #62863

Description

@GH66688

问题背景

edit 工具要求 oldText 参数与文件内容逐字符精确匹配(包括空格、换行),稍有差异就失败。实际使用中经常因 whitespace 不一致导致编辑失败,触发错误报告。

建议方案

1. 空白归一化兜底(核心改进)

在匹配 oldText 之前,对「文件内容」和「oldText」都做空白归一化:

  • 统一换行符(\r\n → \n)
  • 多个空格/制表符压缩为 1 个
  • 去掉首尾空白
  • 可选:忽略空行差异

用归一化后的内容进行匹配,即使有格式差异也能成功。

2. 前置校验步骤

执行 edit 前自动校验:

  • 用 read 读取 oldText 对应的文件内容
  • 与 oldText 做逐字符对比
  • 不一致时提前报错,给出明确提示

3. read 定位增强

除了 offset/limit,增加更友好的定位方式:

  • read file.md line=10 limit=5 — 按行号定位
  • read file.md keyword="目标内容" limit=3 — 按关键词定位

避免手动计算 offset 的误差。

4. 多次小改原则

文档中明确建议:

  • 单次编辑控制在 1-3 行内
  • 批量修改用多次小块 edit 替代一次大块编辑

预期收益

指标 当前 改进后
编辑成功率 ~80% ~99%
用户挫败感
错误报告频率 频繁 罕见

实现优先级

  1. 空白归一化 — 核心兜底,优先级最高
  2. 前置校验 — 低成本高收益
  3. read 定位增强 — 用户体验改进
  4. 文档更新 — 最佳实践说明

技术提示

空白归一化可以参考 git diff 的 whitespace 处理逻辑,或者借鉴 Prettier 的规范化策略。


来源:用户实际使用中的痛点 + 系统性解决方案

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Normal backlog priority with limited blast radius.clawsweeper:fix-shape-clearClawSweeper found a clear likely implementation shape for this issue.clawsweeper:needs-maintainer-reviewClawSweeper marked this issue as needing maintainer review before automation.clawsweeper:needs-product-decisionClawSweeper marked this issue as needing a product or behavior decision.clawsweeper:no-new-fix-prClawSweeper does not recommend queueing a new automated fix PR for this issue.clawsweeper:source-reproClawSweeper found a high-confidence source-level issue reproduction.issue-rating: 🦞 diamond lobsterVery strong issue quality with high-confidence source-level or clear reproduction.staleMarked as stale due to inactivity

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions