edit_file:描述明确匹配/删行/部分应用语义;实现DP缓冲区复用、CRLF悬空\r修复、降级路径报错可辨识

This commit is contained in:
2026-09-22 20:34:09 +08:00
parent 9e9a7249f5
commit 21f35be85e
2 changed files with 24 additions and 7 deletions
+4 -4
View File
@@ -3,7 +3,7 @@
"type": "function",
"function": {
"name": "edit_file",
"description": "This is a tool for applying edits to an existing file.\n\nBefore using this tool, use the `read_file` tool to understand the file's contents and context.\nTo create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.\n\n`read_file` prefixes each line of its output with a line number right-aligned in a\n6-character field followed by a single tab, then the line's actual content. When you\nderive `old_text` or `new_text` from that output, strip this prefix and keep only what\ncomes after the tab, preserving the original indentation (tabs and spaces) exactly.\nNever include any part of the line number prefix in `old_text` or `new_text`.",
"description": "This is a tool for applying edits to an existing file.\n\nBefore using this tool, use the `read_file` tool to understand the file's contents and context.\nTo create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.\n\nWhen copying text from `read_file` output into `old_text` or `new_text`, strip the line-number prefix and the tab after it, and keep the original indentation exactly.\n\nMatching rules:\n- `old_text` is first matched exactly. If there is no exact match, a fuzzy match tolerating minor whitespace and formatting differences is attempted.\n- If `old_text` matches more than one location (overlapping matches count as separate locations), the edit fails. Include enough surrounding context to make it unique; avoid very short or repetitive `old_text`.\n- If no match is found at all, the edit fails. For very large files the fuzzy stage degrades to per-line whitespace-insensitive exact matching; the error message says so — do not retry the same text, locate with `read_file` by line numbers or use `terminal` with sed.\n\nTo delete a whole line, set `old_text` to that line WITHOUT its trailing newline and `new_text` to an empty string. Otherwise a blank line will be left behind.\n\nEdits are applied in order. If one edit fails, the edits before it are already written to disk and the file has changed: the error message tells you how many were applied. You must call `read_file` again before retrying; do not reuse the previous `old_text` values.",
"parameters": {
"type": "object",
"required": ["path", "edits"],
@@ -14,18 +14,18 @@
},
"edits": {
"type": "array",
"description": "List of edit operations to apply sequentially.",
"description": "List of edit operations to apply sequentially. Each edit finds `old_text` in the file and replaces it with `new_text`. If any edit fails, the edits before it remain applied.",
"items": {
"type": "object",
"required": ["old_text", "new_text"],
"properties": {
"old_text": {
"type": "string",
"description": "The exact text to find in the file. Use enough context to make it unique."
"description": "The text to find in the file. Matched exactly first, then fuzzily (whitespace / minor formatting differences tolerated). Provide enough context to make the match unique; short or repeated snippets are reported as ambiguous. A trailing newline, if present, is stripped before matching; for whole-line deletion omit it."
},
"new_text": {
"type": "string",
"description": "The replacement text."
"description": "The replacement text. Use an empty string together with a trailing-newline-free `old_text` to delete a whole line."
}
}
}
+20 -3
View File
@@ -198,12 +198,19 @@ const COST_REP = 1, COST_INS = 3, COST_DEL = 10, FUZZY_THRESHOLD = 0.8;
const FUZZY_DP_CELL_LIMIT = 8_000_000; // 超大文件跳过 DP,退回逐行 trim 扫描
// normalized Levenshtein 相似度(1 - lev/max_len),先做长度粗筛。
// DP 工作集复用模块级 buffer:lineSimilarity 无递归/无重入(单线程下安全),
// 避免 fuzzyLocate m×n 内层每格新建两个 typed array(触顶时是千万次临时分配)。
let simPrev = null, simCurr = null;
function lineSimilarity(a, b) {
if (a === b) return 1;
const la = a.length, lb = b.length, max = Math.max(la, lb);
if (max === 0) return 1;
if (1 - Math.abs(la - lb) / max < FUZZY_THRESHOLD) return 0;
let prev = new Int32Array(lb + 1), curr = new Int32Array(lb + 1);
if (!simPrev || simPrev.length < lb + 1) {
simPrev = new Int32Array(lb + 1);
simCurr = new Int32Array(lb + 1);
}
let prev = simPrev, curr = simCurr; // 下面的交换只换局部引用,不动模块级变量
for (let j = 0; j <= lb; j++) prev[j] = j;
for (let i = 1; i <= la; i++) {
curr[0] = i;
@@ -332,7 +339,13 @@ function applyEdit(text, edit, i) {
// 尾换行摘除:匹配区间后紧跟 \n(或 CRLF 的 \r\n)时吃掉 new_text 的一个尾换行。
const after = text.charAt(idx + pat.length);
const afterCRLF = after === '\r' && text.charAt(idx + pat.length + 1) === '\n';
if ((after === '\n' || afterCRLF) && repl.endsWith('\n')) repl = repl.slice(0, -1);
if (afterCRLF) {
// 尾随 \r\n 要整对切;只切 \n 会在拼接处留下孤立的 \r
if (repl.endsWith('\r\n')) repl = repl.slice(0, -2);
else if (repl.endsWith('\n')) repl = repl.slice(0, -1);
} else if (after === '\n' && repl.endsWith('\n')) {
repl = repl.slice(0, -1);
}
// CRLF 文件:新内容里的行尾统一成 \r\n。
if (text.includes('\r\n')) repl = repl.replace(/\r?\n/g, '\r\n');
return text.slice(0, idx) + repl + text.slice(idx + pat.length);
@@ -342,9 +355,11 @@ function applyEdit(text, edit, i) {
const oldLines = pat.split('\n');
const oldTrim = oldLines.map(l => l.trim());
let loc = null;
let usedFallback = false;
if (oldLines.length * curLines.length <= FUZZY_DP_CELL_LIMIT) {
loc = fuzzyLocate(curLines, oldTrim);
} else {
usedFallback = true;
// 超大文件降级:逐行 trim 首次命中(旧行为)。
for (let s = 0; s + oldLines.length <= curLines.length; s++) {
let ok2 = true;
@@ -355,7 +370,9 @@ function applyEdit(text, edit, i) {
}
}
if (!loc) {
throw new Error(tag + ': 在文件中找不到 old_text(可能已被之前的 edit 修改)。请重新 read_file 获取最新内容后再试。');
throw new Error(tag + ': 在文件中找不到 old_text(可能已被之前的 edit 修改)。' + (usedFallback
? '文件过大,本次仅走了降级匹配(逐行 trim 精确相等、无相似度容忍):请核对 old_text 与原文是否逐字一致,或改用 read_file 按行号定位后用 terminal 的 sed 编辑,不要以同一文本反复重试。'
: '请重新 read_file 获取最新内容后再试。'));
}
if (loc.ambiguous) {
throw new Error(tag + ': old_text 模糊匹配到多处(第 ' + loc.ambiguous.join(', ') +