Agent Zero AI framework
Preserve file permissions and ownership when applying editor patches
Alessandroe9384d27483b
diff --git a/plugins/_text_editor/AGENTS.md b/plugins/_text_editor/AGENTS.mdindex 71a61d883..c4bd41f4b 100644--- a/plugins/_text_editor/AGENTS.md+++ b/plugins/_text_editor/AGENTS.md@@ -19,6 +19,7 @@- The remote editor reuses shipped patch and log helpers even when this plugin is disabled; activation still controls local tool discovery and custom WebUI rendering. Removing bundled helper files is not a supported independent-plugin configuration.- Preserve stale-read protection before patch operations.- Validate patch structures before applying edits.+- All three local patch methods preserve the existing file's mode and, when running as root, its UID/GID before atomic replacement. Metadata failures leave the original file intact. New-file ownership follows the executing process; patching does not repair already-root-owned workspaces.- Read back changed regions after writes or patches where the tool contract requires confirmation.- Include the active agent context id in write/patch result metadata when available so canvas consumers can open the changed file in the correct chat context.diff --git a/plugins/_text_editor/README.md b/plugins/_text_editor/README.mdindex e0547df97..2e2c30bee 100644--- a/plugins/_text_editor/README.md+++ b/plugins/_text_editor/README.md@@ -16,6 +16,7 @@ This plugin exposes a native text editing tool that agents can use to inspect fi- **Patch**- Validates edit structures before applying them.- Rejects edits if the file changed since it was last observed.+ - Preserves file permissions and, when running as root, the existing owner and group.- Reads back the affected patch region after applying changes.- **Extension hooks**- Exposes before and after extension points for read, write, and patch operations.diff --git a/plugins/_text_editor/helpers/file_ops.py b/plugins/_text_editor/helpers/file_ops.pyindex 972bf9da2..4232431af 100644--- a/plugins/_text_editor/helpers/file_ops.py+++ b/plugins/_text_editor/helpers/file_ops.py@@ -5,7 +5,7 @@ No agent/tool dependencies — only stdlib + tokens helper."""import os-import shutil+import statimport tempfilefrom typing import TypedDict@@ -343,7 +343,7 @@ def apply_patch(path: str, edits: list[dict]) -> int:total_written += _count_content_lines(edit["content"])edit_idx += 1- shutil.move(tmp_path, path)+ _replace_file(tmp_path, path)return total_writtenexcept Exception:if os.path.exists(tmp_path):@@ -384,7 +384,7 @@ def apply_context_patch_file(path: str, patch_text: str) -> ContextPatchFileResutry:with os.fdopen(fd, "w", encoding="utf-8") as dst:dst.write(result.content)- shutil.move(tmp_path, path)+ _replace_file(tmp_path, path)except Exception:if os.path.exists(tmp_path):os.unlink(tmp_path)@@ -431,7 +431,7 @@ def apply_exact_replace_file(try:with os.fdopen(fd, "w", encoding="utf-8") as dst:dst.write(new_content)- shutil.move(tmp_path, path)+ _replace_file(tmp_path, path)except Exception:if os.path.exists(tmp_path):os.unlink(tmp_path)@@ -449,6 +449,15 @@ def apply_exact_replace_file(# Internal# ------------------------------------------------------------------+def _replace_file(tmp_path: str, path: str) -> None:+ """Keep the existing file's access when publishing a patched version."""+ original = os.stat(path)+ if hasattr(os, "geteuid") and os.geteuid() == 0:+ os.chown(tmp_path, original.st_uid, original.st_gid)+ os.chmod(tmp_path, stat.S_IMODE(original.st_mode))+ os.replace(tmp_path, path)++def _count_content_lines(content: str) -> int:return content.count("\n") + (1 if content and not content.endswith("\n") else 0diff --git a/tests/test_text_editor_context_patch.py b/tests/test_text_editor_context_patch.pyindex df58d55b9..a550d05b8 100644--- a/tests/test_text_editor_context_patch.py+++ b/tests/test_text_editor_context_patch.py@@ -14,6 +14,7 @@ if str(PROJECT_ROOT) not in sys.path:sys.path.insert(0, str(PROJECT_ROOT))from plugins._text_editor.helpers.context_patch import ContextPatchError+from plugins._text_editor.helpers import file_opsfrom plugins._text_editor.helpers.file_ops import (apply_context_patch_file,apply_exact_replace_file,@@ -32,6 +33,59 @@ from plugins._text_editor.helpers.patch_state import ()[email protected]("method", ["line", "context", "exact"])[email protected]("mode", [0o600, 0o640, 0o644, 0o755])+def test_patch_preserves_file_access(tmp_path: Path, method: str, mode: int) -> None:+ target = tmp_path / "sample.txt"+ target.write_text("before\n", encoding="utf-8")+ if hasattr(os, "geteuid") and os.geteuid() == 0:+ os.chown(target, 12345, 23456)+ target.chmod(mode)+ before = target.stat()++ _patch_sample(target, method)++ after = target.stat()+ assert (after.st_mode, after.st_uid, after.st_gid) == (+ before.st_mode, before.st_uid, before.st_gid+ )+ assert target.read_text(encoding="utf-8") == "after\n"++[email protected]("method", ["line", "context", "exact"])+def test_patch_metadata_failure_keeps_original(+ tmp_path: Path, monkeypatch, method: str+) -> None:+ target = tmp_path / "sample.txt"+ target.write_text("before\n", encoding="utf-8")+ before = target.stat()++ def fail(*args, **kwargs):+ raise PermissionError("metadata denied")++ monkeypatch.setattr(file_ops.os, "chmod", fail)+ with pytest.raises(PermissionError, match="metadata denied"):+ _patch_sample(target, method)++ after = target.stat()+ assert (after.st_ino, after.st_mode, after.st_uid, after.st_gid) == (+ before.st_ino, before.st_mode, before.st_uid, before.st_gid+ )+ assert target.read_text(encoding="utf-8") == "before\n"+ assert list(tmp_path.iterdir()) == [target]+++def _patch_sample(target: Path, method: str) -> None:+ if method == "line":+ file_ops.apply_patch(str(target), [+ {"from": 1, "to": 1, "content": "after\n", "insert": False}+ ])+ elif method == "context":+ apply_context_patch_file(str(target), "@@\n-before\n+after\n")+ else:+ apply_exact_replace_file(str(target), "before", "after")++def test_context_patch_chains_after_line_shift(tmp_path: Path) -> None:target = tmp_path / "sample.txt"target.write_text("alpha\nbeta\ngamma\n", encoding="utf-8")