Skip to content

Agent Zero AI framework

Add context-based patch_text support to text_editor

Alessandro4c2bc3d783a2
diff --git a/plugins/_a0_connector/extensions/python/message_loop_prompts_after/_79_include_text_editor_remote.py b/plugins/_a0_connector/extensions/python/message_loop_prompts_after/_79_include_text_editor_remote.py
index a53b40af3..0c9cecf2e 100644
--- a/plugins/_a0_connector/extensions/python/message_loop_prompts_after/_79_include_text_editor_remote.py
+++ b/plugins/_a0_connector/extensions/python/message_loop_prompts_after/_79_include_text_editor_remote.py
@@ -27,7 +27,8 @@ class IncludeTextEditorRemote(Extension):
access_mode = "Read&Write (legacy/unknown)"
write_guidance = (
"- Writes and patches are expected to be available, but this CLI did not "
- "advertise an explicit F3 access mode."
+ "advertise an explicit F3 access mode.\n"
+ "- Prefer `patch_text` for context-anchored edits when supported."
)
write_examples = """```json
{
@@ -46,9 +47,7 @@ class IncludeTextEditorRemote(Extension):
"tool_args": {
"op": "patch",
"path": "/path/on/remote/machine/file.py",
- "edits": [
- {"from": 5, "to": 5, "content": " if x == 2:\\n"}
- ]
+ "patch_text": "*** Begin Patch\\n*** Update File: /path/on/remote/machine/file.py\\n@@ def main():\\n+ setup()\\n*** End Patch"
}
}
```"""
@@ -56,8 +55,9 @@ class IncludeTextEditorRemote(Extension):
access_mode = "Read&Write"
write_guidance = (
"- Use `write` only when replacing or creating the full file is the right operation.\n"
- "- Use `patch` for surgical line-range edits. Keep the edit set tight and based on the latest remote read.\n"
- "- Freshness-aware patching may reject stale edits. If a patch requires a reread, read the file again and then retry with updated ranges."
+ "- Use `patch` with `patch_text` for context-anchored edits, especially after inserts/deletes or when line numbers may have shifted.\n"
+ "- Use `patch` with `edits` only for surgical line-range edits based on the latest remote read.\n"
+ "- Freshness-aware line patching may reject stale edits. If a line patch requires a reread, read the file again and then retry with updated ranges."
)
write_examples = """```json
{
@@ -70,6 +70,28 @@ class IncludeTextEditorRemote(Extension):
}
```
+```json
+{
+ "tool_name": "text_editor_remote",
+ "tool_args": {
+ "op": "patch",
+ "path": "/path/on/remote/machine/file.py",
+ "patch_text": "*** Begin Patch\\n*** Update File: /path/on/remote/machine/file.py\\n@@ def main():\\n+ setup()\\n*** End Patch"
+ }
+}
+```
+
+```json
+{
+ "tool_name": "text_editor_remote",
+ "tool_args": {
+ "op": "patch",
+ "path": "/path/on/remote/machine/file.py",
+ "patch_text": "*** Begin Patch\\n*** Update File: /path/on/remote/machine/file.py\\n@@ def main():\\n- old_helper()\\n+ new_helper()\\n*** End Patch"
+ }
+}
+```
+
```json
{
"tool_name": "text_editor_remote",
diff --git a/plugins/_a0_connector/helpers/text_editor_freshness.py b/plugins/_a0_connector/helpers/text_editor_freshness.py
index 356e31a23..f43714cbb 100644
--- a/plugins/_a0_connector/helpers/text_editor_freshness.py
+++ b/plugins/_a0_connector/helpers/text_editor_freshness.py
@@ -1,159 +1,31 @@
from __future__ import annotations
-from typing import Any, TypedDict
+from typing import Any
-
-_FRESHNESS_KEY = "_a0_connector_text_editor_remote_mtimes"
-
-
-class FileMetadata(TypedDict):
- realpath: str
- mtime: float | None
- total_lines: int
-
-
-def coerce_file_metadata(file_data: Any) -> FileMetadata | None:
- if not isinstance(file_data, dict):
- return None
-
- realpath = str(file_data.get("realpath", "")).strip()
- if not realpath:
- return None
-
- try:
- total_lines = int(file_data.get("total_lines", 0))
- except (TypeError, ValueError):
- return None
-
- raw_mtime = file_data.get("mtime")
- if raw_mtime is None:
- mtime: float | None = None
- else:
- try:
- mtime = float(raw_mtime)
- except (TypeError, ValueError):
- mtime = None
-
- return FileMetadata(
- realpath=realpath,
- mtime=mtime,
- total_lines=max(total_lines, 0),
- )
+from plugins._text_editor.helpers.patch_state import (
+ REMOTE_FRESHNESS_KEY as _FRESHNESS_KEY,
+ FileMetadata,
+ apply_patch_post_state as _apply_patch_post_state,
+ check_patch_freshness as _check_patch_freshness,
+ coerce_file_metadata,
+ mark_file_state_stale as _mark_file_state_stale,
+ record_file_state as _record_file_state,
+)
def record_file_state(agent, file_data: Any) -> None:
- file_meta = coerce_file_metadata(file_data)
- if file_meta is None or file_meta["mtime"] is None:
- return
-
- freshness = agent.data.setdefault(_FRESHNESS_KEY, {})
- freshness[file_meta["realpath"]] = {
- "mtime": file_meta["mtime"],
- "total_lines": file_meta["total_lines"],
- }
+ _record_file_state(agent, file_data, key=_FRESHNESS_KEY)
def mark_file_state_stale(agent, file_data: Any) -> None:
- file_meta = coerce_file_metadata(file_data)
- if file_meta is None:
- return
-
- freshness = agent.data.setdefault(_FRESHNESS_KEY, {})
- freshness[file_meta["realpath"]] = {"mtime": 0, "total_lines": 0}
+ _mark_file_state_stale(agent, file_data, key=_FRESHNESS_KEY)
def check_patch_freshness(agent, file_data: Any) -> str | None:
- file_meta = coerce_file_metadata(file_data)
- if file_meta is None:
- return "patch_need_read"
-
- freshness = agent.data.get(_FRESHNESS_KEY, {})
- realpath = file_meta["realpath"]
- if realpath not in freshness:
- return "patch_need_read"
-
- stored = freshness[realpath]
- mtime = stored.get("mtime") if isinstance(stored, dict) else stored
- if mtime is None:
- freshness.pop(realpath, None)
- return "patch_need_read"
-
- current = file_meta["mtime"]
- if current is None:
- return None
- if current != mtime:
- return "patch_stale_read"
- return None
-
-
-def apply_patch_post_state(agent, file_data: Any, edits: list[Any] | None) -> None:
- file_meta = coerce_file_metadata(file_data)
- if file_meta is None:
- return
-
- freshness = agent.data.setdefault(_FRESHNESS_KEY, {})
- realpath = file_meta["realpath"]
-
- if not _all_edits_in_place(edits):
- freshness[realpath] = {"mtime": 0, "total_lines": 0}
- return
-
- stored = freshness.get(realpath)
- if not isinstance(stored, dict) or "total_lines" not in stored:
- freshness[realpath] = {"mtime": 0, "total_lines": 0}
- return
-
- if file_meta["total_lines"] != int(stored["total_lines"]):
- freshness[realpath] = {"mtime": 0, "total_lines": 0}
- return
-
- if file_meta["mtime"] is None:
- freshness[realpath] = {"mtime": 0, "total_lines": 0}
- return
-
- freshness[realpath] = {
- "mtime": file_meta["mtime"],
- "total_lines": file_meta["total_lines"],
- }
-
-
-def _all_edits_in_place(edits: list[Any] | None) -> bool:
- if not isinstance(edits, list):
- return False
-
- for edit in edits:
- if not isinstance(edit, dict):
- return False
-
- try:
- start = int(edit.get("from", 0) or 0)
- except (TypeError, ValueError):
- return False
- if start < 1:
- return False
-
- raw_to = edit.get("to")
- if raw_to is None:
- return False
-
- try:
- end = int(raw_to)
- except (TypeError, ValueError):
- return False
- if end < start:
- return False
-
- removed = end - start + 1
- added = _count_content_lines(edit.get("content"))
- if removed != added:
- return False
-
- return True
-
+ return _check_patch_freshness(agent, file_data, key=_FRESHNESS_KEY)
-def _count_content_lines(content: Any) -> int:
- if not content:
- return 0
- text = str(content)
- return text.count("\n") + (1 if not text.endswith("\n") else 0)
+def apply_patch_post_state(
+ agent, file_data: Any, edits: list[Any] | None
+) -> None:
+ _apply_patch_post_state(agent, file_data, edits, key=_FRESHNESS_KEY)
diff --git a/plugins/_a0_connector/prompts/agent.extras.text_editor_remote.md b/plugins/_a0_connector/prompts/agent.extras.text_editor_remote.md
index ecd1c627b..4c1149d8e 100644
--- a/plugins/_a0_connector/prompts/agent.extras.text_editor_remote.md
+++ b/plugins/_a0_connector/prompts/agent.extras.text_editor_remote.md
@@ -5,7 +5,11 @@ Current access mode: `{{access_mode}}`
- Use `text_editor_remote` when the user asks you to edit files on their local machine while connected via the CLI.
- Paths are evaluated on the remote CLI machine's filesystem, not on the Agent Zero server.
-- Prefer `read` before `patch` so you have current line numbers and freshness metadata.
+- Prefer `patch_text` for edits that can be located by surrounding code context.
+- For `patch_text` inserts, use one `@@ existing line` anchor followed directly by `+new line`.
+- For `patch_text` replacements, use `@@ before target` then `-old`/`+new`, or `@@ old target` then the same `-old`/`+new`.
+- Do not repeat the same old line as both context and deletion in one replacement hunk.
+- Prefer `read` before line-number `edits` so you have current line numbers and freshness metadata.
- `read` is always the safest first step for inspecting the local file.
{{write_guidance}}
diff --git a/plugins/_a0_connector/prompts/agent.system.tool.text_editor_remote.md b/plugins/_a0_connector/prompts/agent.system.tool.text_editor_remote.md
index 80a59ff24..cad385810 100644
--- a/plugins/_a0_connector/prompts/agent.system.tool.text_editor_remote.md
+++ b/plugins/_a0_connector/prompts/agent.system.tool.text_editor_remote.md
@@ -12,8 +12,14 @@ subscribed CLI, so the base system prompt stays small when remote editing is not
## Operations
- `read`: optional `line_from`, `line_to`
- `write`: requires `content`
-- `patch`: requires `edits`
+- `patch`: requires either `patch_text` or `edits`
## Notes
- Paths are evaluated on the **remote machine's filesystem**, not the Agent Zero server.
- The transport uses `connector_file_op` and `connector_file_op_result` with a shared `op_id`.
+- `patch_text` uses context chunks and does not require fresh line numbers.
+- `patch_text` line rules: `@@ existing line` anchors the hunk; `+new` inserts after the anchor when there are no context or delete lines; `-old` then `+new` replaces the next matching old line after the anchor, or the anchor line itself when `@@` is the old target line.
+- For replacements, do not repeat the same old line as both a space-context line and a `-old` line.
+- Every non-header content line in `patch_text` must start with exactly one prefix: space for kept context, `+` for added content, or `-` for removed content. Do not emit raw unprefixed content lines.
+- Do not stack multiple `@@` lines for one insert. Use one anchor, then the `+` lines to insert.
+- `edits` uses 1-based line ranges and may require rereading after line-count changes.
diff --git a/plugins/_a0_connector/tools/text_editor_remote.py b/plugins/_a0_connector/tools/text_editor_remote.py
index 60874e3e3..d8c9ff956 100644
--- a/plugins/_a0_connector/tools/text_editor_remote.py
+++ b/plugins/_a0_connector/tools/text_editor_remote.py
@@ -22,6 +22,7 @@ from plugins._a0_connector.helpers.ws_runtime import (
store_pending_file_op,
subscribed_sids_for_context,
)
+from plugins._text_editor.helpers.patch_request import parse_patch_request
FILE_OP_TIMEOUT = 30.0
@@ -70,19 +71,41 @@ class TextEditorRemote(Tool):
result = await self._execute_file_op(op, path, content=content)
self._record_success_state(result)
else:
- edits = self.args.get("edits")
- if not edits:
+ patch_request, err = parse_patch_request(
+ self.args.get("edits"),
+ self.args.get("patch_text"),
+ both_error="provide either edits or patch_text for patch, not both",
+ )
+ if err:
return Response(
- message="edits is required for patch",
+ message=err,
break_loop=False,
)
- result = await self._execute_patch(path, edits)
+ if patch_request and patch_request.mode == "patch_text":
+ result = await self._execute_context_patch(
+ path, patch_request.patch_text
+ )
+ else:
+ result = await self._execute_patch(
+ path,
+ patch_request.edits if patch_request else self.args.get("edits"),
+ )
return Response(
message=self._extract_result(result, op, path),
break_loop=False,
)
+ async def _execute_context_patch(self, path: str, patch_text: str) -> dict[str, Any]:
+ patch_result = await self._execute_file_op("patch", path, patch_text=patch_text)
+ if not self._result_ok(patch_result):
+ return patch_result
+
+ patch_file = self._extract_file_metadata(patch_result)
+ if patch_file is not None:
+ mark_file_state_stale(self.agent, patch_file)
+ return patch_result
+
async def _execute_patch(self, path: str, edits: Any) -> dict[str, Any]:
stat_result = await self._execute_file_op("stat", path)
if self._is_unsupported_cli_freshness(stat_result):
diff --git a/plugins/_text_editor/helpers/context_patch.py b/plugins/_text_editor/helpers/context_patch.py
new file mode 100644
index 000000000..dc859c502
--- /dev/null
+++ b/plugins/_text_editor/helpers/context_patch.py
@@ -0,0 +1,255 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Iterable
+
+
+class ContextPatchError(ValueError):
+ """Raised when a context patch cannot be parsed or applied safely."""
+
+
+@dataclass(frozen=True)
+class ContextPatchApplyResult:
+ content: str
+ line_from: int
+ line_to: int
+ hunk_count: int
+
+
+@dataclass(frozen=True)
+class _PatchLine:
+ kind: str
+ text: str
+
+
+@dataclass(frozen=True)
+class _Hunk:
+ anchor: str
+ lines: tuple[_PatchLine, ...]
+
+
+@dataclass(frozen=True)
+class _HunkApplyResult:
+ cursor: int
+ line_from: int
+ line_to: int
+
+
+_FILE_HEADERS = (
+ "*** Update File:",
+ "*** Add File:",
+ "*** Delete File:",
+ "*** End Patch",
+)
+
+
+def apply_context_patch(content: str, patch_text: str) -> str:
+ """Apply a PseudoPatch-inspired context patch to one text file."""
+ return apply_context_patch_with_metadata(content, patch_text).content
+
+
+def apply_context_patch_with_metadata(
+ content: str, patch_text: str
+) -> ContextPatchApplyResult:
+ """Apply a context patch and report the touched line range."""
+ body = _extract_single_file_body(patch_text)
+ hunks = _parse_hunks(body)
+ if not hunks:
+ raise ContextPatchError("patch_text must contain at least one update hunk")
+
+ lines = content.split("\n")
+ cursor = 0
+ line_from: int | None = None
+ line_to = 1
+ for hunk in hunks:
+ result = _apply_hunk(lines, hunk, cursor)
+ cursor = result.cursor
+ line_from = (
+ result.line_from if line_from is None
+ else min(line_from, result.line_from)
+ )
+ line_to = max(line_to, result.line_to)
+
+ return ContextPatchApplyResult(
+ content="\n".join(lines),
+ line_from=line_from or 1,
+ line_to=line_to,
+ hunk_count=len(hunks),
+ )
+
+
+def _extract_single_file_body(patch_text: str) -> list[str]:
+ raw_lines = [line.rstrip("\r") for line in str(patch_text).splitlines()]
+ lines = _trim_outer_blank_lines(raw_lines)
+ if not lines:
+ raise ContextPatchError("patch_text is required")
+
+ if not lines[0].startswith("*** Begin Patch"):
+ return lines
+ if len(lines) < 2 or lines[-1] != "*** End Patch":
+ raise ContextPatchError("patch_text missing *** End Patch")
+
+ body: list[str] = []
+ in_update = False
+ update_count = 0
+ for line in lines[1:-1]:
+ if line.startswith("*** Update File:"):
+ if update_count:
+ raise ContextPatchError(
+ "patch_text may update only one file per operation"
+ )
+ in_update = True
+ update_count += 1
+ continue
+ if line.startswith("*** Move to:"):
+ raise ContextPatchError("patch_text does not support file moves")
+ if line.startswith(("*** Add File:", "*** Delete File:")):
+ raise ContextPatchError("patch_text supports update hunks only")
+ if in_update:
+ body.append(line)
+
+ if not update_count:
+ raise ContextPatchError("patch_text must include an update file block")
+ return body
+
+
+def _trim_outer_blank_lines(lines: list[str]) -> list[str]:
+ start = 0
+ end = len(lines)
+ while start < end and not lines[start].strip():
+ start += 1
+ while end > start and not lines[end - 1].strip():
+ end -= 1
+ return lines[start:end]
+
+
+def _parse_hunks(lines: list[str]) -> list[_Hunk]:
+ hunks: list[_Hunk] = []
+ anchor = ""
+ current: list[_PatchLine] = []
+
+ def finish_current() -> None:
+ nonlocal anchor, current
+ if current:
+ hunks.append(_Hunk(anchor=anchor, lines=tuple(current)))
+ current = []
+ anchor = ""
+
+ for line in lines:
+ if line.startswith(_FILE_HEADERS):
+ finish_current()
+ break
+ if line.startswith("@@"):
+ finish_current()
+ anchor = line[2:].strip()
+ continue
+ if line.startswith("***"):
+ raise ContextPatchError(f"invalid patch control line: {line}")
+
+ if line == "":
+ current.append(_PatchLine(" ", ""))
+ continue
+ if line[0] not in {" ", "+", "-"}:
+ raise ContextPatchError(f"invalid patch line prefix: {line}")
+ current.append(_PatchLine(line[0], line[1:]))
+
+ finish_current()
+ return hunks
+
+
+def _apply_hunk(
+ lines: list[str], hunk: _Hunk, cursor: int
+) -> _HunkApplyResult:
+ old_lines = [line.text for line in hunk.lines if line.kind in {" ", "-"}]
+ new_lines = [line.text for line in hunk.lines if line.kind in {" ", "+"}]
+
+ if old_lines == new_lines:
+ raise ContextPatchError("patch hunk does not change content")
+ if not old_lines:
+ if not hunk.anchor:
+ raise ContextPatchError("insert-only patch hunk needs an @@ anchor")
+ insert_at = _find_anchor(lines, hunk.anchor, cursor)
+ lines[insert_at:insert_at] = new_lines
+ return _HunkApplyResult(
+ cursor=insert_at + len(new_lines),
+ line_from=insert_at + 1,
+ line_to=insert_at + max(len(new_lines), 1),
+ )
+
+ start = cursor
+ if hunk.anchor:
+ start = _find_anchor(lines, hunk.anchor, cursor)
+
+ try:
+ match_index = _find_context(lines, old_lines, start, anchored=bool(hunk.anchor))
+ except ContextPatchError:
+ if not hunk.anchor:
+ raise
+ # Models often anchor on the line they want to replace. Preserve the
+ # insert-after-anchor rule, but allow replacement context to start at
+ # the anchor line when it is not found after the anchor.
+ match_index = _find_context(lines, old_lines, start - 1, anchored=True)
+ lines[match_index : match_index + len(old_lines)] = new_lines
+ return _HunkApplyResult(
+ cursor=match_index + len(new_lines),
+ line_from=match_index + 1,
+ line_to=match_index + max(len(new_lines), 1),
+ )
+
+
+def _find_anchor(lines: list[str], anchor: str, start: int) -> int:
+ for index in range(start, len(lines)):
+ if lines[index] == anchor:
+ return index + 1
+ stripped_anchor = anchor.strip()
+ for index in range(start, len(lines)):
+ if lines[index].strip() == stripped_anchor:
+ return index + 1
+ raise ContextPatchError(f"anchor not found: {anchor}")
+
+
+def _find_context(
+ lines: list[str],
+ context: list[str],
+ start: int,
+ *,
+ anchored: bool,
+) -> int:
+ matches = _matching_indexes(lines, context, start, mode="exact")
+ if not matches:
+ matches = _matching_indexes(lines, context, start, mode="rstrip")
+
+ if not matches:
+ preview = "\n".join(context[:5])
+ raise ContextPatchError(f"context not found:\n{preview}")
+ if len(matches) > 1 and not anchored:
+ preview = "\n".join(context[:5])
+ raise ContextPatchError(
+ "context matched multiple locations; add an @@ anchor or more context:\n"
+ f"{preview}"
+ )
+ return matches[0]
+
+
+def _matching_indexes(
+ lines: list[str],
+ context: list[str],
+ start: int,
+ *,
+ mode: str,
+) -> list[int]:
+ if len(lines) < len(context):
+ return []
+
+ matches: list[int] = []
+ for index in range(max(start, 0), len(lines) - len(context) + 1):
+ candidate = lines[index : index + len(context)]
+ if _lines_equal(candidate, context, mode=mode):
+ matches.append(index)
+ return matches
+
+
+def _lines_equal(left: Iterable[str], right: Iterable[str], *, mode: str) -> bool:
+ if mode == "rstrip":
+ return [item.rstrip() for item in left] == [item.rstrip() for item in right]
+ return list(left) == list(right)
diff --git a/plugins/_text_editor/helpers/file_ops.py b/plugins/_text_editor/helpers/file_ops.py
index c05ec05d2..10da4f323 100644
--- a/plugins/_text_editor/helpers/file_ops.py
+++ b/plugins/_text_editor/helpers/file_ops.py
@@ -10,6 +10,9 @@ import tempfile
from typing import TypedDict
from helpers import tokens
+from plugins._text_editor.helpers.context_patch import (
+ apply_context_patch_with_metadata,
+)
_BINARY_PEEK = 8192
@@ -208,6 +211,13 @@ class PatchResult(TypedDict):
error: str
+class ContextPatchFileResult(TypedDict):
+ total_lines: int
+ hunk_count: int
+ line_from: int
+ line_to: int
+
+
def validate_edits(edits: list | None) -> tuple[list[dict], str]:
"""
Normalise and validate an edits array.
@@ -352,6 +362,35 @@ def patch_file(path: str, edits: list | None) -> PatchResult:
return PatchResult(total_lines=total, edit_count=len(parsed), error="")
+def apply_context_patch_file(path: str, patch_text: str) -> ContextPatchFileResult:
+ """Apply a context patch to an existing text file."""
+ path = os.path.expanduser(path)
+ if not os.path.isfile(path):
+ raise FileNotFoundError("file not found")
+
+ with open(path, "r", encoding="utf-8", errors="replace") as src:
+ content = src.read()
+
+ result = apply_context_patch_with_metadata(content, patch_text)
+ dir_name = os.path.dirname(path) or "."
+ fd, tmp_path = tempfile.mkstemp(dir=dir_name, suffix=".tmp")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as dst:
+ dst.write(result.content)
+ shutil.move(tmp_path, path)
+ except Exception:
+ if os.path.exists(tmp_path):
+ os.unlink(tmp_path)
+ raise
+
+ return ContextPatchFileResult(
+ total_lines=_count_content_lines(result.content),
+ hunk_count=result.hunk_count,
+ line_from=result.line_from,
+ line_to=result.line_to,
+ )
+
+
# ------------------------------------------------------------------
# Internal
# ------------------------------------------------------------------
diff --git a/plugins/_text_editor/helpers/patch_request.py b/plugins/_text_editor/helpers/patch_request.py
new file mode 100644
index 000000000..b8c4ae0c8
--- /dev/null
+++ b/plugins/_text_editor/helpers/patch_request.py
@@ -0,0 +1,37 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Literal
+
+
+PatchMode = Literal["edits", "patch_text"]
+
+
+@dataclass(frozen=True)
+class PatchRequest:
+ mode: PatchMode
+ edits: Any = None
+ patch_text: str = ""
+
+
+def parse_patch_request(
+ edits: Any,
+ patch_text: Any,
+ *,
+ both_error: str = "provide either edits or patch_text, not both",
+ missing_error: str = "edits or patch_text is required for patch",
+) -> tuple[PatchRequest | None, str]:
+ """Validate the mutually-exclusive patch request shape."""
+ if edits is not None and patch_text is not None:
+ return None, both_error
+
+ if patch_text is not None:
+ text = str(patch_text)
+ if not text.strip():
+ return None, "patch_text must not be empty"
+ return PatchRequest(mode="patch_text", patch_text=text), ""
+
+ if not edits:
+ return None, missing_error
+
+ return PatchRequest(mode="edits", edits=edits), ""
diff --git a/plugins/_text_editor/helpers/patch_state.py b/plugins/_text_editor/helpers/patch_state.py
new file mode 100644
index 000000000..bbcf3403f
--- /dev/null
+++ b/plugins/_text_editor/helpers/patch_state.py
@@ -0,0 +1,187 @@
+from __future__ import annotations
+
+from typing import Any, TypedDict
+
+
+LOCAL_FRESHNESS_KEY = "_text_editor_mtimes"
+REMOTE_FRESHNESS_KEY = "_a0_connector_text_editor_remote_mtimes"
+
+
+class FileMetadata(TypedDict):
+ realpath: str
+ mtime: float | None
+ total_lines: int
+
+
+def coerce_file_metadata(
+ file_data: Any, *, total_lines: int | None = None
+) -> FileMetadata | None:
+ if not isinstance(file_data, dict):
+ return None
+
+ realpath = str(file_data.get("realpath", "")).strip()
+ if not realpath:
+ return None
+
+ try:
+ line_count = (
+ int(total_lines)
+ if total_lines is not None
+ else int(file_data.get("total_lines", 0))
+ )
+ except (TypeError, ValueError):
+ return None
+
+ raw_mtime = file_data.get("mtime")
+ if raw_mtime is None:
+ mtime: float | None = None
+ else:
+ try:
+ mtime = float(raw_mtime)
+ except (TypeError, ValueError):
+ mtime = None
+
+ return FileMetadata(
+ realpath=realpath,
+ mtime=mtime,
+ total_lines=max(line_count, 0),
+ )
+
+
+def record_file_state(
+ agent,
+ file_data: Any,
+ *,
+ key: str,
+ total_lines: int | None = None,
+) -> None:
+ file_meta = coerce_file_metadata(file_data, total_lines=total_lines)
+ if file_meta is None or file_meta["mtime"] is None:
+ return
+
+ freshness = agent.data.setdefault(key, {})
+ freshness[file_meta["realpath"]] = {
+ "mtime": file_meta["mtime"],
+ "total_lines": file_meta["total_lines"],
+ }
+
+
+def mark_file_state_stale(
+ agent,
+ file_data: Any,
+ *,
+ key: str,
+ total_lines: int | None = None,
+) -> None:
+ file_meta = coerce_file_metadata(file_data, total_lines=total_lines)
+ if file_meta is None:
+ return
+
+ freshness = agent.data.setdefault(key, {})
+ freshness[file_meta["realpath"]] = {"mtime": 0, "total_lines": 0}
+
+
+def check_patch_freshness(agent, file_data: Any, *, key: str) -> str | None:
+ file_meta = coerce_file_metadata(file_data)
+ if file_meta is None:
+ return "patch_need_read"
+
+ freshness = agent.data.get(key, {})
+ realpath = file_meta["realpath"]
+ if realpath not in freshness:
+ return "patch_need_read"
+
+ stored = freshness[realpath]
+ mtime = stored.get("mtime") if isinstance(stored, dict) else stored
+ if mtime is None:
+ freshness.pop(realpath, None)
+ return "patch_need_read"
+
+ current = file_meta["mtime"]
+ if current is None:
+ return None
+ if current != mtime:
+ return "patch_stale_read"
+ return None
+
+
+def apply_patch_post_state(
+ agent,
+ file_data: Any,
+ edits: list[Any] | None,
+ *,
+ key: str,
+ total_lines: int | None = None,
+) -> None:
+ file_meta = coerce_file_metadata(file_data, total_lines=total_lines)
+ if file_meta is None:
+ return
+
+ freshness = agent.data.setdefault(key, {})
+ realpath = file_meta["realpath"]
+
+ if not all_edits_in_place(edits):
+ freshness[realpath] = {"mtime": 0, "total_lines": 0}
+ return
+
+ stored = freshness.get(realpath)
+ if not isinstance(stored, dict) or "total_lines" not in stored:
+ freshness[realpath] = {"mtime": 0, "total_lines": 0}
+ return
+
+ if file_meta["total_lines"] != int(stored["total_lines"]):
+ freshness[realpath] = {"mtime": 0, "total_lines": 0}
+ return
+
+ if file_meta["mtime"] is None:
+ freshness[realpath] = {"mtime": 0, "total_lines": 0}
+ return
+
+ freshness[realpath] = {
+ "mtime": file_meta["mtime"],
+ "total_lines": file_meta["total_lines"],
+ }
+
+
+def all_edits_in_place(edits: list[Any] | None) -> bool:
+ if not isinstance(edits, list):
+ return False
+
+ for edit in edits:
+ if not isinstance(edit, dict):
+ return False
+ if edit.get("insert"):
+ return False
+
+ try:
+ start = int(edit.get("from", 0) or 0)
+ except (TypeError, ValueError):
+ return False
+ if start < 1:
+ return False
+
+ raw_to = edit.get("to")
+ if raw_to is None:
+ return False
+
+ try:
+ end = int(raw_to)
+ except (TypeError, ValueError):
+ return False
+ if end < start:
+ return False
+
+ removed = end - start + 1
+ added = count_content_lines(edit.get("content"))
+ if removed != added:
+ return False
+
+ return True
+
+
+def count_content_lines(content: Any) -> int:
+ if not content:
+ return 0
+
+ text = str(content)
+ return text.count("\n") + (1 if not text.endswith("\n") else 0)
diff --git a/plugins/_text_editor/prompts/agent.system.tool.text_editor.md b/plugins/_text_editor/prompts/agent.system.tool.text_editor.md
index d3a65cd3c..a30868528 100644
--- a/plugins/_text_editor/prompts/agent.system.tool.text_editor.md
+++ b/plugins/_text_editor/prompts/agent.system.tool.text_editor.md
@@ -38,19 +38,19 @@ usage:
~~~
#### text_editor:patch
-line edits on existing file
-args path edits [{from to content}]
-from to inclusive \n in content
-{from:2 to:2 content:"x\n"} replace line
-{from:1 to:3 content:"x\n"} replace range
-{from:2 to:2} delete (no content)
-{from:2 content:"x\n"} insert before (omit to)
-use original line numbers from read
-dont adjust for shifts no overlapping edits
+edit existing file. prefer patch_text; use edits only right after read for tiny line edits
+args path plus exactly one of: patch_text string OR edits [{from to content}]
+patch_text uses current file content, no prior read required
+patch_text update-only forms:
+- insert after anchor: @@ exact existing line then +new lines
+- replace: use @@ line before target then -old +new, or @@ old target line then -same old target line +new
+- do not repeat the same old line as both a space-context line and a -removed line
+- context lines start with space, removals with -, additions with +
+- use enough unique context; add @@ anchor when repeated text exists
+edits legacy line mode: from/to inclusive, original line numbers from read, no overlaps
+edits examples: {from:2 to:2 content:"x\n"} replace; {from:2 to:2} delete; {from:2 content:"x\n"} insert before
+for edits, re-read after insert/delete or line-count-changing replace
ensure valid syntax in content (all braces brackets tags closed)
-only replace exact lines needed dont include surrounding unchanged lines
-re-read when insert delete or N≠M replace else patch again ok
-large changes write over multiple patches
usage:
~~~json
{
@@ -58,10 +58,7 @@ usage:
"tool_name": "text_editor:patch",
"tool_args": {
"path": "/path/file.py",
- "edits": [
- {"from": 1, "content": "import sys\n"},
- {"from": 5, "to": 5, "content": " if x == 2:\n"}
- ]
+ "patch_text": "*** Begin Patch\n*** Update File: file.py\n@@ def run():\n+ print('ready')\n*** End Patch"
}
}
~~~
diff --git a/plugins/_text_editor/tools/text_editor.py b/plugins/_text_editor/tools/text_editor.py
index 78c667482..b7108d445 100644
--- a/plugins/_text_editor/tools/text_editor.py
+++ b/plugins/_text_editor/tools/text_editor.py
@@ -7,12 +7,21 @@ from plugins._text_editor.helpers.file_ops import (
write_file,
validate_edits,
apply_patch,
+ apply_context_patch_file,
file_info,
)
+from plugins._text_editor.helpers.patch_request import parse_patch_request
+from plugins._text_editor.helpers.patch_state import (
+ LOCAL_FRESHNESS_KEY,
+ apply_patch_post_state,
+ check_patch_freshness,
+ mark_file_state_stale,
+ record_file_state,
+)
# Key used in agent.data to store file state for patch validation
# Value: {path: {"mtime": float, "total_lines": int}}
-_MTIME_KEY = "_text_editor_mtimes"
+_MTIME_KEY = LOCAL_FRESHNESS_KEY
@@ -56,7 +65,12 @@ class TextEditor(Tool):
return self._error("read", path, result["error"])
info = await runtime.call_development_function(file_info, path)
- _record_mtime(self.agent, info, result["total_lines"])
+ record_file_state(
+ self.agent,
+ info,
+ key=_MTIME_KEY,
+ total_lines=result["total_lines"],
+ )
# Extension point
ext_data = {
@@ -105,7 +119,12 @@ class TextEditor(Tool):
)
info = await runtime.call_development_function(file_info, path)
- _record_mtime(self.agent, info, result["total_lines"])
+ record_file_state(
+ self.agent,
+ info,
+ key=_MTIME_KEY,
+ total_lines=result["total_lines"],
+ )
cfg = _get_config(self.agent)
read_result = await runtime.call_development_function(
@@ -128,9 +147,18 @@ class TextEditor(Tool):
# ------------------------------------------------------------------
# PATCH
# ------------------------------------------------------------------
- async def _patch(self, path: str = "", edits=None, **kwargs) -> Response:
+ async def _patch(
+ self, path: str = "", edits=None, patch_text=None, **kwargs
+ ) -> Response:
if not path:
return self._error("patch", path, "path is required")
+ patch_request, err = parse_patch_request(
+ edits,
+ patch_text,
+ missing_error="",
+ )
+ if err:
+ return self._error("patch", path, err)
info = await runtime.call_development_function(file_info, path)
if not info["is_file"]:
@@ -138,9 +166,28 @@ class TextEditor(Tool):
expanded = info["expanded"]
- stale_err = _check_mtime(self.agent, info)
- if stale_err:
- return self._error("patch", path, stale_err)
+ if patch_request and patch_request.mode == "patch_text":
+ return await self._patch_context(
+ path, expanded, patch_request.patch_text
+ )
+
+ return await self._patch_edits(
+ path,
+ expanded,
+ info,
+ patch_request.edits if patch_request else edits,
+ )
+
+ async def _patch_edits(
+ self, path: str, expanded: str, info: FileInfo, edits
+ ) -> Response:
+ freshness_code = check_patch_freshness(self.agent, info, key=_MTIME_KEY)
+ if freshness_code:
+ return self._error(
+ "patch",
+ path,
+ _freshness_error_message(self.agent, info, freshness_code),
+ )
parsed, err = validate_edits(edits)
if err:
@@ -169,8 +216,12 @@ class TextEditor(Tool):
post_info = await runtime.call_development_function(
file_info, expanded
)
- _apply_patch_post(
- self.agent, post_info, total_lines, ext_data["edits"]
+ apply_patch_post_state(
+ self.agent,
+ post_info,
+ ext_data["edits"],
+ key=_MTIME_KEY,
+ total_lines=total_lines,
)
patch_content = await _read_patch_region(
@@ -186,6 +237,64 @@ class TextEditor(Tool):
)
return Response(message=msg, break_loop=False)
+ async def _patch_context(
+ self, path: str, expanded: str, patch_text
+ ) -> Response:
+ patch_text = str(patch_text)
+ if not patch_text.strip():
+ return self._error("patch", path, "patch_text must not be empty")
+
+ # Extension point
+ ext_data = {
+ "path": expanded,
+ "patch_text": patch_text,
+ "edits": [],
+ "mode": "patch_text",
+ }
+ await call_extensions_async(
+ "text_editor_patch_before", agent=self.agent, data=ext_data
+ )
+
+ try:
+ result = await runtime.call_development_function(
+ apply_context_patch_file,
+ ext_data["path"],
+ ext_data["patch_text"],
+ )
+ except Exception as exc:
+ return self._error("patch", path, str(exc))
+
+ total_lines = result["total_lines"]
+
+ # Extension point
+ await call_extensions_async(
+ "text_editor_patch_after", agent=self.agent,
+ data={
+ "path": ext_data["path"],
+ "total_lines": total_lines,
+ "hunk_count": result["hunk_count"],
+ "mode": "patch_text",
+ },
+ )
+
+ post_info = await runtime.call_development_function(
+ file_info, ext_data["path"]
+ )
+ mark_file_state_stale(self.agent, post_info, key=_MTIME_KEY)
+
+ patch_content = await _read_context_patch_region(
+ ext_data["path"], result, _get_config(self.agent)
+ )
+
+ msg = self.agent.read_prompt(
+ "fw.text_editor.patch_ok.md",
+ path=ext_data["path"],
+ edit_count=str(result["hunk_count"]),
+ total_lines=str(total_lines),
+ content=patch_content,
+ )
+ return Response(message=msg, break_loop=False)
+
# ------------------------------------------------------------------
# Shared error helper
# ------------------------------------------------------------------
@@ -230,82 +339,34 @@ async def _read_patch_region(
return result["content"]
-def _record_mtime(agent, info: FileInfo, total_lines: int):
- mtimes = agent.data.setdefault(_MTIME_KEY, {})
- if info["mtime"] is not None:
- mtimes[info["realpath"]] = {
- "mtime": info["mtime"],
- "total_lines": total_lines,
- }
+async def _read_context_patch_region(
+ path: str, result: dict, cfg: dict
+) -> str:
+ total_lines = int(result["total_lines"])
+ if total_lines <= 0:
+ return ""
+ line_from = min(max(int(result["line_from"]), 1), total_lines)
+ line_to = min(max(int(result["line_to"]), line_from) + 3, total_lines)
-def _count_content_lines(content: str) -> int:
- return content.count("\n") + (
- 1 if content and not content.endswith("\n") else 0
+ read_result = await runtime.call_development_function(
+ read_file,
+ path,
+ line_from=max(line_from - 1, 1),
+ line_to=line_to,
+ max_line_tokens=cfg["max_line_tokens"],
+ max_total_read_tokens=cfg["max_total_read_tokens"],
)
+ return read_result["content"]
-def _all_edits_in_place(edits: list[dict]) -> bool:
- for e in edits:
- if e.get("insert"):
- return False
- removed = max(e["to"] - e["from"] + 1, 0)
- added = _count_content_lines(e.get("content", "") or "")
- if removed != added:
- return False
- return True
-
-
-def _apply_patch_post(
- agent, info: FileInfo, new_total: int, edits: list[dict]
-):
- mtimes = agent.data.setdefault(_MTIME_KEY, {})
- real = info["realpath"]
-
- if not _all_edits_in_place(edits):
- # Line count changed — mark stale so next patch gets
- # "file changed since last read" instead of "line numbers unknown"
- mtimes[real] = {"mtime": 0, "total_lines": 0}
- return
-
- stored = mtimes.get(real)
- if not isinstance(stored, dict) or "total_lines" not in stored:
- mtimes[real] = {"mtime": 0, "total_lines": 0}
- return
- if new_total != stored["total_lines"]:
- mtimes[real] = {"mtime": 0, "total_lines": 0}
- return
- if info["mtime"] is not None:
- mtimes[real] = {
- "mtime": info["mtime"],
- "total_lines": new_total,
- }
- else:
- mtimes[real] = {"mtime": 0, "total_lines": 0}
-
-
-def _check_mtime(agent, info: FileInfo) -> str:
- mtimes = agent.data.get(_MTIME_KEY, {})
- real = info["realpath"]
- if real not in mtimes:
- return agent.read_prompt(
- "fw.text_editor.patch_need_read.md", path=info["expanded"]
- )
- stored = mtimes[real]
- mtime = stored.get("mtime") if isinstance(stored, dict) else stored
- if mtime is None:
- mtimes.pop(real, None)
- return agent.read_prompt(
- "fw.text_editor.patch_need_read.md", path=info["expanded"]
- )
- current = info["mtime"]
- if current is None:
- return ""
- if current != mtime:
- return agent.read_prompt(
- "fw.text_editor.patch_stale_read.md", path=info["expanded"]
- )
- return ""
+def _freshness_error_message(agent, info: FileInfo, code: str) -> str:
+ prompt = (
+ "fw.text_editor.patch_stale_read.md"
+ if code == "patch_stale_read"
+ else "fw.text_editor.patch_need_read.md"
+ )
+ return agent.read_prompt(prompt, path=info["expanded"])
# ------------------------------------------------------------------
# Config
diff --git a/tests/test_text_editor_context_patch.py b/tests/test_text_editor_context_patch.py
new file mode 100644
index 000000000..03a47c226
--- /dev/null
+++ b/tests/test_text_editor_context_patch.py
@@ -0,0 +1,498 @@
+import asyncio
+import importlib
+import inspect
+import os
+import sys
+import types
+from dataclasses import dataclass
+from pathlib import Path
+
+import pytest
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+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.file_ops import apply_context_patch_file
+from plugins._text_editor.helpers.patch_request import parse_patch_request
+from plugins._text_editor.helpers.patch_state import (
+ LOCAL_FRESHNESS_KEY,
+ REMOTE_FRESHNESS_KEY,
+ apply_patch_post_state,
+ check_patch_freshness,
+ mark_file_state_stale,
+ record_file_state,
+)
+
+
+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")
+
+ first = apply_context_patch_file(
+ str(target),
+ (
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ "@@ alpha\n"
+ "+inserted\n"
+ "*** End Patch"
+ ),
+ )
+ second = apply_context_patch_file(
+ str(target),
+ (
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ " beta\n"
+ "-gamma\n"
+ "+gamma-updated\n"
+ "*** End Patch"
+ ),
+ )
+
+ assert first["total_lines"] == 4
+ assert first["hunk_count"] == 1
+ assert second["total_lines"] == 4
+ assert target.read_text(encoding="utf-8") == (
+ "alpha\ninserted\nbeta\ngamma-updated\n"
+ )
+
+
+def test_context_patch_inserts_after_anchor(tmp_path: Path) -> None:
+ target = tmp_path / "sample.txt"
+ target.write_text("alpha\nbeta\n", encoding="utf-8")
+
+ result = apply_context_patch_file(
+ str(target),
+ (
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ "@@ alpha\n"
+ "+inserted\n"
+ "*** End Patch"
+ ),
+ )
+
+ assert result["line_from"] == 2
+ assert result["line_to"] == 2
+ assert target.read_text(encoding="utf-8") == "alpha\ninserted\nbeta\n"
+
+
+def test_context_patch_replaces_matching_context(tmp_path: Path) -> None:
+ target = tmp_path / "sample.txt"
+ target.write_text("alpha\nbeta\ngamma\n", encoding="utf-8")
+
+ result = apply_context_patch_file(
+ str(target),
+ (
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ " beta\n"
+ "-gamma\n"
+ "+delta\n"
+ "*** End Patch"
+ ),
+ )
+
+ assert result["line_from"] == 2
+ assert target.read_text(encoding="utf-8") == "alpha\nbeta\ndelta\n"
+
+
+def test_context_patch_replaces_when_anchor_is_target_line(
+ tmp_path: Path,
+) -> None:
+ target = tmp_path / "sample.py"
+ target.write_text(
+ (
+ "def main():\n"
+ " print(greet(\"Agent Zero\"))\n"
+ "\n"
+ "\n"
+ "if __name__ == \"__main__\":\n"
+ " main()\n"
+ ),
+ encoding="utf-8",
+ )
+
+ result = apply_context_patch_file(
+ str(target),
+ (
+ "*** Begin Patch\n"
+ "*** Update File: sample.py\n"
+ "@@ print(greet(\"Agent Zero\"))\n"
+ "- print(greet(\"Agent Zero\"))\n"
+ "+ print(greet(\"Agent Zero\").upper())\n"
+ "*** End Patch"
+ ),
+ )
+
+ assert result["line_from"] == 2
+ assert target.read_text(encoding="utf-8") == (
+ "def main():\n"
+ " print(greet(\"Agent Zero\").upper())\n"
+ "\n"
+ "\n"
+ "if __name__ == \"__main__\":\n"
+ " main()\n"
+ )
+
+
+def test_context_patch_rejects_ambiguous_unanchored_context(
+ tmp_path: Path,
+) -> None:
+ target = tmp_path / "sample.txt"
+ target.write_text("same\nold\nsame\nold\n", encoding="utf-8")
+
+ with pytest.raises(ContextPatchError, match="matched multiple locations"):
+ apply_context_patch_file(
+ str(target),
+ (
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ " same\n"
+ "-old\n"
+ "+new\n"
+ "*** End Patch"
+ ),
+ )
+
+
+ "patch_text, expected",
+ [
+ (
+ "*** Begin Patch\n*** Add File: sample.txt\n+x\n*** End Patch",
+ "supports update hunks only",
+ ),
+ (
+ "*** Begin Patch\n*** Delete File: sample.txt\n*** End Patch",
+ "supports update hunks only",
+ ),
+ (
+ (
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ "*** Move to: other.txt\n"
+ "*** End Patch"
+ ),
+ "does not support file moves",
+ ),
+ (
+ (
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ "@@ alpha\n"
+ "+one\n"
+ "*** Update File: other.txt\n"
+ "@@ beta\n"
+ "+two\n"
+ "*** End Patch"
+ ),
+ "may update only one file",
+ ),
+ ],
+)
+def test_context_patch_rejects_unsupported_file_operations(
+ tmp_path: Path, patch_text: str, expected: str
+) -> None:
+ target = tmp_path / "sample.txt"
+ target.write_text("alpha\nbeta\n", encoding="utf-8")
+
+ with pytest.raises(ContextPatchError, match=expected):
+ apply_context_patch_file(str(target), patch_text)
+
+
+def test_patch_request_rejects_edits_and_patch_text_together() -> None:
+ request, err = parse_patch_request(
+ [{"from": 1, "to": 1, "content": "x\n"}],
+ "@@ alpha\n+beta",
+ )
+
+ assert request is None
+ assert err == "provide either edits or patch_text, not both"
+
+
+def test_patch_request_rejects_empty_patch_text() -> None:
+ request, err = parse_patch_request(None, " \n")
+
+ assert request is None
+ assert err == "patch_text must not be empty"
+
+
+def test_patch_state_records_and_checks_fresh_file_state() -> None:
+ agent = _FakeAgent()
+ file_data = {"realpath": "/tmp/sample.txt", "mtime": 1.0, "total_lines": 3}
+
+ record_file_state(agent, file_data, key=LOCAL_FRESHNESS_KEY)
+
+ assert check_patch_freshness(agent, file_data, key=LOCAL_FRESHNESS_KEY) is None
+ assert check_patch_freshness(
+ agent,
+ {"realpath": "/tmp/sample.txt", "mtime": 2.0, "total_lines": 3},
+ key=LOCAL_FRESHNESS_KEY,
+ ) == "patch_stale_read"
+
+
+def test_patch_state_marks_context_patches_stale() -> None:
+ agent = _FakeAgent()
+ file_data = {"realpath": "/tmp/sample.txt", "mtime": 1.0, "total_lines": 3}
+
+ record_file_state(agent, file_data, key=LOCAL_FRESHNESS_KEY)
+ mark_file_state_stale(agent, file_data, key=LOCAL_FRESHNESS_KEY)
+
+ assert agent.data[LOCAL_FRESHNESS_KEY]["/tmp/sample.txt"] == {
+ "mtime": 0,
+ "total_lines": 0,
+ }
+
+
+def test_patch_state_line_preserving_edits_can_chain() -> None:
+ agent = _FakeAgent()
+ initial = {"realpath": "/tmp/sample.txt", "mtime": 1.0, "total_lines": 3}
+ patched = {"realpath": "/tmp/sample.txt", "mtime": 2.0, "total_lines": 3}
+ edits = [{"from": 2, "to": 2, "content": "line-2a\n"}]
+
+ record_file_state(agent, initial, key=LOCAL_FRESHNESS_KEY)
+ apply_patch_post_state(agent, patched, edits, key=LOCAL_FRESHNESS_KEY)
+
+ assert agent.data[LOCAL_FRESHNESS_KEY]["/tmp/sample.txt"] == {
+ "mtime": 2.0,
+ "total_lines": 3,
+ }
+ assert check_patch_freshness(agent, patched, key=LOCAL_FRESHNESS_KEY) is None
+
+
+def test_patch_state_line_count_changes_force_reread() -> None:
+ agent = _FakeAgent()
+ initial = {"realpath": "/tmp/sample.txt", "mtime": 1.0, "total_lines": 3}
+ patched = {"realpath": "/tmp/sample.txt", "mtime": 2.0, "total_lines": 4}
+ edits = [{"from": 2, "content": "inserted\n"}]
+
+ record_file_state(agent, initial, key=LOCAL_FRESHNESS_KEY)
+ apply_patch_post_state(agent, patched, edits, key=LOCAL_FRESHNESS_KEY)
+
+ assert agent.data[LOCAL_FRESHNESS_KEY]["/tmp/sample.txt"] == {
+ "mtime": 0,
+ "total_lines": 0,
+ }
+
+
+def test_patch_state_uses_separate_local_and_remote_keys() -> None:
+ agent = _FakeAgent()
+ file_data = {"realpath": "/tmp/sample.txt", "mtime": 1.0, "total_lines": 3}
+
+ record_file_state(agent, file_data, key=LOCAL_FRESHNESS_KEY)
+ mark_file_state_stale(agent, file_data, key=REMOTE_FRESHNESS_KEY)
+
+ assert agent.data[LOCAL_FRESHNESS_KEY]["/tmp/sample.txt"] == {
+ "mtime": 1.0,
+ "total_lines": 3,
+ }
+ assert agent.data[REMOTE_FRESHNESS_KEY]["/tmp/sample.txt"] == {
+ "mtime": 0,
+ "total_lines": 0,
+ }
+
+
+@dataclass
+class _FakeResponse:
+ message: str
+ break_loop: bool
+ additional: dict | None = None
+
+
+class _FakeTool:
+ def __init__(
+ self,
+ agent,
+ name: str = "text_editor",
+ method: str = "patch",
+ args: dict | None = None,
+ message: str = "",
+ loop_data=None,
+ **kwargs,
+ ) -> None:
+ self.agent = agent
+ self.name = name
+ self.method = method
+ self.args = args or {}
+ self.message = message
+ self.loop_data = loop_data
+
+
+class _FakeAgent:
+ def __init__(self) -> None:
+ self.data = {}
+
+ def read_prompt(self, name: str, **kwargs) -> str:
+ if name.endswith("patch_ok.md"):
+ return (
+ f"{kwargs['path']} patched {kwargs['edit_count']} edits applied "
+ f"{kwargs['total_lines']} lines now\n>>>\n{kwargs['content']}\n<<<"
+ )
+ if name.endswith("patch_need_read.md"):
+ return f"must read {kwargs['path']} first"
+ if name.endswith("patch_stale_read.md"):
+ return f"stale read for {kwargs['path']}"
+ return f"error patching {kwargs.get('path')}: {kwargs.get('error')}"
+
+
+def _load_text_editor_tool(monkeypatch: pytest.MonkeyPatch):
+ calls: list[tuple[str, dict | None]] = []
+
+ tool_stub = types.ModuleType("helpers.tool")
+ tool_stub.Tool = _FakeTool
+ tool_stub.Response = _FakeResponse
+
+ extension_stub = types.ModuleType("helpers.extension")
+
+ async def call_extensions_async(name: str, *args, **kwargs):
+ calls.append((name, kwargs.get("data")))
+
+ extension_stub.call_extensions_async = call_extensions_async
+
+ plugins_stub = types.ModuleType("helpers.plugins")
+ plugins_stub.get_plugin_config = lambda *args, **kwargs: {}
+
+ runtime_stub = types.ModuleType("helpers.runtime")
+
+ async def call_development_function(func, *args, **kwargs):
+ result = func(*args, **kwargs)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ runtime_stub.call_development_function = call_development_function
+
+ monkeypatch.setitem(sys.modules, "helpers.tool", tool_stub)
+ monkeypatch.setitem(sys.modules, "helpers.extension", extension_stub)
+ monkeypatch.setitem(sys.modules, "helpers.plugins", plugins_stub)
+ monkeypatch.setitem(sys.modules, "helpers.runtime", runtime_stub)
+ sys.modules.pop("plugins._text_editor.tools.text_editor", None)
+ module = importlib.import_module("plugins._text_editor.tools.text_editor")
+ return module, calls
+
+
+def test_text_editor_patch_text_does_not_require_prior_read(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ module, calls = _load_text_editor_tool(monkeypatch)
+ target = tmp_path / "sample.txt"
+ target.write_text("line-1\nline-2\nline-3\n", encoding="utf-8")
+ agent = _FakeAgent()
+ tool = module.TextEditor(agent, "text_editor", "patch", {}, "", None)
+
+ response = asyncio.run(
+ tool._patch(
+ path=str(target),
+ patch_text=(
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ "@@ line-1\n"
+ "+inserted\n"
+ "*** End Patch"
+ ),
+ )
+ )
+
+ assert "patched 1 edits applied 4 lines now" in response.message
+ assert "inserted" in response.message
+ assert target.read_text(encoding="utf-8") == (
+ "line-1\ninserted\nline-2\nline-3\n"
+ )
+ realpath = os.path.realpath(target)
+ assert agent.data[module._MTIME_KEY][realpath] == {
+ "mtime": 0,
+ "total_lines": 0,
+ }
+ assert calls[0] == (
+ "text_editor_patch_before",
+ {
+ "path": str(target),
+ "patch_text": (
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ "@@ line-1\n"
+ "+inserted\n"
+ "*** End Patch"
+ ),
+ "edits": [],
+ "mode": "patch_text",
+ },
+ )
+ assert calls[1][0] == "text_editor_patch_after"
+ assert calls[1][1]["mode"] == "patch_text"
+
+
+def test_text_editor_patch_text_rejects_simultaneous_edits(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ module, _calls = _load_text_editor_tool(monkeypatch)
+ target = tmp_path / "sample.txt"
+ target.write_text("line-1\n", encoding="utf-8")
+ tool = module.TextEditor(_FakeAgent(), "text_editor", "patch", {}, "", None)
+
+ response = asyncio.run(
+ tool._patch(
+ path=str(target),
+ edits=[{"from": 1, "to": 1, "content": "updated\n"}],
+ patch_text="@@ line-1\n+inserted",
+ )
+ )
+
+ assert "provide either edits or patch_text" in response.message
+ assert target.read_text(encoding="utf-8") == "line-1\n"
+
+
+def test_text_editor_patch_text_marks_existing_line_state_stale(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ module, _calls = _load_text_editor_tool(monkeypatch)
+ target = tmp_path / "sample.txt"
+ target.write_text("line-1\nline-2\n", encoding="utf-8")
+ realpath = os.path.realpath(target)
+ agent = _FakeAgent()
+ agent.data[module._MTIME_KEY] = {
+ realpath: {"mtime": os.path.getmtime(target), "total_lines": 2}
+ }
+ tool = module.TextEditor(agent, "text_editor", "patch", {}, "", None)
+
+ asyncio.run(
+ tool._patch(
+ path=str(target),
+ patch_text=(
+ "*** Begin Patch\n"
+ "*** Update File: sample.txt\n"
+ "@@ line-1\n"
+ "+inserted\n"
+ "*** End Patch"
+ ),
+ )
+ )
+
+ assert agent.data[module._MTIME_KEY][realpath] == {
+ "mtime": 0,
+ "total_lines": 0,
+ }
+
+
+def test_text_editor_line_edits_still_require_prior_read(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ module, calls = _load_text_editor_tool(monkeypatch)
+ target = tmp_path / "sample.txt"
+ target.write_text("line-1\n", encoding="utf-8")
+ tool = module.TextEditor(_FakeAgent(), "text_editor", "patch", {}, "", None)
+
+ response = asyncio.run(
+ tool._patch(
+ path=str(target),
+ edits=[{"from": 1, "to": 1, "content": "updated\n"}],
+ )
+ )
+
+ assert "must read" in response.message
+ assert target.read_text(encoding="utf-8") == "line-1\n"
+ assert calls == []