Skip to content

Non-invasive MCP accelerator plugin for Google Antigravity (CLI/Desktop/IDE): cuts LLM turns (-34%), token quota (-31%), and upload traffic (-40%) without affecting native UI or diffs.

fix(apply-edits): serialize in-process commits, reject stale snapshots, and report rollback failures (#102)

0x7bb3c0b334dc73
diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjs
index 9d96489..02735fe 100755
--- a/dist/mcp-server.mjs
+++ b/dist/mcp-server.mjs
@@ -3295,7 +3295,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();
@@ -3337,6 +3370,7 @@ async function commitPlannedWrites(plans) {
await fs3.unlink(tmpPath);
} catch {
}
+ if (createdDirSet.has(target)) throw renameErr;
written.push(plan);
if (plan.originalSymlinkTarget) {
try {
@@ -3355,6 +3389,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;
@@ -3369,18 +3404,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) {
@@ -4396,7 +4445,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
};
}
diff --git a/src/tools/apply-edits.ts b/src/tools/apply-edits.ts
index 42a45b3..87960a1 100644
--- a/src/tools/apply-edits.ts
+++ b/src/tools/apply-edits.ts
@@ -901,7 +901,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>();
@@ -948,6 +989,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
@@ -969,6 +1013,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]!;
@@ -983,21 +1028,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}`);
}
}
@@ -2254,7 +2311,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,
};
}
diff --git a/test/apply-edits.test.ts b/test/apply-edits.test.ts
index 5f73f21..fa0e4b4 100644
--- a/test/apply-edits.test.ts
+++ b/test/apply-edits.test.ts
@@ -891,6 +891,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 });
@@ -997,7 +1069,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 {
@@ -1016,6 +1090,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