Skip to content

The agent that grows with you

fix(memory): make patch edit exactly one span

emozilla412512365ffd
diff --git a/tests/tools/test_memory_patch_action.py b/tests/tools/test_memory_patch_action.py
index 362ad30cd16..e2412344823 100644
--- a/tests/tools/test_memory_patch_action.py
+++ b/tests/tools/test_memory_patch_action.py
@@ -50,6 +50,8 @@ class TestPatchSingleOp:
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
+ # Deleting the whole entry would drop the sibling facts; point at a longer span instead.
+ assert "patch a longer span" in result["error"]
def test_patch_unmatched_old_text_fails_without_write(self, packed_store):
result = json.loads(memory_tool(
@@ -71,13 +73,20 @@ class TestPatchStoreLevel:
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):
+ def test_patch_rejects_a_span_repeated_within_the_entry(self, tmp_path, monkeypatch):
+ # Replacing every occurrence rewrote sibling facts that shared the span.
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"]
+ entry = "Jeff drinks tea in the morning; his wife drinks tea at night"
+ s.add("memory", entry)
+ single = s.patch("memory", "tea", "coffee")
+ batch = s.apply_batch("memory", [{"action": "patch", "old_text": "tea", "content": "coffee"}])
+ for result in (single, batch):
+ assert result["success"] is False
+ assert "appears 2 times" in result["error"]
+ assert s._entries_for("memory") == [entry]
+ assert s.patch("memory", "drinks tea in the morning", "drinks coffee in the morning")["success"] is True
+ assert s._entries_for("memory") == ["Jeff drinks coffee in the morning; his wife drinks tea at night"]
class TestPatchBatch:
@@ -88,6 +97,12 @@ class TestPatchBatch:
assert result["success"] is True
assert packed_store._entries_for("memory") == ["todo: item A; item B done; item C"]
+ def test_patch_op_without_content_points_at_a_longer_span(self, packed_store):
+ result = packed_store.apply_batch("memory", [{"action": "patch", "old_text": "item B", "content": ""}])
+ assert result["success"] is False
+ assert "patch a longer span" in result["error"]
+ assert packed_store._entries_for("memory") == [PACKED]
+
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.
diff --git a/tools/memory_tool.py b/tools/memory_tool.py
index 072207c7e81..7f0639aa768 100644
--- a/tools/memory_tool.py
+++ b/tools/memory_tool.py
@@ -41,7 +41,7 @@ def get_memory_dir() -> Path:
from tools.memory_tool_store import (
- ENTRY_DELIMITER, FAILURE_CLASS, MEMORY_BLOCK_HEADERS, MemoryStore, _scan_memory_content)
+ ENTRY_DELIMITER, FAILURE_CLASS, MEMORY_BLOCK_HEADERS, PATCH_DROP_HINT, MemoryStore, _scan_memory_content)
def load_on_disk_store() -> MemoryStore:
@@ -164,7 +164,8 @@ def _validate_single_op(store, action, target, content, old_text) -> Optional[st
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 tool_error(f"content (the new text for the old_text span) is required for 'patch' action. "
+ f"{PATCH_DROP_HINT}", success=False)
return None
@@ -416,7 +417,7 @@ MEMORY_SCHEMA = {
},
"old_text": {
"type": "string",
- "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'."
+ "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 replaces exactly this span, which must occur once in the entry; 'replace'/'remove' do not splice it). Omit only for 'add'."
},
"new_text": {
"type": "string",
@@ -435,7 +436,7 @@ MEMORY_SCHEMA = {
"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."},
+ "old_text": {"type": "string", "description": "Substring identifying the entry for replace/patch/remove; for patch, also the span replaced (must occur once in the entry)."},
},
"required": ["action"],
},
diff --git a/tools/memory_tool_store.py b/tools/memory_tool_store.py
index 705b81c430f..0cd96477396 100644
--- a/tools/memory_tool_store.py
+++ b/tools/memory_tool_store.py
@@ -122,6 +122,15 @@ def _over_limit(new_total: int, limit: int) -> str:
return f"would put memory at {new_total:,}/{limit:,} chars: free at least {new_total - limit:,} chars"
+# Patch content cannot be empty, and 'remove' would drop the sibling facts in the entry.
+PATCH_DROP_HINT = "To drop text inside an entry, patch a longer span that contains it; 'remove' deletes the whole entry."
+
+
+def _repeated_span_message(old_text: str, count: int) -> str:
+ return (f"'{old_text}' appears {count} times in the matched entry, and patch edits one span. "
+ f"Include more surrounding text so old_text occurs once.")
+
+
def _pinned_index(entries: list[str], matched_entry: str) -> Optional[int]:
"""Index of the exact entry a staged write was reviewed against; None once it is gone (stale)."""
return entries.index(matched_entry) if matched_entry in entries else None
@@ -370,14 +379,14 @@ class MemoryStore:
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)."""
+ """Find the entry containing *old_text* and replace that one span with *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). A span that
+ occurs more than once in the entry is rejected rather than edited everywhere."""
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 _error(f"new_text cannot be empty. {PATCH_DROP_HINT}", "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,
@@ -388,6 +397,8 @@ class MemoryStore:
if isinstance(idx, dict):
return idx
before = entries[idx]
+ if (count := before.count(old_text)) > 1:
+ return _error(_repeated_span_message(old_text, count), "ambiguous")
after = before.replace(old_text, new_text)
if after == before:
return _error(f"Patched entry is unchanged by replacing '{old_text}' "
@@ -479,7 +490,7 @@ class MemoryStore:
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"
+ f"text for the old_text span. {PATCH_DROP_HINT}"), None, "missing_content"
if matched_entry is not None:
idx = _pinned_index(working, matched_entry)
if idx is None:
@@ -493,6 +504,8 @@ class MemoryStore:
return f"{pos}: {miss['error']}", miss.get("closest_entries"), "no_match"
previous_content = working[idx]
if act == "patch":
+ if (count := previous_content.count(old_text)) > 1:
+ return f"{pos}: {_repeated_span_message(old_text, count)}", None, "ambiguous"
patched = previous_content.replace(old_text, content)
if patched == previous_content:
return (f"{pos}: patch is a no-op -- '{old_text}' -> '{content}' leaves the "
diff --git a/website/docs/user-guide/features/memory.md b/website/docs/user-guide/features/memory.md
index 70d2f3b2bc8..52d9db45182 100644
--- a/website/docs/user-guide/features/memory.md
+++ b/website/docs/user-guide/features/memory.md
@@ -93,7 +93,7 @@ The agent uses the `memory` tool with these actions:
- **add** — Add a new memory entry
- **replace** — Replace an existing entry with updated content (uses substring matching via `old_text`)
-- **patch** — Replace matching text inside an existing entry while preserving the rest (uses `old_text` and `new_text`)
+- **patch** — Replace one span inside an existing entry and keep the rest (`old_text` is the span, `content` its replacement)
- **remove** — Remove an entry that's no longer relevant (uses substring matching via `old_text`)
There is no `read` action — memory content is automatically injected into the system prompt at session start. The agent sees its memories as part of its conversation context.
@@ -110,7 +110,7 @@ or staging approval. Correct the payload and retry; use separate calls to update
### Substring Matching
-The `replace` and `remove` actions use short unique substring matching — you don't need the full entry text. The `old_text` parameter just needs to be a unique substring that identifies exactly one entry:
+The `replace`, `patch` and `remove` actions use short unique substring matching — you don't need the full entry text. The `old_text` parameter just needs to be a unique substring that identifies exactly one entry:
```python
# If memory contains "User prefers dark mode in all editors"
@@ -123,6 +123,10 @@ If the substring matches multiple entries, an error is returned asking for a mor
`replace` overwrites the **whole matched entry** with `content` — `old_text` only locates the entry, it is not cut out and replaced. The new `content` must be the complete new entry, including every part of the old one you want to keep. (A whole-entry `old_text` equal to the entry itself is matched exactly and wins over substring matches.)
+`patch` replaces only the `old_text` span inside the matched entry and keeps everything else. The span must
+occur once in that entry; if it appears more than once, the call is rejected and the agent retries with more
+surrounding text. To drop text from an entry, patch a longer span that contains it.
+
## Two Targets Explained
### `memory` — Agent's Personal Notes