Skip to content

Commit eada7bb

Browse files
fix(agents): verify apply_patch removals with an entry-existence contract
A delete and a move source removal recorded success right after remove() resolved, so a delegated bridge that resolved without deleting produced false D/M receipts. Add an authoritative lstat-semantics entryExists contract at the SandboxFsBridge owner boundary (Docker, remote, MXC, OpenShell), wire it into PatchFileOps, and reject any removal whose entry — including a dangling symlink — still exists. Focused delete/move no-op regressions on a memory bridge and the real filesystem, plus a shell-plan unit test for the anchored lstat probe.
1 parent 3929d5e commit eada7bb

14 files changed

Lines changed: 412 additions & 2 deletions

‎extensions/mxc/src/fs-bridge.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,17 @@ class MxcFsBridge implements SandboxFsBridge {
169169
};
170170
}
171171

172+
async entryExists(params: {
173+
filePath: string;
174+
cwd?: string;
175+
signal?: AbortSignal;
176+
}): Promise<boolean> {
177+
const target = this.resolveTarget(params);
178+
// fs-safe Root.exists lstat's the final component, so a dangling symlink is
179+
// still reported as a present entry, mirroring the bridge's uniform contract.
180+
return await (await fsRoot(target.mount.hostRoot)).exists(target.mountRelativePath);
181+
}
182+
172183
private resolveTarget(params: { filePath: string; cwd?: string }): ResolvedMxcPath {
173184
const input = params.filePath.trim();
174185
const cwd = params.cwd?.trim() ? path.resolve(params.cwd) : this.defaultContainerRoot;

‎extensions/openshell/src/fs-bridge.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,25 @@ class OpenShellFsBridge implements SandboxFsBridge {
255255
};
256256
}
257257

258+
async entryExists(params: {
259+
filePath: string;
260+
cwd?: string;
261+
signal?: AbortSignal;
262+
}): Promise<boolean> {
263+
const target = this.resolveTarget(params);
264+
const hostPath = this.requireHostPath(target);
265+
// lstat the entry itself: a still-present dangling symlink is an entry, only
266+
// an absent path reports false. No boundary throw here — resolveTarget already
267+
// bounds the path, and a present final symlink must not be treated as removed.
268+
const stats = await fsPromises.lstat(hostPath).catch((err: unknown) => {
269+
if (isNotFoundError(err)) {
270+
return null;
271+
}
272+
throw err;
273+
});
274+
return stats !== null;
275+
}
276+
258277
private ensureWritable(target: ResolvedMountPath, action: string) {
259278
if (this.sandbox.workspaceAccess !== "rw" || !target.writable) {
260279
throw new Error(`Sandbox path is read-only; cannot ${action}: ${target.containerPath}`);

‎src/agents/agent-tools-agent-config.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ describe("Agent-specific tool filtering", () => {
4242
remove: async () => {},
4343
rename: async () => {},
4444
stat: async () => null,
45+
entryExists: async () => false,
4546
};
4647

4748
function expectReadOnlyToolSet(toolNames: string[], extraDenied: string[] = []) {

‎src/agents/apply-patch-file-ops.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ export type PatchFileOps = {
3333
remove: (filePath: string) => Promise<void>;
3434
mkdirp: (dir: string) => Promise<void>;
3535
statFile: (filePath: string) => Promise<PersistedFileStat | null>;
36+
/**
37+
* Uniform entry-existence contract: whether any filesystem entry (regular
38+
* file, directory, symlink including dangling, etc.) exists at the path.
39+
* Uses lstat semantics so an entry that survives a removal attempt cannot
40+
* masquerade as absent through a follow-style stat. `statFile` is not enough.
41+
*/
42+
entryExists: (filePath: string) => Promise<boolean>;
3643
};
3744

3845
export async function createPatchTarget(params: {
@@ -71,6 +78,7 @@ export function resolvePatchFileOps(options: ApplyPatchFileOptions): PatchFileOp
7178
remove: (filePath) => bridge.remove({ filePath, cwd: root, force: false }),
7279
mkdirp: (dir) => bridge.mkdirp({ filePath: dir, cwd: root }),
7380
statFile: (filePath) => bridge.stat({ filePath, cwd: root }),
81+
entryExists: (filePath) => bridge.entryExists({ filePath, cwd: root }),
7482
},
7583
});
7684
}
@@ -99,6 +107,7 @@ export function resolvePatchFileOps(options: ApplyPatchFileOptions): PatchFileOp
99107
await fs.mkdir(dir, { recursive: true });
100108
},
101109
statFile: (filePath) => statPatchFile(filePath),
110+
entryExists: (filePath) => entryExistsAtPath(filePath),
102111
},
103112
});
104113
}
@@ -156,6 +165,12 @@ export function resolvePatchFileOps(options: ApplyPatchFileOptions): PatchFileOp
156165
await root.mkdir(relative);
157166
},
158167
statFile: (filePath) => statPatchFile(filePath),
168+
entryExists: async (filePath) => {
169+
const relative = toRelativeSandboxPath(options.cwd, filePath);
170+
// fs-safe Root.stat is lstat-based, so a dangling symlink still reports
171+
// present — the authoritative absence contract for removal receipts.
172+
return await (await rootPromise).exists(relative);
173+
},
159174
},
160175
});
161176
}
@@ -181,6 +196,24 @@ async function statPatchFile(absolutePath: string): Promise<PersistedFileStat |
181196
}
182197
}
183198

199+
async function entryExistsAtPath(absolutePath: string): Promise<boolean> {
200+
try {
201+
await fs.lstat(absolutePath);
202+
return true;
203+
} catch (error) {
204+
if (
205+
error &&
206+
typeof error === "object" &&
207+
"code" in error &&
208+
((error as { code?: unknown }).code === "ENOENT" ||
209+
(error as { code?: unknown }).code === "ENOTDIR")
210+
) {
211+
return false;
212+
}
213+
throw error;
214+
}
215+
}
216+
184217
class PatchCreateExistsSignal extends Error {}
185218

186219
function withPatchMemoryWriteProvenance(params: {

‎src/agents/apply-patch-verification.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ function createVerificationSandbox(initialFiles: Record<string, string>) {
4949
? null
5050
: { type: "file", size: Buffer.byteLength(contents), mtimeMs: 0 };
5151
},
52+
entryExists: async ({ filePath }) => files.has(filePath),
5253
};
5354
return {
5455
files,
@@ -93,4 +94,41 @@ describe("applyPatch write verification", () => {
9394
"ApplyPatch verification failed for new.txt",
9495
);
9596
});
97+
98+
it("rejects a delete whose delegated remove resolves without deleting the entry", async () => {
99+
const sandbox = createVerificationSandbox({ "source.txt": "x\n" });
100+
// Simulate a delegated remove that resolves but leaves the entry behind.
101+
vi.spyOn(sandbox.bridge, "remove").mockImplementation(async () => {});
102+
103+
const patch = `*** Begin Patch
104+
*** Delete File: source.txt
105+
*** End Patch`;
106+
107+
await expect(applyPatch(patch, sandbox.options)).rejects.toThrow(
108+
"ApplyPatch verification failed for source.txt: the entry still exists after removal.",
109+
);
110+
expect(sandbox.files.has("/sandbox/source.txt")).toBe(true);
111+
});
112+
113+
it("rejects a move whose delegated source removal resolves without deleting", async () => {
114+
const sandbox = createVerificationSandbox({ "source.txt": "foo\nbar\n" });
115+
// The destination write is verified, but the source removal is a no-op, so
116+
// the move must not report success while both entries exist.
117+
vi.spyOn(sandbox.bridge, "remove").mockImplementation(async () => {});
118+
119+
const patch = `*** Begin Patch
120+
*** Update File: source.txt
121+
*** Move to: dest.txt
122+
@@
123+
foo
124+
-bar
125+
+baz
126+
*** End Patch`;
127+
128+
await expect(applyPatch(patch, sandbox.options)).rejects.toThrow(
129+
"ApplyPatch verification failed for source.txt: the entry still exists after removal.",
130+
);
131+
expect(sandbox.files.has("/sandbox/dest.txt")).toBe(true);
132+
expect(sandbox.files.has("/sandbox/source.txt")).toBe(true);
133+
});
96134
});

‎src/agents/apply-patch-write-verification.host-fs.proof.test.ts‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,17 @@ function realFsBridge(root: string): SandboxFsBridge {
8484
await fs.mkdir(toAbsolute(filePath), { recursive: true });
8585
},
8686
stat: async ({ filePath }) => stat(filePath),
87+
entryExists: async ({ filePath }) => {
88+
try {
89+
await fs.lstat(toAbsolute(filePath));
90+
return true;
91+
} catch (error) {
92+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
93+
return false;
94+
}
95+
throw error;
96+
}
97+
},
8798
};
8899
}
89100

@@ -156,4 +167,121 @@ describe("applyPatch write verification on a real filesystem", () => {
156167
// The corrupted bytes are really on disk: no false-success receipt.
157168
expect(await fs.readFile(path.join(dir, "source.txt"), "utf8")).toBe("corrupted");
158169
});
170+
171+
it("persists a delete and a move source removal on a real filesystem", async () => {
172+
const dir = await makeTempDir();
173+
await fs.writeFile(path.join(dir, "doomed.txt"), "x\n", "utf8");
174+
await fs.writeFile(path.join(dir, "mover.txt"), "foo\nbar\n", "utf8");
175+
176+
const patch = `*** Begin Patch
177+
*** Delete File: doomed.txt
178+
*** Update File: mover.txt
179+
*** Move to: moved.txt
180+
@@
181+
foo
182+
-bar
183+
+baz
184+
*** End Patch`;
185+
186+
const result = await applyPatch(patch, { cwd: dir, workspaceOnly: false });
187+
188+
expect(result.summary.deleted).toContain("doomed.txt");
189+
expect(result.summary.modified).toContain("moved.txt");
190+
await expect(fs.lstat(path.join(dir, "doomed.txt"))).rejects.toThrow();
191+
await expect(fs.lstat(path.join(dir, "mover.txt"))).rejects.toThrow();
192+
expect(await fs.readFile(path.join(dir, "moved.txt"), "utf8")).toBe("foo\nbaz\n");
193+
});
194+
195+
it("rejects a delete whose real remove leaves the entry behind", async () => {
196+
const dir = await makeTempDir();
197+
const bridge = realFsBridge(dir);
198+
// A remove that resolves without deleting the entry.
199+
const noOpRemoveBridge: SandboxFsBridge = {
200+
...bridge,
201+
remove: async () => {},
202+
};
203+
204+
await fs.writeFile(path.join(dir, "source.txt"), "x\n", "utf8");
205+
206+
const patch = `*** Begin Patch
207+
*** Delete File: source.txt
208+
*** End Patch`;
209+
210+
await expect(
211+
applyPatch(patch, { cwd: dir, sandbox: { root: dir, bridge: noOpRemoveBridge } }),
212+
).rejects.toThrow(
213+
"ApplyPatch verification failed for source.txt: the entry still exists after removal.",
214+
);
215+
expect(await fs.readFile(path.join(dir, "source.txt"), "utf8")).toBe("x\n");
216+
});
217+
218+
it("rejects a move whose real source removal leaves the source behind", async () => {
219+
const dir = await makeTempDir();
220+
const bridge = realFsBridge(dir);
221+
const noOpRemoveBridge: SandboxFsBridge = {
222+
...bridge,
223+
remove: async () => {},
224+
};
225+
226+
await fs.writeFile(path.join(dir, "source.txt"), "foo\nbar\n", "utf8");
227+
228+
const patch = `*** Begin Patch
229+
*** Update File: source.txt
230+
*** Move to: dest.txt
231+
@@
232+
foo
233+
-bar
234+
+baz
235+
*** End Patch`;
236+
237+
await expect(
238+
applyPatch(patch, { cwd: dir, sandbox: { root: dir, bridge: noOpRemoveBridge } }),
239+
).rejects.toThrow(
240+
"ApplyPatch verification failed for source.txt: the entry still exists after removal.",
241+
);
242+
// The verified destination is really on disk, and the unverified source
243+
// removal did not happen — both entries exist, so no success receipt.
244+
expect(await fs.readFile(path.join(dir, "dest.txt"), "utf8")).toBe("foo\nbaz\n");
245+
expect(await fs.readFile(path.join(dir, "source.txt"), "utf8")).toBe("foo\nbar\n");
246+
});
247+
248+
it("treats a still-present dangling symlink as a removal verification failure", async () => {
249+
const dir = await makeTempDir();
250+
const bridge = realFsBridge(dir);
251+
// `stat` follows symlinks and would report this dangling link as absent;
252+
// the entry-existence check must use lstat semantics and reject the removal.
253+
const noOpRemoveBridge: SandboxFsBridge = {
254+
...bridge,
255+
remove: async () => {},
256+
};
257+
258+
await fs.symlink(path.join(dir, "missing-target.txt"), path.join(dir, "dangling.txt"));
259+
260+
const patch = `*** Begin Patch
261+
*** Delete File: dangling.txt
262+
*** End Patch`;
263+
264+
await expect(
265+
applyPatch(patch, { cwd: dir, sandbox: { root: dir, bridge: noOpRemoveBridge } }),
266+
).rejects.toThrow(
267+
"ApplyPatch verification failed for dangling.txt: the entry still exists after removal.",
268+
);
269+
await expect(fs.readlink(path.join(dir, "dangling.txt"))).resolves.toBe(
270+
path.join(dir, "missing-target.txt"),
271+
);
272+
});
273+
274+
it("verifies a real delete of a dangling symlink succeeds", async () => {
275+
const dir = await makeTempDir();
276+
await fs.symlink(path.join(dir, "missing-target.txt"), path.join(dir, "dangling.txt"));
277+
278+
const patch = `*** Begin Patch
279+
*** Delete File: dangling.txt
280+
*** End Patch`;
281+
282+
const result = await applyPatch(patch, { cwd: dir, workspaceOnly: false });
283+
284+
expect(result.summary.deleted).toEqual(["dangling.txt"]);
285+
await expect(fs.lstat(path.join(dir, "dangling.txt"))).rejects.toThrow();
286+
});
159287
});

‎src/agents/apply-patch.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ function createMemoryPatchSandbox(
8787
? null
8888
: { type: "file", size: Buffer.byteLength(contents), mtimeMs: 0 };
8989
},
90+
entryExists: async ({ filePath }) => files.has(filePath),
9091
mkdirp,
9192
};
9293
return {

‎src/agents/apply-patch.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,14 @@ async function applyPatch(input: string, options: ApplyPatchOptions): Promise<Ap
207207

208208
if (hunk.kind === "delete") {
209209
const target = await resolvePatchPath(hunk.path, options, PATH_ALIAS_POLICIES.unlinkTarget);
210-
await withFileMutationQueue(target.resolved, () => fileOps.remove(target.resolved));
210+
await withFileMutationQueue(target.resolved, async () => {
211+
await fileOps.remove(target.resolved);
212+
await verifyPatchEntryRemoved({
213+
ops: fileOps,
214+
filePath: target.resolved,
215+
display: target.display,
216+
});
217+
});
211218
recordSummary(summary, seen, "deleted", target.display);
212219
continue;
213220
}
@@ -255,6 +262,11 @@ async function applyPatch(input: string, options: ApplyPatchOptions): Promise<Ap
255262
content: applied,
256263
});
257264
await fileOps.remove(target.resolved);
265+
await verifyPatchEntryRemoved({
266+
ops: fileOps,
267+
filePath: target.resolved,
268+
display: target.display,
269+
});
258270
}
259271
if (!noOpPaths.has(target.display)) {
260272
recordSummary(
@@ -305,6 +317,21 @@ async function verifyPatchTargetPersisted(params: {
305317
}
306318
}
307319

320+
async function verifyPatchEntryRemoved(params: {
321+
ops: PatchFileOps;
322+
filePath: string;
323+
display: string;
324+
}): Promise<void> {
325+
// A removal receipt must prove the entry is really gone. entryExists uses
326+
// lstat semantics, so a still-present entry — including a dangling symlink
327+
// that a follow-style stat would report as absent — fails the check.
328+
if (await params.ops.entryExists(params.filePath)) {
329+
throw new Error(
330+
`ApplyPatch verification failed for ${params.display}: the entry still exists after removal. Inspect the target and retry.`,
331+
);
332+
}
333+
}
334+
308335
function recordSummary(
309336
summary: ApplyPatchSummary,
310337
seen: {

0 commit comments

Comments
 (0)