The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): reject V4A Add File onto an existing path
entropy-0xf79cb7722452
diff --git a/tests/tools/test_patch_parser.py b/tests/tools/test_patch_parser.pyindex ea6c56257c4..1cf3eef71eb 100644--- a/tests/tools/test_patch_parser.py+++ b/tests/tools/test_patch_parser.py@@ -435,6 +435,70 @@ class TestValidationPhase:assert result.success is Falseassert "hunk 2" in result.error.lower()+ def test_add_onto_existing_file_fails_and_preserves_contents(self):+ """An Add targeting a path that already exists must fail validation and+ leave the original bytes untouched (no silent overwrite)."""+ patch = """\+*** Begin Patch+*** Add File: exists.py++brand new++content+*** End Patch"""+ ops, err = parse_v4a_patch(patch)+ assert err is None++ original = "def keep_me():\n return 1\n"+ written = {}++ class FakeFileOps:+ def read_file_raw(self, path):+ if path == "exists.py":+ return SimpleNamespace(content=original, error=None)+ return SimpleNamespace(content=None, error=f"File not found: {path}")++ def write_file(self, path, content):+ written[path] = content+ return SimpleNamespace(error=None)++ result = apply_v4a_operations(ops, FakeFileOps())+ assert result.success is False+ assert written == {}, f"No file should have been written, got: {list(written.keys())}"+ assert "already exists" in result.error+ assert "validation failed" in result.error.lower()++ def test_delete_then_add_same_path_still_validates(self):+ """A patch that deletes a file and re-adds the same path (a legitimate+ rewrite idiom) must not trip the Add-onto-existing guard: the earlier+ DELETE frees the path in the validation overlay."""+ patch = """\+*** Begin Patch+*** Delete File: rewrite.py+*** Add File: rewrite.py++fresh = True+*** End Patch"""+ ops, err = parse_v4a_patch(patch)+ assert err is None++ state = {"rewrite.py": "old = True\n"}++ class FakeFileOps:+ def read_file_raw(self, path):+ if path in state:+ return SimpleNamespace(content=state[path], error=None)+ return SimpleNamespace(content=None, error=f"File not found: {path}")++ def delete_file(self, path):+ state.pop(path, None)+ return SimpleNamespace(error=None)++ def write_file(self, path, content, pre_content=None):+ state[path] = content+ return SimpleNamespace(error=None)++ result = apply_v4a_operations(ops, FakeFileOps())+ assert result.success is True, result.error+ assert state["rewrite.py"] == "fresh = True"+class TestApplyDelete:"""Tests for _apply_delete producing a real unified diff."""@@ -569,6 +633,9 @@ class TestV4ALspDiagnosticsPropagation:)class FakeFileOps:+ def read_file_raw(self, path):+ return SimpleNamespace(content=None, error=f"File not found: {path}")+def write_file(self, path, content, pre_content=None):return SimpleNamespace(error=None, lsp_diagnostics=diag_block)@@ -621,6 +688,9 @@ class TestV4ALspDiagnosticsPropagation:ops = self._build_ops_writing("foo.py", "x = 1\n")class FakeFileOps:+ def read_file_raw(self, path):+ return SimpleNamespace(content=None, error=f"File not found: {path}")+def write_file(self, path, content, pre_content=None):# lsp_diagnostics omitted entirely (older WriteResult shape).return SimpleNamespace(error=None)@@ -654,6 +724,9 @@ class TestV4ALspDiagnosticsPropagation:}class FakeFileOps:+ def read_file_raw(self, path):+ return SimpleNamespace(content=None, error=f"File not found: {path}")+def write_file(self, path, content, pre_content=None):return SimpleNamespace(error=None, lsp_diagnostics=per_file[path])diff --git a/tools/patch_parser.py b/tools/patch_parser.pyindex 3c9c1c3f37e..39b469d9a93 100644--- a/tools/patch_parser.py+++ b/tools/patch_parser.py@@ -224,7 +224,20 @@ def _validate_operations(operations: List[PatchOperation], file_ops: Any) -> Liselif not src_err: # only a cleanly-validated move updates the overlaypending_content[op.new_path] = src_content if src_content is not None else ""_remove(op.file_path)- # ADD: write_file creates parent directories; no pre-check needed.+ elif op.operation == OperationType.ADD:+ # An Add must create a NEW file. If the target already exists, write_file+ # would clobber it with only the patch's '+' lines and report success,+ # silently destroying the original contents (models frequently confuse Add+ # with Update). Reject it here so the two-phase contract holds, mirroring+ # the MOVE destination guard. Overlay-aware: an Add after a Delete of the+ # same path in this patch stays legal, and the added content enters the+ # overlay so later hunks against it validate.+ if not _read(op.file_path)[1]:+ errors.append(f"{op.file_path}: file already exists — use Update File, not Add File")+ else:+ removed_paths.discard(op.file_path)+ pending_content[op.file_path] = '\n'.join(+ line.content for hunk in op.hunks for line in hunk.lines if line.prefix == '+')if not errors and real_change_count == 0:errors.append("Patch contains no changes (only context lines were provided)")return errors@@ -308,7 +321,13 @@ def _write_file_accepts_pre_content(file_ops: Any) -> bool:def _apply_add(op: PatchOperation, file_ops: Any) -> ApplyResult:- """Create a file from the hunks' '+' lines."""+ """Create a file from the hunks' '+' lines. Fails closed when the target already+ exists: validation confirmed the path was free (or freed by an earlier DELETE in+ this patch, which has already applied by now), so an existing file here is a+ validate/apply race — never clobber."""+ read_back = file_ops.read_file_raw(op.file_path)+ if not read_back.error:+ return _fail(f"{op.file_path}: file already exists — use Update File, not Add File")content_lines = [line.content for hunk in op.hunks for line in hunk.lines if line.prefix == '+']result = file_ops.write_file(op.file_path, '\n'.join(content_lines))diff = f"--- /dev/null\n+++ b/{op.file_path}\n" + '\n'.join(f"+{line}" for line in content_lines)