feat: 升级至 v0.3.12 — 文件与代码类工具全面优化(16 项)

【阶段一 · 紧急修复 F1】
- F1-1 file_editor regex 计数 bug:强制 g 标志 + 同一 RegExp 实例做 match+replace
- F1-2 code_search 统一 safeResolvePath(含路径遍历 + MEMORY.md 拦截)
- F1-3 git_commit amend 模式:message 可选 + --no-edit 防止编辑器 hang
- F1-4 write_file append 模式原子化:显式 open(O_APPEND)+write+fsync+close

【阶段二 · 增强现有工具 F2】
- F2-1 read_file 智能编码检测:BOM(UTF-8/UTF-16 LE/BE) + GBK 降级
- F2-2 read_file 支持 tail 模式(读取末尾 N 行,适用日志)
- F2-3 search_files 二进制过滤 + 智能编码检测
- F2-4 search_files 多 glob 匹配(逗号分隔,如 *.ts,*.js)
- F2-5 file_editor 新增 find_replace 操作(字面量替换,规避正则歧义)
- F2-6 file_editor regex 支持跨行匹配(multiline 参数)
- F2-7 file_editor 新增 backup 参数(编辑前 .bak 备份)

【阶段三 · 新增工具 F3】
- F3-1 file_move:双路径校验 + overwrite + 自动建父目录 + rename 原子
- F3-2 file_info:大小/时间/类型/编码/二进制/权限位

【阶段四 · 优化 F4】
- F4-1 diff_viewer Uint32Array→Uint16Array(省一半内存)+ safeResolvePath + 智能编码
- F4-2 错误处理统一:diff-viewer/file-editor/code-search catch 块改用 extractErrorMessage

【阶段五 · 验证 F5】
- tsc --noEmit 类型检查通过
- 人工审查通过:路径校验/错误处理/原子性/资源释放/权限策略/导出注册

工具数量:13 → 15(新增 file_move / file_info)
This commit is contained in:
2026-07-21 16:08:39 +08:00
parent 8973ea6d47
commit 058ee2de36
12 changed files with 586 additions and 100 deletions
+122 -21
View File
@@ -33,7 +33,7 @@ export class FileEditorTool implements IMetonaTool {
readonly definition: MetonaToolDef = {
name: 'file_editor',
description:
'Edit a file with precision. Supports operations: replace (replace lines), insert (insert at line), delete (delete lines), regex (regex replace in range). More efficient than write_file for targeted edits. Supports dry_run mode for preview. File size limit: 10MB.',
'Edit a file with precision. Supports operations: replace (replace lines), insert (insert at line), delete (delete lines), regex (regex replace in range), find_replace (literal string replace, avoids regex ambiguity). More efficient than write_file for targeted edits. Supports dry_run mode for preview, multiline regex matching, and automatic .bak backup. File size limit: 10MB.',
parameters: {
type: 'object',
properties: {
@@ -41,14 +41,19 @@ export class FileEditorTool implements IMetonaTool {
operation: {
type: 'string',
description: 'Edit operation',
enum: ['replace', 'insert', 'delete', 'regex'],
enum: ['replace', 'insert', 'delete', 'regex', 'find_replace'],
},
start_line: { type: 'number', description: 'Start line number (1-indexed). Used by replace/insert/delete/regex' },
end_line: { type: 'number', description: 'End line number (inclusive). Used by replace/delete' },
end_line: { type: 'number', description: 'End line number (inclusive). Used by replace/delete/regex' },
content: { type: 'string', description: 'New content for replace/insert operations' },
pattern: { type: 'string', description: 'Regex pattern for regex operation' },
replacement: { type: 'string', description: 'Replacement string for regex operation' },
flags: { type: 'string', description: 'Regex flags (default "g")' },
flags: { type: 'string', description: 'Regex flags (default "g"). Use "gm" for multiline, "gms" for multiline+dotall' },
multiline: { type: 'boolean', description: 'F2-6: Enable cross-line regex matching. When true, regex is applied to the joined content of the range (not line-by-line). Useful for replacing multi-line code blocks. Default false.' },
find: { type: 'string', description: 'F2-5: Literal string to find for find_replace operation (no regex interpretation)' },
replace: { type: 'string', description: 'F2-5: Replacement string for find_replace operation' },
replace_all: { type: 'boolean', description: 'F2-5: Replace all occurrences (true, default) or only the first (false). For find_replace operation.' },
backup: { type: 'boolean', description: 'F2-7: Save a .bak copy of the original file before editing (default false)' },
dry_run: { type: 'boolean', description: 'Preview mode: return the diff without writing to file (default false)' },
},
required: ['file_path', 'operation'],
@@ -66,8 +71,10 @@ export class FileEditorTool implements IMetonaTool {
return { success: false, error: 'file_path is required' };
}
const filePath = safeResolvePath(args.file_path as string, context.workspacePath);
const operation = args.operation as 'replace' | 'insert' | 'delete' | 'regex';
const operation = args.operation as 'replace' | 'insert' | 'delete' | 'regex' | 'find_replace';
const dryRun = (args.dry_run as boolean) ?? false;
// F2-7: backup 参数 — 编辑前保存 .bak 文件
const backup = (args.backup as boolean) ?? false;
// 文件必须存在(不支持创建新文件,请用 write_file
if (!existsSync(filePath)) {
@@ -143,6 +150,8 @@ export class FileEditorTool implements IMetonaTool {
const pattern = args.pattern as string;
const replacement = (args.replacement as string) ?? '';
const flags = (args.flags as string) ?? 'g';
// F2-6: multiline 参数 — 支持跨行匹配
const multiline = (args.multiline as boolean) ?? false;
if (!pattern) {
return { success: false, error: 'Regex operation requires "pattern" parameter' };
}
@@ -156,27 +165,42 @@ export class FileEditorTool implements IMetonaTool {
return { success: false, error: `end_line (${endLine}) must be >= start_line (${startLine})` };
}
// F1-1 修复: 强制 regex 含 g 标志,保证 match 计数与 replace 结果一致
const effectiveFlags = flags.includes('g') ? flags : flags + 'g';
let regex: RegExp;
try {
regex = new RegExp(pattern, flags);
regex = new RegExp(pattern, effectiveFlags);
} catch (err) {
return { success: false, error: `Invalid regex: ${(err as Error).message}` };
// F4-2: 统一用 extractErrorMessage 提取错误信息
return { success: false, error: `Invalid regex: ${extractErrorMessage(err)}` };
}
// F1.4: 用带 g 标志的正则统计匹配数
const targetLines = lines.slice(startLine - 1, endLine);
const countRegex = new RegExp(pattern, flags.includes('g') ? flags : flags + 'g');
const replacedLines = targetLines.map((line) => {
const matches = line.match(countRegex);
if (matches) replaceCount += matches.length;
return line.replace(regex, replacement);
});
newLines = [
...lines.slice(0, startLine - 1),
...replacedLines,
...lines.slice(endLine),
];
if (multiline) {
// F2-6: 跨行匹配 — 对整个目标内容做正则替换(支持多行代码块替换)
const targetContent = lines.slice(startLine - 1, endLine).join('\n');
const matches = targetContent.match(regex);
if (matches) replaceCount = matches.length;
const replacedContent = targetContent.replace(regex, replacement);
const replacedLines = replacedContent.split('\n');
newLines = [
...lines.slice(0, startLine - 1),
...replacedLines,
...lines.slice(endLine),
];
} else {
// F1-1 修复: 用同一个 regex 实例做 match 计数 + replace 替换(逐行)
const targetLines = lines.slice(startLine - 1, endLine);
const replacedLines = targetLines.map((line) => {
const matches = line.match(regex);
if (matches) replaceCount += matches.length;
return line.replace(regex, replacement);
});
newLines = [
...lines.slice(0, startLine - 1),
...replacedLines,
...lines.slice(endLine),
];
}
affectedRange = { start: startLine, end: endLine };
// 如果没有替换,返回提示
@@ -195,6 +219,56 @@ export class FileEditorTool implements IMetonaTool {
break;
}
case 'find_replace': {
// F2-5: 字面量字符串替换 — 不解析正则元字符,避免歧义
// 适用于精准替换代码片段(如函数名、配置值)
const find = args.find as string;
const replaceStr = (args.replace as string) ?? '';
const replaceAll = (args.replace_all as boolean) ?? true;
if (find === undefined || find === null) {
return { success: false, error: 'find_replace operation requires "find" parameter' };
}
if (find.length === 0) {
return { success: false, error: '"find" must not be empty' };
}
if (replaceAll) {
// 全局替换:用 split + join 统计匹配次数并替换
const parts = originalContent.split(find);
replaceCount = parts.length - 1;
const newContent = parts.join(replaceStr);
newLines = newContent.split('\n');
} else {
// 只替换第一个匹配
const idx = originalContent.indexOf(find);
if (idx >= 0) {
replaceCount = 1;
const newContent = originalContent.slice(0, idx) + replaceStr + originalContent.slice(idx + find.length);
newLines = newContent.split('\n');
} else {
replaceCount = 0;
newLines = lines;
}
}
// find_replace 作用于整个文件,affectedRange 覆盖全部行
affectedRange = { start: 1, end: lines.length };
if (replaceCount === 0) {
return {
success: true,
operation,
file_path: args.file_path,
message: 'No matches found for find pattern',
replacements: 0,
affected_range: affectedRange,
dry_run: dryRun,
};
}
break;
}
default:
return { success: false, error: `Unknown operation: ${operation}` };
}
@@ -214,6 +288,24 @@ export class FileEditorTool implements IMetonaTool {
affectedRange.start - 1,
Math.min(affectedRange.end, newLines.length),
).join('\n');
} else if (operation === 'find_replace') {
// F2-5: find_replace 的 dry_run — 只预览第一个匹配附近的内容
// 避免大文件预览整个文件(affectedRange 覆盖全部行)
const firstMatchIdx = originalContent.indexOf(args.find as string);
if (firstMatchIdx >= 0) {
const beforeMatch = originalContent.slice(0, firstMatchIdx);
const matchLine = beforeMatch.split('\n').length;
const contextRadius = 3; // 前后各 3 行
const previewStart = Math.max(1, matchLine - contextRadius);
const previewEnd = Math.min(lines.length, matchLine + contextRadius);
originalPreview = lines.slice(previewStart - 1, previewEnd).join('\n');
const lineDelta = newLines.length - lines.length;
const modifiedEnd = Math.min(newLines.length, previewEnd + lineDelta);
modifiedPreview = newLines.slice(previewStart - 1, Math.max(previewStart - 1, modifiedEnd)).join('\n');
} else {
originalPreview = '';
modifiedPreview = '';
}
} else {
// replace/delete/regex: 原文件取 [start-1, end) 区间
originalPreview = lines.slice(
@@ -254,6 +346,14 @@ export class FileEditorTool implements IMetonaTool {
await mkdir(parentDir, { recursive: true });
}
// F2-7: backup 模式 — 编辑前保存 .bak 文件
// 注意:备份在写入前进行,确保即使写入失败也有原始备份
let backupPath: string | null = null;
if (backup) {
backupPath = `${filePath}.bak`;
await writeFile(backupPath, originalContent, 'utf-8');
}
const newContent = newLines.join('\n');
// F1.7: 原子写入 - 临时文件 + rename
const tmpPath = `${filePath}.tmp_${Date.now()}`;
@@ -277,6 +377,7 @@ export class FileEditorTool implements IMetonaTool {
lines_before: lines.length,
lines_after: newLines.length,
bytes_written: Buffer.byteLength(newContent, 'utf-8'),
backup_path: backupPath, // F2-7: 备份文件路径(null 表示未备份)
};
} catch (err) {
return { success: false, error: extractErrorMessage(err) };