import { readFile, stat, realpath } from 'node:fs/promises'; import { atomicWriteFile, encodeTextFile, readTextFile } from './fileUtils.js'; import { hashFileBytes } from './fileState.js'; // Bound the in-memory replacement engine independently of model context size. export const MAX_EDIT_BYTES = 128 * 1024 * 1024; const commits = new Map>(); export async function readEditSnapshot(path: string) { if ((await stat(path)).size > MAX_EDIT_BYTES) throw new Error('文件超过 128 MiB 内存编辑边界;请使用流式转换写入临时文件并校验,不要用 Write 全文覆盖。'); const snapshot = await readTextFile(path); if (snapshot.bytes.length > MAX_EDIT_BYTES) throw new Error('读取期间文件超过编辑边界'); return snapshot; } export async function commitEdit(path: string, snapshot: Awaited>, content: string) { const key = await realpath(path); const previous = commits.get(key) ?? Promise.resolve(); let release!: () => void; const current = new Promise(resolve => { release = resolve; }); commits.set(key, current); await previous; try { return await commitSnapshot(key, snapshot, content); } finally { release(); if (commits.get(key) === current) commits.delete(key); } } async function commitSnapshot(path: string, snapshot: Awaited>, content: string) { const bytes = encodeTextFile(content, snapshot.encoding); if (bytes.length > MAX_EDIT_BYTES) throw new Error('编辑结果超过 128 MiB 内存编辑边界'); const beforeHash = hashFileBytes(snapshot.bytes); if (hashFileBytes(await readFile(path)) !== beforeHash) throw new Error('编辑期间文件已被其他操作修改,未提交;请重新读取后再编辑。'); // Optimistic conflict check, not an OS-wide compare-and-swap guarantee. if (!bytes.equals(snapshot.bytes)) await atomicWriteFile(path, bytes); const afterHash = hashFileBytes(bytes); if (hashFileBytes(await readFile(path)) !== afterHash) throw new Error('提交后文件内容与预期不一致(可能被外部进程改写);请读取核验,不要盲目重复替换。'); return { beforeHash, afterHash }; }