Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 54 additions & 5 deletions dist/mcp-server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3248,7 +3248,40 @@ async function findMissingAncestorDirs(dir) {
}
return missing;
}
var pendingEditCommit = Promise.resolve();
async function commitPlannedWrites(plans) {
const previous = pendingEditCommit;
let release;
pendingEditCommit = new Promise((resolve) => {
release = resolve;
});
await previous;
try {
for (const plan of plans) {
if (plan.isNoOp) continue;
const target = plan.writeTargetPath;
const current = await fs3.lstat(target).catch((err) => {
if (err.code === "ENOENT") return null;
throw err;
});
let matches = false;
if (plan.originalSymlinkTarget !== null && plan.originalSymlinkTarget !== void 0) {
matches = current?.isSymbolicLink() === true && await fs3.readlink(target) === plan.originalSymlinkTarget;
} else if (!plan.existed) {
matches = current === null;
} else if (current?.isFile() && plan.originalBuffer !== null) {
matches = current.size === plan.originalBuffer.length && (await fs3.readFile(target)).equals(plan.originalBuffer);
}
if (!matches) {
throw new Error(`Edit conflict: ${plan.relPath} changed after planning; re-read and retry`);
}
}
await writePlannedFiles(plans);
} finally {
release();
}
}
async function writePlannedFiles(plans) {
const written = [];
const createdDirs = [];
const createdDirSet = /* @__PURE__ */ new Set();
Expand Down Expand Up @@ -3290,6 +3323,7 @@ async function commitPlannedWrites(plans) {
await fs3.unlink(tmpPath);
} catch {
}
if (createdDirSet.has(target)) throw renameErr;
written.push(plan);
if (plan.originalSymlinkTarget) {
try {
Expand All @@ -3308,6 +3342,7 @@ async function commitPlannedWrites(plans) {
}
}
} catch (err) {
const rollbackFailures = [];
for (let i = written.length - 1; i >= 0; i--) {
const item = written[i];
const target = item.writeTargetPath;
Expand All @@ -3322,18 +3357,32 @@ async function commitPlannedWrites(plans) {
await fs3.chmod(target, item.originalMode);
}
} else if (!item.existed) {
await fs3.unlink(target);
await fs3.unlink(target).catch((unlinkErr) => {
if (unlinkErr.code !== "ENOENT") throw unlinkErr;
});
}
} catch {
} catch (rollbackErr) {
rollbackFailures.push(`${item.relPath}: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`);
}
}
for (let i = createdDirs.length - 1; i >= 0; i--) {
try {
await fs3.rmdir(createdDirs[i]);
} catch {
} catch (cleanupErr) {
if (cleanupErr.code !== "ENOENT") {
rollbackFailures.push(`${createdDirs[i]}: ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`);
}
}
}
throw err;
const message = err instanceof Error ? err.message : String(err);
if (rollbackFailures.length > 0) {
throw new Error(formatErrorBulletsWithinBytes(
"Write failed (rollback incomplete; inspect affected files before retrying):",
[`Original write error: ${message}`, ...rollbackFailures],
DEFAULT_INLINE_MAX_BYTES
));
}
throw new Error(`Write failed (changes rolled back): ${message}`);
}
}
function corruptedEditsError(items) {
Expand Down Expand Up @@ -4349,7 +4398,7 @@ Example: ${TOOL_VALIDATION_EXAMPLES.apply_edits}`;
await commitPlannedWrites(plans);
} catch (err) {
return {
text: `Write failed (changes rolled back): ${err instanceof Error ? err.message : String(err)}`,
text: truncateWithByteNotice(err instanceof Error ? err.message : String(err), DEFAULT_INLINE_MAX_BYTES),
isError: true
};
}
Expand Down
71 changes: 64 additions & 7 deletions src/tools/apply-edits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,48 @@ async function findMissingAncestorDirs(dir: string): Promise<string[]> {
return missing;
}

// Serialize commits only within this Node/MCP process. Separate CLI processes
// still validate snapshots but do not share this in-memory lock.
let pendingEditCommit = Promise.resolve();

async function commitPlannedWrites(plans: PlannedWrite[]): Promise<void> {
const previous = pendingEditCommit;
let release!: () => void;
pendingEditCommit = new Promise<void>((resolve) => {
release = resolve;
});
await previous;
try {
// Validate snapshots before writing any file. A queued edit may have been
// planned against content that an earlier request has since changed.
for (const plan of plans) {
if (plan.isNoOp) continue;
const target = plan.writeTargetPath;
const current = await fs.lstat(target).catch((err: NodeJS.ErrnoException) => {
if (err.code === "ENOENT") return null;
throw err;
});
let matches = false;
if (plan.originalSymlinkTarget !== null && plan.originalSymlinkTarget !== undefined) {
matches = current?.isSymbolicLink() === true &&
await fs.readlink(target) === plan.originalSymlinkTarget;
} else if (!plan.existed) {
matches = current === null;
} else if (current?.isFile() && plan.originalBuffer !== null) {
matches = current.size === plan.originalBuffer.length &&
(await fs.readFile(target)).equals(plan.originalBuffer);
}
if (!matches) {
throw new Error(`Edit conflict: ${plan.relPath} changed after planning; re-read and retry`);
}
}
await writePlannedFiles(plans);
} finally {
release();
}
}

async function writePlannedFiles(plans: PlannedWrite[]): Promise<void> {
const written: PlannedWrite[] = [];
const createdDirs: string[] = [];
const createdDirSet = new Set<string>();
Expand Down Expand Up @@ -910,6 +951,9 @@ async function commitPlannedWrites(plans: PlannedWrite[]): Promise<void> {
} catch {
// ignore cleanup failure
}
// An earlier plan may have created this target as a parent directory.
// Do not attempt a direct file write or unlink it as a file on rollback.
if (createdDirSet.has(target)) throw renameErr;
written.push(plan);
if (plan.originalSymlinkTarget) {
// Replace dangling symlink itself instead of following it on fallback write
Expand All @@ -931,6 +975,7 @@ async function commitPlannedWrites(plans: PlannedWrite[]): Promise<void> {
}
}
} catch (err) {
const rollbackFailures: string[] = [];
// Rollback all previously written files
for (let i = written.length - 1; i >= 0; i--) {
const item = written[i]!;
Expand All @@ -945,21 +990,33 @@ async function commitPlannedWrites(plans: PlannedWrite[]): Promise<void> {
await fs.chmod(target, item.originalMode);
}
} else if (!item.existed) {
await fs.unlink(target);
await fs.unlink(target).catch((unlinkErr: NodeJS.ErrnoException) => {
if (unlinkErr.code !== "ENOENT") throw unlinkErr;
});
}
} catch {
// Best-effort rollback
} catch (rollbackErr) {
rollbackFailures.push(`${item.relPath}: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`);
}
}
// Best-effort remove newly created parent directories deepest-first (rmdir never removes non-empty dirs)
for (let i = createdDirs.length - 1; i >= 0; i--) {
try {
await fs.rmdir(createdDirs[i]!);
} catch {
// Ignore ENOENT / ENOTEMPTY / permission errors
} catch (cleanupErr) {
if ((cleanupErr as NodeJS.ErrnoException).code !== "ENOENT") {
rollbackFailures.push(`${createdDirs[i]}: ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`);
}
}
}
throw err;
const message = err instanceof Error ? err.message : String(err);
if (rollbackFailures.length > 0) {
throw new Error(formatErrorBulletsWithinBytes(
"Write failed (rollback incomplete; inspect affected files before retrying):",
[`Original write error: ${message}`, ...rollbackFailures],
DEFAULT_INLINE_MAX_BYTES,
));
}
throw new Error(`Write failed (changes rolled back): ${message}`);
}
}

Expand Down Expand Up @@ -2216,7 +2273,7 @@ export async function runApplyEdits(
await commitPlannedWrites(plans);
} catch (err) {
return {
text: `Write failed (changes rolled back): ${err instanceof Error ? err.message : String(err)}`,
text: truncateWithByteNotice(err instanceof Error ? err.message : String(err), DEFAULT_INLINE_MAX_BYTES),
isError: true,
};
}
Expand Down
77 changes: 76 additions & 1 deletion test/apply-edits.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,78 @@ describe("apply_edits", () => {
assert.equal((await fs.readdir(realSubDir)).some((n) => n.startsWith(".agy-tmp-")), false);
});

it("rejects a stale concurrent edit instead of overwriting a successful edit", async () => {
const dir = await fs.mkdtemp(path.join(tmpDir, "concurrent-"));
const target = path.join(await fs.realpath(dir), "shared.txt");
await fs.writeFile(target, "alpha\nbeta\n");
const originalRead = fs.readFile;
let snapshotReads = 0;
let unblock!: () => void;
const bothRead = new Promise<void>((resolve) => { unblock = resolve; });
fs.readFile = (async (...args: Parameters<typeof originalRead>) => {
const content = await originalRead(...args);
if (String(args[0]) === target && snapshotReads < 2) {
snapshotReads++;
if (snapshotReads === 2) unblock();
await bothRead;
}
return content;
}) as typeof fs.readFile;
const alpha = { cwd: dir, edits: [{ path: "shared.txt", hunks: [{ target: "alpha", replacement: "ALPHA" }] }] };
const beta = { cwd: dir, edits: [{ path: "shared.txt", hunks: [{ target: "beta", replacement: "BETA" }] }] };
let results;
try {
results = await Promise.all([runApplyEdits(alpha), runApplyEdits(beta)]);
} finally {
fs.readFile = originalRead;
}
assert.equal(results.filter((result) => !result.isError).length, 1);
const failed = results.findIndex((result) => result.isError);
assert.match(results[failed]!.text, /Edit conflict/);
assert.doesNotMatch(results[failed]!.text, /changes rolled back/);
const retry = await runApplyEdits(failed === 0 ? alpha : beta);
assert.equal(retry.isError, false);
assert.equal(await fs.readFile(target, "utf8"), "ALPHA\nBETA\n");
});

for (const longDiagnostic of [false, true]) {
it(`reports incomplete rollback within the inline byte cap (long diagnostic: ${longDiagnostic})`, async () => {
const dir = await fs.mkdtemp(path.join(tmpDir, "rollback-fail-"));
const firstFile = path.join(await fs.realpath(dir), "first.txt");
await fs.writeFile(firstFile, "first orig\n");
await fs.writeFile(path.join(dir, "second.txt"), "second orig\n");
const origWriteFile = fs.writeFile;
fs.writeFile = (async (...args: Parameters<typeof origWriteFile>) => {
const p = String(args[0]);
if (path.basename(p).startsWith(".agy-tmp-") && String(args[1]).includes("second mod")) {
throw makeErrnoError("ENOSPC", "write failed");
}
if (p === firstFile) {
throw makeErrnoError("EIO", "restore failed" + (longDiagnostic ? "界".repeat(10000) : ""));
}
return origWriteFile(...args);
}) as typeof fs.writeFile;
try {
const res = await runApplyEdits({
cwd: dir,
edits: [
{ path: "first.txt", hunks: [{ target: "first orig", replacement: "first mod" }] },
{ path: "second.txt", hunks: [{ target: "second orig", replacement: "second mod" }] },
],
});
assert.equal(res.isError, true);
assert.match(res.text, /rollback incomplete/);
assert.match(res.text, /write failed/);
assert.match(res.text, /first\.txt: restore failed/);
assert.doesNotMatch(res.text, /changes rolled back/);
assert.ok(Buffer.byteLength(res.text, "utf8") <= 8800);
} finally {
fs.writeFile = origWriteFile;
}
assert.equal(await fs.readFile(firstFile, "utf8"), "first mod\n");
});
}

it("fails fast on non-ENOENT errors in create without overwriting or deleting existing files", async () => {
const subDir = path.join(tmpDir, "create-non-enoent");
await fs.mkdir(subDir, { recursive: true });
Expand Down Expand Up @@ -970,7 +1042,9 @@ describe("apply_edits", () => {
return origRename(...args);
}) as typeof fs.rename;
fs.writeFile = (async (...args: Parameters<typeof origWriteFile>) => {
if (String(args[0]) === failTarget) throw makeErrnoError("EIO", "EIO");
if (String(args[0]) === failTarget && String(args[1]).includes("mod")) {
throw makeErrnoError("EIO", "EIO");
}
return origWriteFile(...args);
}) as typeof fs.writeFile;
try {
Expand All @@ -989,6 +1063,7 @@ describe("apply_edits", () => {
}
assert.equal((await fs.lstat(danglingLink)).isSymbolicLink(), true);
assert.equal(await fs.readlink(danglingLink), "missing-target.txt");
assert.equal(await fs.readFile(failTarget, "utf8"), "orig\n");
}

// 2. Symlinked parent directory deduplication for new files
Expand Down
Loading