Skip to content

The agent that grows with you

fix(memory): replace states and surfaces the whole-entry contract instead of truncating silently (#117952, salvage #109177)

kshitijk4poor67208caac33c
diff --git a/tests/tools/test_memory_tool.py b/tests/tools/test_memory_tool.py
index 7207002cb66..83ca9b4b087 100644
--- a/tests/tools/test_memory_tool.py
+++ b/tests/tools/test_memory_tool.py
@@ -193,6 +193,46 @@ class TestMemoryStoreReplace:
assert "Python 3.12 project" in store.memory_entries
assert "Python 3.11 project" not in store.memory_entries
+ def test_replace_whole_entry_contract(self, store):
+ """Regression for #117952 / #59184: replace commits content as the COMPLETE
+ new entry (old_text only locates it), and the response surfaces the full text
+ that was overwritten so a whole-entry write is never silent."""
+ entry = "RULE A: gate merges. RULE B: ci per HEAD. RULE C: never squash."
+ store.add("memory", entry)
+ result = store.replace("memory", "RULE B: ci per HEAD.", "RULE B: CI is per-head.")
+ assert result["success"] is True
+ assert store.memory_entries == ["RULE B: CI is per-head."]
+ assert result["replaced_entry"] == entry
+
+ def test_replace_same_across_single_batch_and_approval_replay(self, store):
+ """The three dispatch surfaces (store.replace, apply_batch, apply_memory_pending
+ write-approval replay) must agree on the final entry for the same op (#117952)."""
+ from tools.memory_tool import apply_memory_pending
+ entry = "alpha fact. beta fact. gamma fact."
+
+ s1 = store
+ s1.add("memory", entry)
+ assert s1.replace("memory", "beta fact.", "beta fact, updated.")["success"] is True
+ single = s1.memory_entries[0]
+
+ s2 = store.__class__(memory_char_limit=500)
+ s2.add("memory", entry)
+ batch_result = s2.apply_batch("memory", [{"action": "replace", "old_text": "beta fact.",
+ "content": "beta fact, updated."}])
+ assert batch_result["success"] is True
+ assert batch_result["replaced_entries"] == {0: entry}
+ batch = s2.memory_entries[0]
+
+ s3 = store.__class__(memory_char_limit=500)
+ s3.add("memory", entry)
+ payload = {"action": "batch", "target": "memory",
+ "operations": [{"action": "replace", "old_text": "beta fact.",
+ "content": "beta fact, updated."}]}
+ assert apply_memory_pending(payload, s3)["success"] is True
+ replay = s3.memory_entries[0]
+
+ assert single == batch == replay == "beta fact, updated."
+
def test_replace_ambiguous_match(self, store):
store.add("memory", "server A runs nginx")
diff --git a/tools/memory_tool.py b/tools/memory_tool.py
index adf740d5c92..734132dfeea 100644
--- a/tools/memory_tool.py
+++ b/tools/memory_tool.py
@@ -119,7 +119,10 @@ def _validate_single_op(store, action, target, content, old_text) -> Optional[st
"success": False,
"error": (f"'{action}' needs old_text -- a short unique substring of the entry "
f"to {action}. None was provided. Reissue the {action} with old_text "
- f"set to part of one of the current_entries below."),
+ f"set to part of one of the current_entries below."
+ + (" For 'replace', content is the COMPLETE new entry -- the whole "
+ "matched entry is overwritten, not just the old_text span."
+ if action == "replace" else "")),
"current_entries": store._entries_for(target), "usage": store._usage(target)}, ensure_ascii=False)
if action == "replace" and not content:
return tool_error("content is required for 'replace' action.", success=False)
@@ -174,7 +177,8 @@ def memory_tool(action: str = None, target: str = "memory", content: str = None,
store: Optional[MemoryStore] = None) -> str:
"""Tool entry point; returns a JSON string. Single op (action + content/old_text)
or batch (``operations``, atomic against the final budget). ``new_text``
- aliases ``content`` — callers mirror ``old_text`` with it (patch-tool shape)."""
+ aliases ``content`` -- for 'replace' both mean the COMPLETE new entry (the
+ whole matched entry is overwritten; old_text only locates it)."""
if store is None:
return tool_error("Memory is not available. It may be disabled in config or this environment.", success=False)
if content is None and new_text is not None:
@@ -300,15 +304,15 @@ MEMORY_SCHEMA = {
},
"content": {
"type": "string",
- "description": "The entry content. Required for 'add' and 'replace' (single-op shape). Alias: 'new_text' is also accepted (mirrors old_text)."
+ "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)."
},
"old_text": {
"type": "string",
- "description": "REQUIRED for 'replace' and 'remove' (single-op shape): a short unique substring identifying the existing entry to modify. Omit only for 'add'."
+ "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'."
},
"new_text": {
"type": "string",
- "description": "Alias for 'content' (single-op shape). Provided so the replace/remove old_text/new_text pairing works; if both are set, 'content' wins."
+ "description": "Alias for 'content' (single-op shape): the COMPLETE new entry for 'replace', not a patch of old_text. If both are set, 'content' wins."
},
"operations": {
"type": "array",
@@ -321,7 +325,7 @@ MEMORY_SCHEMA = {
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["add", "replace", "remove"]},
- "content": {"type": "string", "description": "Entry content for add/replace. Alias: 'new_text'."},
+ "content": {"type": "string", "description": "Entry content for add/replace. For replace, the COMPLETE new entry (whole entry is overwritten). 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.py
index 36f8026c4e2..92bf30e3e3f 100644
--- a/tools/memory_tool_store.py
+++ b/tools/memory_tool_store.py
@@ -69,6 +69,14 @@ def _find_unique_match(entries: List[str], old_text: str) -> Tuple[Optional[int]
return (matches[0] if matches else None), False
+# Optional third value of an _edit _apply closure: (payload field name, extractor).
+# Surfaced in the success response so an entry-level replace shows the full text it
+# overwrote — a whole-entry write is never silent about the loss (#117952).
+_REPLACED_ENTRY = ("replaced_entry", lambda result: result[2] if len(result) > 2 else None)
+# Batch twin: op index -> full entry text that op's replace overwrote, same reason.
+_BATCH_REPLACED_ENTRIES = ("replaced_entries", lambda result: result[2] if len(result) > 2 else None)
+
+
class MemoryStore:
"""Bounded curated memory with file persistence; one instance per AIAgent.
``_system_prompt_snapshot`` is frozen at load time (prefix-cache stable);
@@ -226,13 +234,16 @@ class MemoryStore:
return self._consolidation_failure(
_error(message + " No operations were applied (batch is all-or-nothing).", usage=self._usage(target)))
- def _mutate(self, target: str, mutate, *, skip_drift: bool = False) -> Dict[str, Any]:
+ def _mutate(self, target: str, mutate, *, skip_drift: bool = False,
+ extra: Optional[Tuple[str, Any]] = None) -> Dict[str, Any]:
"""Lock, re-read from disk, run ``mutate(entries, limit)`` -> ``(new_entries, message)``
or an error dict, then persist and return the success response. The reload aborts
on an existing-but-unreadable file (even append-only ``add`` rewrites the whole
file) and, unless *skip_drift*, on external drift (flushing would discard
un-roundtrippable content). Drift check and parse use the SAME raw snapshot —
- a failed second read used to count as "no drift"."""
+ a failed second read used to count as "no drift". When *extra* is passed, the
+ closure may return a third value; it is extracted and added to the success
+ payload under the named field."""
path = self._path_for(target)
with self._file_lock(path):
raw, read_ok = self._read_raw_checked(path)
@@ -250,7 +261,12 @@ class MemoryStore:
mkdir_under_hermes_home(path.parent)
self._write_file(path, result[0])
- return self._success_response(target, result[1])
+ response = self._success_response(target, result[1])
+ if extra is not None:
+ name, extract = extra
+ if (value := extract(result)) is not None:
+ response[name] = value
+ return response
def add(self, target: str, content: str) -> Dict[str, Any]:
"""Append a new entry. Returns error if it would exceed the char limit."""
@@ -275,7 +291,9 @@ class MemoryStore:
return self._mutate(target, _add, skip_drift=True)
def replace(self, target: str, old_text: str, new_content: str) -> Dict[str, Any]:
- """Find entry containing old_text substring, replace it with new_content."""
+ """Find the entry containing old_text (whole-entry exact match first) and
+ replace the WHOLE entry with new_content — old_text only locates the entry;
+ the matched span is not spliced into it."""
new_content = new_content.strip()
if not old_text.strip():
return _error("old_text cannot be empty.")
@@ -311,31 +329,35 @@ class MemoryStore:
f"Replacement would put memory at {new_total:,}/{limit:,} chars. Shorten the new content, "
f"or 'remove' other stale or less important entries to make room (see current_entries "
f"below), then retry — all in this turn."))
- return replaced, "Entry replaced."
- return self._mutate(target, _apply)
+ return replaced, "Entry replaced.", entries[idx]
+ return self._mutate(target, _apply, extra=_REPLACED_ENTRY)
@staticmethod
- def _apply_batch_op(working: List[str], act: str, content: str, old_text: str, pos: str) -> Optional[str]:
- """Apply one batch op to *working* in place; return an error message or None."""
+ def _apply_batch_op(working: List[str], act: str, content: str, old_text: str,
+ pos: str) -> Tuple[Optional[str], Optional[str]]:
+ """Apply one batch op to *working* in place; return ``(error message, replaced
+ entry text)`` — the second value is the full entry a 'replace' overwrote, so
+ the caller can surface it (#117952); both are None-typed on non-replace paths."""
if act == "add":
if not content:
- return f"{pos}: content is required."
+ return f"{pos}: content is required.", None
if content not in working: # idempotent -- skip duplicate, don't fail the batch
working.append(content)
- return None
+ return None, None
if act not in ("replace", "remove"):
- return f"{pos}: unknown action. Use add, replace, or remove."
+ return f"{pos}: unknown action. Use add, replace, or remove.", None
if not old_text:
- return f"{pos}: old_text is required."
+ return f"{pos}: old_text is required.", None
if act == "replace" and not content:
- return f"{pos}: content is required (use action='remove' to delete)."
+ return f"{pos}: content is required (use action='remove' to delete).", None
idx, ambiguous = _find_unique_match(working, old_text)
if ambiguous:
- return f"{pos}: '{old_text}' matched multiple distinct entries -- be more specific."
+ return f"{pos}: '{old_text}' matched multiple distinct entries -- be more specific.", None
if idx is None:
- return f"{pos}: no entry matched '{old_text}'."
+ return f"{pos}: no entry matched '{old_text}'.", None
+ replaced_text = working[idx] if act == "replace" else None
working[idx:idx + 1] = [content] if act == "replace" else []
- return None
+ return None, replaced_text
def apply_batch(self, target: str, operations: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Apply add/replace/remove ops atomically against the FINAL budget, so one call
@@ -353,12 +375,16 @@ class MemoryStore:
def _apply(entries, limit):
working = list(entries) # only committed if the whole batch validates
+ replaced = {} # op index -> full entry text its replace overwrote (#117952)
for i, op in enumerate(ops):
act = op.get("action")
- msg = self._apply_batch_op(working, act, (op.get("content") or op.get("new_text") or "").strip(),
- (op.get("old_text") or "").strip(), f"Operation {i + 1} ({act or 'unknown'})")
+ msg, replaced_text = self._apply_batch_op(
+ working, act, (op.get("content") or op.get("new_text") or "").strip(),
+ (op.get("old_text") or "").strip(), f"Operation {i + 1} ({act or 'unknown'})")
if msg:
return self._batch_failure(target, msg)
+ if replaced_text is not None:
+ replaced[i] = replaced_text
if entries and not working:
# #103419: a consolidation batch that removes the last entry would
# commit an empty file as a normal successful write. Refuse; single
@@ -375,8 +401,8 @@ class MemoryStore:
f"After applying all {len(operations)} operations, memory would be at "
f"{new_total:,}/{limit:,} chars -- over the limit. Remove or shorten more "
f"entries in the same batch, then retry."))
- return working, f"Applied {len(operations)} operation(s)."
- return self._mutate(target, _apply)
+ return working, f"Applied {len(operations)} operation(s).", replaced
+ return self._mutate(target, _apply, extra=_BATCH_REPLACED_ENTRIES)
def format_for_system_prompt(self, target: str) -> Optional[str]:
"""Frozen load-time snapshot (NOT live state — mid-session writes don't touch
diff --git a/website/docs/user-guide/features/memory.md b/website/docs/user-guide/features/memory.md
index ee3c226c8e6..efee7737fca 100644
--- a/website/docs/user-guide/features/memory.md
+++ b/website/docs/user-guide/features/memory.md
@@ -110,6 +110,8 @@ memory(action="replace", target="memory",
If the substring matches multiple entries, an error is returned asking for a more specific match.
+`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.)
+
## Two Targets Explained
### `memory` — Agent's Personal Notes