The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(memory): pin a staged replace/remove to the entry the approver reviewed
John Paul Solivab96e88b245ce
diff --git a/hermes_cli/write_approval_commands.py b/hermes_cli/write_approval_commands.pyindex 590279154b5..71d0b3dfab0 100644--- a/hermes_cli/write_approval_commands.py+++ b/hermes_cli/write_approval_commands.py@@ -23,6 +23,8 @@ def _fmt_pending_list(subsystem: str) -> str:origin = r.get("origin", "foreground")tag = " [auto]" if origin == "background_review" else ""lines.append(f" {r['id']}{tag} {r.get('summary', '')}")+ if subsystem == wa.MEMORY:+ lines.extend(f" {line}" for line in _matched_entries(r.get("payload")))lines.append("")lines.append(f"Apply: /{subsystem} approve <id> Reject: /{subsystem} reject <id>")if subsystem == wa.SKILLS:@@ -74,13 +76,14 @@ def _approve(subsystem: str, rest: List[str], memory_store) -> str:return f"No pending {subsystem} write with id '{target}'."targets = [rec]- applied, failed, overwritten = 0, [], []+ applied, failed, overwritten, removed = 0, [], [], []for rec in targets:ok, msg, result = _apply_one(subsystem, rec, memory_store)if ok:wa.discard_pending(subsystem, rec["id"])applied += 1- overwritten.extend(f" {rec['id']}: {text}" for text in _replaced_entries(result))+ overwritten.extend(f" {rec['id']}: {text}" for text in _changed_entries(result, "replaced"))+ removed.extend(f" {rec['id']}: {text}" for text in _changed_entries(result, "removed"))else:failed.append(f"{rec['id']}: {msg}")@@ -90,19 +93,33 @@ def _approve(subsystem: str, rest: List[str], memory_store) -> str:# is the last person who can notice a clause went missing, so show what was lost.out.append("Overwrote entire entry (re-add anything you still need):")out.extend(overwritten)+ if removed:+ out.append("Removed entry (re-add anything you still need):")+ out.extend(removed)if failed:out.append("Failed:")out.extend(f" {f}" for f in failed)return "\n".join(out)-def _replaced_entries(result: dict) -> List[str]:- """Full text of every entry a memory replace overwrote, single-op or batch shape."""- single = result.get("replaced_entry")- batch = result.get("replaced_entries") or {}+def _changed_entries(result: dict, kind: str) -> List[str]:+ """Full text of every entry a memory replace overwrote (``kind="replaced"``) or remove+ deleted (``"removed"``), single-op or batch shape."""+ single = result.get(f"{kind}_entry")+ batch = result.get(f"{kind}_entries") or {}return ([single] if single else []) + [batch[k] for k in sorted(batch, key=int)]+def _matched_entries(payload) -> List[str]:+ """The full entry each staged memory replace/remove is pinned to: the summary shows only+ the old_text search string, and approval applies to this entry, not to that search."""+ if not isinstance(payload, dict):+ return []+ ops = payload.get("operations") if payload.get("action") == "batch" else [payload]+ return [f"{op['action']}s entry: {op['matched_entry']}" for op in (ops if isinstance(ops, list) else [])+ if isinstance(op, dict) and op.get("action") in ("replace", "remove") and op.get("matched_entry")]++def _apply_one(subsystem: str, rec, memory_store):"""``(ok, error, result)`` — *result* is the applier's full payload (empty on exceptions)."""payload = rec.get("payload", {})diff --git a/tests/tools/test_write_approval.py b/tests/tools/test_write_approval.pyindex 3a5cb6adf0a..03542fdcbc1 100644--- a/tests/tools/test_write_approval.py+++ b/tests/tools/test_write_approval.py@@ -185,6 +185,70 @@ def test_handle_approve_surfaces_overwritten_entry(hermes_home):assert store.memory_entries == ["RULE B: CI is per-head."]+_KEPT = "Repo lives in ~/src/app; tests via make test"+_REVIEWED = "Staging DB: pg-staging-2 (old cluster, retiring)"+++def _review_stages_remove(shape):+ """Seed memory, then stage a remove the way the unattended background review does."""+ from tools.memory_tool import MemoryStore, memory_tool+ from tools.skill_provenance import (reset_current_write_origin, reset_review_attended,+ set_current_write_origin, set_review_attended)+ store = MemoryStore(); store.load_from_disk()+ for entry in (_KEPT, _REVIEWED):+ assert store.add("memory", entry)["success"]+ op = {"action": "remove", "old_text": "Staging DB"}+ kwargs = op if shape == "single" else {"operations": [op, {"action": "add", "content": "Deploys via make ship"}]}+ origin, attended = set_current_write_origin("background_review"), set_review_attended(False)+ try:+ staged = json.loads(memory_tool(target="memory", store=store, **kwargs))+ finally:+ reset_review_attended(attended)+ reset_current_write_origin(origin)+ assert staged["staged"] is True, staged+ return store, staged["pending_id"]++[email protected]("shape", ["single", "batch"])+def test_approve_refuses_staged_remove_whose_entry_changed(hermes_home, shape):+ """Approval re-ran the staged old_text search against the file as it is THEN, so it+ deleted the newer entry the live agent had written in place, which the approver never saw."""+ from hermes_cli.write_approval_commands import handle_pending_subcommand+ from tools.memory_tool import load_on_disk_store, memory_tool+ from tools import write_approval as wa+ store, pid = _review_stages_remove(shape)+ newer = "Staging DB: pg-staging-3 (migrated 2026-09-20, creds in vault 'stg')"+ assert json.loads(memory_tool(action="replace", old_text="pg-staging-2", content=newer, store=store))["success"]++ out = handle_pending_subcommand(wa.MEMORY, ["approve", pid], memory_store=load_on_disk_store())++ assert load_on_disk_store().memory_entries == [_KEPT, newer], out+ assert "changed since it was staged" in out+ assert wa.get_pending(wa.MEMORY, pid) is not None+ # The pending list shows the whole entry the write targets, not just its search string.+ assert _REVIEWED in handle_pending_subcommand(wa.MEMORY, ["pending"])++[email protected]("shape,legacy", [("single", False), ("batch", False), ("single", True)])+def test_approve_names_the_entry_a_remove_deleted(hermes_home, shape, legacy):+ """Approve listed what a replace overwrote but was silent about what a remove deleted,+ including a record staged before removes were pinned to their full entry."""+ from hermes_cli.write_approval_commands import handle_pending_subcommand+ from tools.memory_tool import load_on_disk_store+ from tools import write_approval as wa+ _store, pid = _review_stages_remove(shape)+ if legacy:+ path = wa._pending_path(wa.MEMORY, pid)+ record = json.loads(path.read_text(encoding="utf-8"))+ record["payload"].pop("matched_entry", None)+ path.write_text(json.dumps(record), encoding="utf-8")++ out = handle_pending_subcommand(wa.MEMORY, ["approve", pid], memory_store=load_on_disk_store())++ assert _REVIEWED not in load_on_disk_store().memory_entries, out+ assert _REVIEWED in out++def test_handle_approval_on(hermes_home):from hermes_cli.write_approval_commands import handle_pending_subcommandfrom tools import write_approval as wadiff --git a/tools/memory_tool.py b/tools/memory_tool.pyindex f770bb24662..897faa28d19 100644--- a/tools/memory_tool.py+++ b/tools/memory_tool.py@@ -61,7 +61,28 @@ def load_on_disk_store() -> "MemoryStore":return store-def _gate_or_stage(summary: str, detail: str, payload: Dict[str, Any]) -> Optional[str]:+def _pin_matched_entries(store: "MemoryStore", payload: Dict[str, Any]) -> Optional[str]:+ """Record on each staged replace/remove the FULL entry its old_text selects now. Approval+ then applies to exactly the entry the approver reviewed and refuses if it changed:+ re-running the old_text search at approve time could hit a newer entry that still+ contains it. Returns the JSON error when the search fails now, as the direct write would."""+ target = payload.get("target", "memory")+ if payload.get("action") == "batch":+ ops = [op or {} for op in payload["operations"]]+ result = store.resolve_batch_entries(target, ops)+ if result.get("success"):+ payload["operations"] = [op if entry is None else {**op, "matched_entry": entry}+ for op, entry in zip(ops, result["matched_entries"])]+ elif payload.get("action") in _BG_DELETE_ACTIONS:+ result = store.resolve_entry(target, payload.get("old_text") or "", payload["action"])+ if result.get("success"):+ payload["matched_entry"] = result["matched_entry"]+ else:+ return None+ return None if result.get("success") else json.dumps(result, ensure_ascii=False)+++def _gate_or_stage(store: "MemoryStore", summary: str, detail: str, payload: Dict[str, Any]) -> Optional[str]:"""JSON tool-result string when the write must NOT proceed (blocked or stagedfor approval), None to proceed. Fails open if the gate module can't load."""try:@@ -73,6 +94,8 @@ def _gate_or_stage(summary: str, detail: str, payload: Dict[str, Any]) -> Optionreturn Noneif decision.blocked:return tool_error(decision.message, success=False)+ if (unmatched := _pin_matched_entries(store, payload)) is not None:+ return unmatchedrecord = wa.stage_write(wa.MEMORY, payload, summary=f"{summary}: {detail[:120]}", origin=wa.current_origin())return json.dumps({"success": True, "staged": True, "pending_id": record["id"], "message": decision.message},ensure_ascii=False)@@ -80,12 +103,12 @@ def _gate_or_stage(summary: str, detail: str, payload: Dict[str, Any]) -> Option# action -> (store call, gate (summary, detail) text) for the live tool path and staged replay._STORE_ACTIONS = {- "add": (lambda store, target, content, old_text: store.add(target, content),+ "add": (lambda store, target, content, old_text, entry=None: store.add(target, content),lambda label, content, old_text: (f"add to {label}", content or "")),- "replace": (lambda store, target, content, old_text: store.replace(target, old_text, content),+ "replace": (lambda store, target, content, old_text, entry=None: store.replace(target, old_text, content, entry),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: store.remove(target, old_text),+ "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 ""))}@@ -99,15 +122,15 @@ def _batch_op_line(op: Dict[str, Any]) -> str:else f"- {act}: {content}")-def _apply_write_gate(action: str, target: str, content: Optional[str], old_text: Optional[str],- operations: Optional[List[Dict[str, Any]]] = None) -> Optional[str]:+def _apply_write_gate(store: "MemoryStore", action: str, target: str, content: Optional[str],+ old_text: Optional[str], operations: Optional[List[Dict[str, Any]]] = None) -> Optional[str]:"""Gate one mutating op, or (``operations`` set) a whole batch as a single unit."""label = "user profile" if target == "user" else "memory"if operations is not None:- return _gate_or_stage(f"apply {len(operations)} op(s) to {label}",+ return _gate_or_stage(store, f"apply {len(operations)} op(s) to {label}","\n".join(_batch_op_line(op) for op in operations),{"action": "batch", "target": target, "operations": operations})- return _gate_or_stage(*_STORE_ACTIONS[action][1](label, content, old_text),+ return _gate_or_stage(store, *_STORE_ACTIONS[action][1](label, content, old_text),{"action": action, "target": target, "content": content, "old_text": old_text})@@ -135,7 +158,8 @@ def _validate_single_op(store, action, target, content, old_text) -> Optional[st_BG_DELETE_ACTIONS = ("replace", "remove")-def _background_delete_gate(action, operations, target="memory", content=None, old_text=None) -> Optional[str]:+def _background_delete_gate(store, action, operations, target="memory", content=None,+ old_text=None) -> Optional[str]:"""Fail-closed operation gate for unattended background-review forks (#105921): ``add``stays available (it is all any review prompt asks for), while ``replace``/``remove`` —single or inside a batch — are never applied unattended. The op is staged in the pending@@ -156,6 +180,8 @@ def _background_delete_gate(action, operations, target="memory", content=None, odetail = ("; ".join(_batch_op_line(op) for op in operations) if operations is not Noneelse _batch_op_line({"action": action, "content": content, "old_text": old_text}))try:+ if (unmatched := _pin_matched_entries(store, payload)) is not None:+ return unmatchedfrom tools import write_approval as warecord = wa.stage_write(wa.MEMORY, payload,@@ -194,19 +220,19 @@ def memory_tool(action: str = None, target: str = "memory", content: str = None,if operations:if not isinstance(operations, list):return tool_error("operations must be a list of {action, content?, old_text?} objects.", success=False)- denied = _background_delete_gate(action, operations, target)+ denied = _background_delete_gate(store, action, operations, target)if denied is not None:return denied# Approval gate: stages (background/gateway) or prompts inline (CLI); off by default.- gate_result = _apply_write_gate("batch", target, None, None, operations)+ gate_result = _apply_write_gate(store, "batch", target, None, None, operations)if gate_result is not None:return gate_resultreturn json.dumps(store.apply_batch(target, operations), ensure_ascii=False)if action not in _STORE_ACTIONS:return tool_error(f"Unknown action '{action}'. Use: add, replace, remove", success=False)invalid = (_validate_single_op(store, action, target, content, old_text)- or _background_delete_gate(action, None, target, content, old_text)- or _apply_write_gate(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))if invalid is not None:return invalidreturn json.dumps(_STORE_ACTIONS[action][0](store, target, content, old_text), ensure_ascii=False)@@ -254,7 +280,9 @@ def _memory_target_error(store: "MemoryStore", target: str) -> Optional[Dict[strdef apply_memory_pending(payload: Dict[str, Any], store: "MemoryStore") -> Dict[str, Any]:- """Replay a staged write against the store, bypassing the gate (/memory approve)."""+ """Replay a staged write against the store, bypassing the gate (/memory approve). A+ replace/remove pinned to its ``matched_entry`` applies to that exact entry or is refused;+ records staged before pinning still replay by old_text (approve lists what they removed)."""action, target = payload.get("action"), payload.get("target", "memory")target_error = _memory_target_error(store, target)if target_error is not None:@@ -263,7 +291,8 @@ def apply_memory_pending(payload: Dict[str, Any], store: "MemoryStore") -> Dict[return store.apply_batch(target, payload.get("operations") or [])if action not in _STORE_ACTIONS:return {"success": False, "error": f"Unknown staged action '{action}'."}- return _STORE_ACTIONS[action][0](store, target, payload.get("content") or "", payload.get("old_text") or "")+ return _STORE_ACTIONS[action][0](store, target, payload.get("content") or "", payload.get("old_text") or "",+ payload.get("matched_entry"))MEMORY_SCHEMA = {diff --git a/tools/memory_tool_store.py b/tools/memory_tool_store.pyindex d340333ee1c..ddadb2f3d46 100644--- a/tools/memory_tool_store.py+++ b/tools/memory_tool_store.py@@ -69,6 +69,12 @@ def _find_unique_match(entries: List[str], old_text: str) -> Tuple[Optional[int]return (matches[0] if matches else None), False+def _stale_entry_message(entry: str) -> str:+ return (f"Entry changed since it was staged, so this write was not applied: '{entry}' is no longer "+ f"in memory as reviewed. Recreate the change against the current entry or reject it; the "+ f"pending record has been preserved.")++# Optional third value of an _apply closure: a dict merged into the success payload —# e.g. the full text an entry-level replace overwrote, so a whole-entry write is never# silent about the loss (#117952). Same convention as _error(**extra).@@ -282,7 +288,8 @@ class MemoryStore:# content) but still refuse a failed read — add rewrites the WHOLE file.return self._mutate(target, _add, skip_drift=True)- def replace(self, target: str, old_text: str, new_content: str) -> Dict[str, Any]:+ def replace(self, target: str, old_text: str, new_content: str,+ matched_entry: Optional[str] = None) -> Dict[str, Any]:"""Find the entry containing old_text (whole-entry exact match first) andreplace the WHOLE entry with new_content — old_text only locates the entry;the matched span is not spliced into it."""@@ -293,25 +300,47 @@ class MemoryStore:return _error("new_content cannot be empty. Use 'remove' to delete entries.")if scan_error := _scan_memory_content(new_content):return _error(scan_error)- return self._edit(target, old_text.strip(), new_content)+ return self._edit(target, old_text.strip(), new_content, matched_entry)- def remove(self, target: str, old_text: str) -> Dict[str, Any]:+ 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():return _error("old_text cannot be empty.")- return self._edit(target, old_text.strip(), None)-- def _edit(self, target: str, old_text: str, new_content: Optional[str]) -> Dict[str, Any]:+ return self._edit(target, old_text.strip(), None, matched_entry)++ def _locate(self, entries: List[str], old_text: str, verb: str, matched_entry: Optional[str] = None):+ """Index of the entry *old_text* selects, or the error dict the edit returns. A write+ staged for approval carries the FULL entry it was reviewed against (*matched_entry*):+ only that exact entry qualifies, so replay never hits a newer entry that still+ contains old_text."""+ if matched_entry is not None:+ return entries.index(matched_entry) if matched_entry in entries else _error(+ _stale_entry_message(matched_entry))+ idx, ambiguous = _find_unique_match(entries, old_text)+ if ambiguous:+ return _error(f"Multiple entries matched '{old_text}'. Be more specific.",+ matches=[e[:80] + ("..." if len(e) > 80 else "") for e in entries if old_text in e])+ if idx is None:+ return self._consolidation_failure(_error(+ f"No entry matched '{old_text}'. Check current_entries below and retry with the exact text "+ f"of the entry you want to {verb}.", current_entries=entries))+ return idx++ def resolve_entry(self, target: str, old_text: str, verb: str) -> Dict[str, Any]:+ """``{"success": True, "matched_entry": <full entry>}`` for the entry *old_text* selects+ now, read under the lock, or the error the direct edit would return."""+ def _resolve(entries, limit):+ idx = self._locate(entries, old_text.strip(), verb)+ return idx if isinstance(idx, dict) else {"success": True, "matched_entry": entries[idx]}+ return self._mutate(target, _resolve, skip_drift=True)++ def _edit(self, target: str, old_text: str, new_content: Optional[str],+ matched_entry: Optional[str] = None) -> Dict[str, Any]:"""Locked replace (``new_content`` set) or remove (None) of the entry matching *old_text*."""def _apply(entries, limit):- idx, ambiguous = _find_unique_match(entries, old_text)- if ambiguous:- return _error(f"Multiple entries matched '{old_text}'. Be more specific.",- matches=[e[:80] + ("..." if len(e) > 80 else "") for e in entries if old_text in e])- if idx is None:- return self._consolidation_failure(_error(- f"No entry matched '{old_text}'. Check current_entries below and retry with the exact text "- f"of the entry you want to {'replace' if new_content else 'remove'}.", current_entries=entries))+ idx = self._locate(entries, old_text, "replace" if new_content else "remove", matched_entry)+ if isinstance(idx, dict):+ return idxreplaced = entries[:idx] + ([] if new_content is None else [new_content]) + entries[idx + 1:]if new_content is None:return replaced, "Entry removed.", {"removed_entry": entries[idx]}@@ -326,10 +355,11 @@ class MemoryStore:@staticmethoddef _apply_batch_op(working: List[str], act: str, content: str, old_text: str,- pos: str) -> Tuple[Optional[str], Optional[str]]:+ pos: str, matched_entry: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:"""Apply one batch op to *working*; return ``(error message, previous content)``.Previous content is captured before each replace/remove, under the store lock.It is published only after the entire batch has been validated and persisted.+ A staged op's *matched_entry* selects exactly that entry, as in ``_locate``."""if act == "add":if not content:@@ -343,7 +373,12 @@ class MemoryStore:return f"{pos}: old_text is required.", Noneif act == "replace" and not content:return f"{pos}: content is required (use action='remove' to delete).", None- idx, ambiguous = _find_unique_match(working, old_text)+ if matched_entry is not None:+ if matched_entry not in working:+ return f"{pos}: {_stale_entry_message(matched_entry)}", None+ idx, ambiguous = working.index(matched_entry), False+ else:+ idx, ambiguous = _find_unique_match(working, old_text)if ambiguous:return f"{pos}: '{old_text}' matched multiple distinct entries -- be more specific.", Noneif idx is None:@@ -374,7 +409,8 @@ class MemoryStore:act = op.get("action")msg, previous_content = 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'})")+ (op.get("old_text") or "").strip(), f"Operation {i + 1} ({act or 'unknown'})",+ op.get("matched_entry"))if msg:return self._batch_failure(target, msg)if previous_content is not None:@@ -403,6 +439,23 @@ class MemoryStore:return working, f"Applied {len(operations)} operation(s).", replaced_fieldsreturn self._mutate(target, _apply)+ def resolve_batch_entries(self, target: str, operations: List[Dict[str, Any]]) -> Dict[str, Any]:+ """``{"success": True, "matched_entries": [...]}``: per op, the FULL entry its+ replace/remove selects now (None for add), in batch order and read under the lock,+ or the error the direct batch would return for that op."""+ def _resolve(entries, limit):+ working, matched = list(entries), []+ for i, op in enumerate(operations):+ act = op.get("action")+ msg, previous_content = 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)+ matched.append(previous_content)+ return {"success": True, "matched_entries": matched}+ return self._mutate(target, _resolve, skip_drift=True)+def format_for_system_prompt(self, target: str) -> Optional[str]:"""Frozen load-time snapshot (NOT live state — mid-session writes don't touchit, preserving the prefix cache); None if empty."""diff --git a/website/docs/user-guide/features/memory.md b/website/docs/user-guide/features/memory.mdindex afe78f83d33..02407314ab3 100644--- a/website/docs/user-guide/features/memory.md+++ b/website/docs/user-guide/features/memory.md@@ -317,6 +317,12 @@ This is the answer to "the agent saved a wrong assumption about me": set`write_approval: true`, and every save — especially the unprompted backgroundones — waits for your yes/no before it ever enters your profile.+A staged `replace` or `remove` (the background review stages these even with the+gate off) records the full entry it targets, and `/memory pending` shows it.+Approval applies to exactly that entry: if it changed after the write was staged,+the write is refused and stays pending for you to reject. `/memory approve` lists+the full text of every entry it overwrote or removed.+## Background review notifications (`display.memory_notifications`)After a turn, the background self-improvement review may quietly save a memory