The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(memory): add 'patch' action for partial edits so replace stops eating sibling facts
Yuan Lib5ba0abacb33
diff --git a/tests/tools/test_memory_patch_action.py b/tests/tools/test_memory_patch_action.pynew file mode 100644index 00000000000..5bf130cb44d--- /dev/null+++ b/tests/tools/test_memory_patch_action.py@@ -0,0 +1,90 @@+"""Regression for #124582: the memory tool had no find-and-splice edit, so a+partial edit of one clause of a packed multi-fact entry could only be expressed+as a whole-entry ``replace`` — silently discarding the sibling facts in the same+entry. The ``patch`` action splices ``old_text`` → ``new_text`` inside the+matched entry, preserving the rest of the entry verbatim."""++import json++import pytest++from tools.memory_tool import memory_tool+from tools.memory_tool_store import MemoryStore++PACKED = "todo: item A; item B; item C"+++def packed_store(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ s = MemoryStore(memory_char_limit=500, user_char_limit=300)+ s.add("memory", PACKED)+ return s+++class TestPatchSingleOp:+ def test_patch_splices_only_the_matched_span(self, packed_store):+ result = json.loads(memory_tool(+ action="patch", old_text="item B", new_text="item B done", store=packed_store))+ assert result["success"] is True+ assert packed_store._entries_for("memory") == ["todo: item A; item B done; item C"]++ def test_patch_returns_before_and_after(self, packed_store):+ result = json.loads(memory_tool(+ action="patch", old_text="item B", new_text="item B done", store=packed_store))+ assert result["patched_entry_before"] == PACKED+ assert result["patched_entry_after"] == "todo: item A; item B done; item C"++ def test_patch_requires_old_text(self, packed_store):+ result = json.loads(memory_tool(action="patch", new_text="x", store=packed_store))+ assert result["success"] is False+ assert "old_text" in result["error"]++ def test_patch_requires_new_text(self, packed_store):+ result = json.loads(memory_tool(action="patch", old_text="item B", store=packed_store))+ assert result["success"] is False++ def test_patch_unmatched_old_text_fails_without_write(self, packed_store):+ result = json.loads(memory_tool(+ action="patch", old_text="item Z", new_text="whatever", store=packed_store))+ assert result["success"] is False+ assert packed_store._entries_for("memory") == [PACKED]++ def test_patch_multi_entry_match_is_rejected(self, packed_store):+ packed_store.add("memory", "also mentions item B elsewhere")+ result = json.loads(memory_tool(+ action="patch", old_text="item B", new_text="x", store=packed_store))+ assert result["success"] is False+ assert packed_store._entries_for("memory") == [PACKED, "also mentions item B elsewhere"]+++class TestPatchStoreLevel:+ def test_store_patch_method(self, packed_store):+ result = packed_store.patch("memory", "item B", "item B done")+ assert result["success"] is True+ assert packed_store._entries_for("memory") == ["todo: item A; item B done; item C"]++ def test_patch_all_occurrences_within_entry(self, tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ s = MemoryStore(memory_char_limit=500)+ s.add("memory", "x: see B and again B")+ result = s.patch("memory", "B", "C")+ assert result["success"] is True+ assert s._entries_for("memory") == ["x: see C and again C"]+++class TestPatchBatch:+ def test_patch_op_in_batch(self, packed_store):+ result = packed_store.apply_batch("memory", [+ {"action": "patch", "old_text": "item B", "new_text": "item B done"},+ ])+ assert result["success"] is True+ assert packed_store._entries_for("memory") == ["todo: item A; item B done; item C"]++ def test_patch_op_counts_as_destructive_for_staging(self, packed_store):+ # patch rewrites part of an entry: it must be staged (matched_entry pinned)+ # exactly like replace, never replayed against a newer entry.+ from tools.memory_tool import destructive_ops+ ops = destructive_ops({"action": "batch", "operations": [+ {"action": "patch", "old_text": "item B", "new_text": "x"}]})+ assert [op["action"] for op in ops] == ["patch"]diff --git a/tools/memory_tool.py b/tools/memory_tool.pyindex 6151f1e7a73..072207c7e81 100644--- a/tools/memory_tool.py+++ b/tools/memory_tool.py@@ -110,7 +110,11 @@ _STORE_ACTIONS = {lambda label, content, old_text: (f"replace in {label}",f"entry matching: {old_text}\nwhole entry becomes: {content}")),"remove": (lambda store, target, content, old_text, entry=None: store.remove(target, old_text, entry),- lambda label, content, old_text: (f"remove from {label}", old_text or ""))}+ lambda label, content, old_text: (f"remove from {label}", old_text or "")),+ "patch": (lambda store, target, content, old_text, entry=None: store.patch(target, old_text, content, entry),+ lambda label, content, old_text: (f"patch in {label}",+ f"entry matching: {old_text}\nspan '{old_text}' becomes: {content} "+ "(rest of the entry is kept)"))}def _batch_op_line(op: dict[str, Any]) -> str:@@ -118,6 +122,8 @@ def _batch_op_line(op: dict[str, Any]) -> str:act, content, old = op.get("action", "?"), op.get("content") or op.get("new_text") or "", op.get("old_text", "")if act == "remove":return f"- remove: {old}"+ if act == "patch":+ return f"- patch span '{old}' -> '{content}' (rest of the entry is kept)"# Whole-entry contract (#117952): the approver must not read this as a span patch.return (f"- replace entry matching '{old}' -> whole entry becomes: {content}" if act == "replace"else f"- {act}: {content}")@@ -142,7 +148,7 @@ def _validate_single_op(store, action, target, content, old_text) -> Optional[stif action == "add" and not content:FAILURE_CLASS.set("missing_content")return tool_error("Content is required for 'add' action.", success=False)- if action in ("replace", "remove") and not old_text:+ if action in ("replace", "remove", "patch") and not old_text:FAILURE_CLASS.set("missing_old_text")replace_hint = (" For 'replace', content is the COMPLETE new entry -- the whole ""matched entry is overwritten, not just the old_text span."@@ -156,10 +162,13 @@ def _validate_single_op(store, action, target, content, old_text) -> Optional[stif action == "replace" and not content:FAILURE_CLASS.set("missing_content")return tool_error("content is required for 'replace' action.", success=False)+ if action == "patch" and not content:+ FAILURE_CLASS.set("missing_content")+ return tool_error("content (the new span text) is required for 'patch' action.", success=False)return None-_BG_DELETE_ACTIONS = ("replace", "remove")+_BG_DELETE_ACTIONS = ("replace", "remove", "patch")def destructive_ops(payload: dict[str, Any]) -> list[dict[str, Any]]:@@ -265,11 +274,11 @@ def _memory_tool(action, target, content, old_text, new_text, operations, store)# *why* the call was malformed and can trigger repeated retries. (#64291)if not action and not operations:return _invalid(- "Missing required parameter: provide 'action' (add/replace/remove) "+ "Missing required parameter: provide 'action' (add/replace/patch/remove) ""or 'operations' (batch list). Got neither.")if action not in _STORE_ACTIONS:- return _invalid(f"Unknown action '{action}'. Use: add, replace, remove")+ return _invalid(f"Unknown action '{action}'. Use: add, replace, patch, remove")invalid = (_validate_single_op(store, action, target, content, old_text)or _background_delete_gate(store, action, None, target, content, old_text)or _apply_write_gate(store, action, target, content, old_text))@@ -390,8 +399,11 @@ MEMORY_SCHEMA = {"properties": {"action": {"type": "string",- "enum": ["add", "replace", "remove"],- "description": "The action to perform (single-op shape). Omit when using 'operations'."+ "enum": ["add", "replace", "patch", "remove"],+ "description": ("The action to perform (single-op shape). Omit when using 'operations'. "+ "'patch' edits ONE SPAN inside the matched entry (old_text -> content, rest of the "+ "entry kept) -- prefer it when changing part of a multi-fact entry instead of "+ "rewriting the whole entry with 'replace'.")},"target": {"type": "string",@@ -400,11 +412,11 @@ MEMORY_SCHEMA = {},"content": {"type": "string",- "description": "The entry content. Required for 'add' and 'replace'. For 'replace' it is the COMPLETE new entry text: the whole matched entry is overwritten, so include everything you want to keep. Alias: 'new_text' is also accepted (same full-entry meaning)."+ "description": "The entry content. Required for 'add', 'replace' and 'patch'. For 'replace' it is the COMPLETE new entry text: the whole matched entry is overwritten, so include everything you want to keep. For 'patch' it is only the NEW SPAN TEXT that replaces old_text inside the matched entry. Alias: 'new_text' is also accepted."},"old_text": {"type": "string",- "description": "REQUIRED for 'replace' and 'remove' (single-op shape): a short unique substring IDENTIFYING the existing entry to modify -- it locates the entry, it is not spliced out. Omit only for 'add'."+ "description": "REQUIRED for 'replace', 'patch' and 'remove' (single-op shape): a short unique substring IDENTIFYING the existing entry to modify -- it locates the entry ('patch' also splices exactly this span out; 'replace'/'remove' do not splice it). Omit only for 'add'."},"new_text": {"type": "string",@@ -420,8 +432,8 @@ MEMORY_SCHEMA = {"items": {"type": "object","properties": {- "action": {"type": "string", "enum": ["add", "replace", "remove"]},- "content": {"type": "string", "description": "Entry content for add/replace. For replace, the COMPLETE new entry (whole entry is overwritten). Alias: 'new_text'."},+ "action": {"type": "string", "enum": ["add", "replace", "patch", "remove"]},+ "content": {"type": "string", "description": "Entry content for add/replace. For replace, the COMPLETE new entry (whole entry is overwritten); for patch, the NEW SPAN TEXT replacing old_text inside the entry. Alias: 'new_text'."},"new_text": {"type": "string", "description": "Alias for 'content' in a batch op."},"old_text": {"type": "string", "description": "Substring identifying the entry for replace/remove."},},diff --git a/tools/memory_tool_store.py b/tools/memory_tool_store.pyindex 525956e0b87..add74b1f417 100644--- a/tools/memory_tool_store.py+++ b/tools/memory_tool_store.py@@ -368,6 +368,43 @@ class MemoryStore:return _error(scan_error, "scan_blocked")return self._edit(target, old_text.strip(), new_content, matched_entry)+ def patch(self, target: str, old_text: str, new_text: str,+ matched_entry: Optional[str] = None) -> dict[str, Any]:+ """Find the entry containing *old_text* and splice every occurrence of it into+ *new_text* — the rest of the entry is preserved verbatim. This is the partial-edit+ shape ``replace`` deliberately is not (replace overwrites the WHOLE entry)."""+ if not (old_text or "").strip():+ return _error("old_text cannot be empty.", "missing_old_text")+ if new_text is None or not str(new_text).strip():+ return _error("new_text cannot be empty. Use 'remove' to delete entries, "+ "or an empty-sense edit is not a change.", "missing_content")+ return self._patch(target, old_text.strip(), str(new_text), matched_entry)++ def _patch(self, target: str, old_text: str, new_text: str,+ matched_entry: Optional[str] = None) -> dict[str, Any]:+ """Locked find-and-splice inside the matched entry (#124582)."""+ def _apply(entries, limit):+ idx = self._locate(entries, old_text, "patch", matched_entry)+ if isinstance(idx, dict):+ return idx+ before = entries[idx]+ after = before.replace(old_text, new_text)+ if after == before:+ return _error(f"Patched entry is unchanged by replacing '{old_text}' "+ f"with '{new_text}'.", "invalid_args")+ if scan_error := _scan_memory_content(after):+ return _error(scan_error, "scan_blocked")+ patched = entries[:idx] + [after] + entries[idx + 1:]+ new_total = len(ENTRY_DELIMITER.join(patched))+ if new_total > limit:+ return self._failure_with_entries(target, (+ f"Patch would put memory at {new_total:,}/{limit:,} chars. Shorten the new "+ f"text, or 'remove' other stale or less important entries to make room "+ f"(see current_entries below), then retry — all in this turn."))+ return patched, "Entry patched.", {+ "patched_entry_before": before, "patched_entry_after": after}+ return self._mutate(target, _apply)+def remove(self, target: str, old_text: str, matched_entry: Optional[str] = None) -> dict[str, Any]:"""Remove the entry containing old_text substring."""if not old_text.strip():@@ -433,13 +470,16 @@ class MemoryStore:if content not in working: # idempotent -- skip duplicate, don't fail the batchworking.append(content)return None, None, "none"- if act not in ("replace", "remove"):- return f"{pos}: unknown action. Use add, replace, or remove.", None, "invalid_args"+ if act not in ("replace", "remove", "patch"):+ return f"{pos}: unknown action. Use add, replace, patch, or remove.", None, "invalid_args"if not old_text:return f"{pos}: old_text is required.", None, "missing_old_text"if act == "replace" and not content:return (f"{pos}: content is required — set this operation object's own 'content' to the COMPLETE "f"new entry (or use action='remove' to delete)."), None, "missing_content"+ if act == "patch" and not content:+ return (f"{pos}: content is required — set this operation object's own 'content' to the new "+ f"text for the old_text span (or use action='remove' to delete)."), None, "missing_content"if matched_entry is not None:idx = _pinned_index(working, matched_entry)if idx is None:@@ -452,7 +492,16 @@ class MemoryStore:miss = _no_match_error(working, old_text, act)return f"{pos}: {miss['error']}", miss.get("closest_entries"), "no_match"previous_content = working[idx]- working[idx:idx + 1] = [content] if act == "replace" else []+ if act == "patch":+ patched = previous_content.replace(old_text, content)+ if patched == previous_content:+ return (f"{pos}: patch is a no-op -- '{old_text}' -> '{content}' leaves the "+ f"entry unchanged."), None, "invalid_args"+ if scan_error := _scan_memory_content(patched):+ return f"{pos}: {scan_error}", None, "scan_blocked"+ working[idx:idx + 1] = [patched]+ else:+ working[idx:idx + 1] = [content] if act == "replace" else []return None, previous_content, "none"def apply_batch(self, target: str, operations: list[dict[str, Any]]) -> dict[str, Any]: