The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(memory): require explicit top-level targets before writes
James Nolancb62ae45f6b9
diff --git a/agent/inline_tool_executors.py b/agent/inline_tool_executors.pyindex 75a497d3b59..4d2c85a8b13 100644--- a/agent/inline_tool_executors.py+++ b/agent/inline_tool_executors.py@@ -143,7 +143,7 @@ def _memory(agent, args: dict, ctx: InlineToolContext) -> Any:result = _call_tool("tools.memory_tool", "memory_tool", args,(- ("action", "action"), ("target", "target", "memory"), ("content", "content"),+ ("action", "action"), ("target", "target"), ("content", "content"),("old_text", "old_text"), ("new_text", "new_text"), ("operations", "operations"),),store=agent._memory_store,diff --git a/tests/tools/test_memory_target_contract.py b/tests/tools/test_memory_target_contract.pynew file mode 100644index 00000000000..7595c7fee1b--- /dev/null+++ b/tests/tools/test_memory_target_contract.py@@ -0,0 +1,90 @@+"""Memory calls must name one store before writing or staging a proposal."""++import copy+import json+from types import SimpleNamespace++import pytest++from agent.inline_tool_executors import INLINE_TOOL_EXECUTORS+from hermes_cli.config import load_config, save_config+from tools.memory_tool import MemoryStore, apply_memory_pending+from tools.registry import registry+from tools.skill_provenance import reset_current_write_origin, set_current_write_origin+from tools import write_approval as wa+++def _call(route, store, args):+ if route == "store":+ return store.apply_batch(args.get("target"), args["operations"])+ if route == "replay":+ return apply_memory_pending({"action": "batch", **args}, store)+ if route == "inline":+ agent = SimpleNamespace(_memory_store=store, _memory_manager=None)+ return json.loads(INLINE_TOOL_EXECUTORS["memory"](agent, args, None))+ return json.loads(registry.dispatch("memory", args, store=store))++[email protected]("route", ["registry", "inline", "store", "replay"])[email protected]("origin", ["direct", "foreground", "background_review"])[email protected]("target_fields,nested_fields", [+ ({}, {}),+ ({"target": None}, {}),+ ({}, {"target": "user"}),+ ({"target": "memory"}, {"target": "user"}),+ ({"target": "user"}, {"target": "user"}),+ ({"target": "user"}, {"target": None}),+])+def test_invalid_targets_leave_files_and_pending_queue_unchanged(+ route, origin, target_fields, nested_fields,+):+ store = MemoryStore()+ store.load_from_disk()+ for target in ("memory", "user"):+ assert store.add(target, f"Existing {target} fact")["success"]+ before = {t: store._path_for(t).read_bytes() for t in ("memory", "user")}+ config = load_config()+ config.setdefault("memory", {})["write_approval"] = origin != "direct"+ save_config(config)+ # A bad target in a later operation must reject the entire batch.+ args = {**target_fields, "operations": [+ {"action": "add", "content": "First fact"},+ {"action": "add", "content": "Second fact", **nested_fields},+ ]}+ original = copy.deepcopy(args)+ token = set_current_write_origin(origin)+ try:+ result = _call(route, store, args)+ finally:+ reset_current_write_origin(token)+ assert result["success"] is False, result+ assert "target" in result["error"] and "top level" in result["error"]+ assert "retry" in result["error"].lower()+ assert not result.get("staged")+ assert wa.list_pending(wa.MEMORY) == []+ assert args == original+ assert {t: store._path_for(t).read_bytes() for t in before} == before++[email protected]("route", ["registry", "inline"])[email protected]("batch", [False, True])[email protected]("target", ["memory", "user"])+def test_missing_target_can_be_corrected_without_writing_to_the_other_store(route, batch, target):+ store = MemoryStore()+ store.load_from_disk()+ for name in ("memory", "user"):+ assert store.add(name, f"Existing {name} fact")["success"]+ other = "user" if target == "memory" else "memory"+ other_before = store._path_for(other).read_bytes()+ snapshot = store.format_for_system_prompt(target)+ operation = {"action": "add", "content": "User prefers metric units"}+ args = {"operations": [operation]} if batch else operation+ rejected = _call(route, store, args)+ assert rejected["success"] is False, rejected+ result = _call(route, store, {**args, "target": target})+ assert result["success"] is True, result+ fresh = MemoryStore()+ fresh.load_from_disk()+ assert fresh._entries_for(target) == [f"Existing {target} fact", operation["content"]]+ assert store._path_for(other).read_bytes() == other_before+ assert store.format_for_system_prompt(target) == snapshotdiff --git a/tools/memory_tool.py b/tools/memory_tool.pyindex a6e8a72258d..ec942f7c880 100644--- a/tools/memory_tool.py+++ b/tools/memory_tool.py@@ -245,9 +245,7 @@ def _memory_tool(action, target, content, old_text, new_text, operations, store)# An omitted optional string can arrive as "" (#90468): let the new_text alias fill it.if not content and new_text:content = new_text- # Strict providers send JSON null for optional fields; treat as omitted.- target = "memory" if target is None else target- target_error = _memory_target_error(store, target)+ target_error = _memory_target_error(store, target, operations)if target_error is not None:return "rejected", json.dumps(target_error)if operations:@@ -309,13 +307,28 @@ def check_memory_requirements() -> bool:return flags[0] or flags[1]-def _memory_target_error(store: MemoryStore, target: str) -> Optional[dict[str, Any]]:- """Return a shared validation error for an invalid or disabled target."""- if target not in {"memory", "user"}:+def _memory_target_error(store: MemoryStore, target: Optional[str],+ operations: Optional[list[dict[str, Any]]] = None) -> Optional[dict[str, Any]]:+ """Validate one explicit store before writing, staging, or replaying a batch."""+ if target is None:+ FAILURE_CLASS.set("invalid_args")+ return {"success": False, "error": (+ "Missing required target. Retry with target='memory' or target='user' at the top level. "+ "For a batch, remove target from every operation; use separate calls for different stores. "+ "Nothing was written or staged.")}+ if not isinstance(target, str) or target not in {"memory", "user"}:from tools.registry import _bound_error_textFAILURE_CLASS.set("invalid_args")return {"success": False,"error": _bound_error_text(f"Invalid memory target '{target}'. Use 'memory' or 'user'.")}+ if isinstance(operations, list):+ for index, op in enumerate(operations, 1):+ if isinstance(op, dict) and "target" in op:+ FAILURE_CLASS.set("invalid_args")+ return {"success": False, "error": (+ f"Operation {index} has a nested target. Retry with target only at the top level "+ "and remove it from every operation. Use separate calls for different stores. "+ "Nothing was written or staged.")}if store.target_enabled(target):return Nonelabel = "USER.md" if target == "user" else "MEMORY.md"@@ -328,8 +341,8 @@ def apply_memory_pending(payload: dict[str, Any], store: MemoryStore) -> dict[streplace/remove applies to exactly its pinned ``matched_entry`` or is refused; a recordstaged before pinning has no verifiable target, so it is refused rather than replayed byold_text (which could hit a newer entry the approver never saw)."""- action, target = payload.get("action"), payload.get("target", "memory")- target_error = _memory_target_error(store, target)+ action, target = payload.get("action"), payload.get("target")+ target_error = _memory_target_error(store, target, payload.get("operations"))if target_error is not None:return target_errorif any(not op.get("matched_entry") for op in destructive_ops(payload)):@@ -348,8 +361,10 @@ MEMORY_SCHEMA = {"description": ("Save durable facts to persistent memory that survive across sessions. Memory is ""injected into every future turn, so keep entries compact and high-signal.\n\n"- "HOW: make ALL your changes in ONE call via an 'operations' array (each item: "- "{action, content?, old_text?}). The batch applies atomically and the char limit is "+ "HOW: make your changes in ONE call PER STORE via an 'operations' array (each item: "+ "{action, content?, old_text?}). Always supply target at the top level, never inside "+ "an operation. Use separate calls for different stores. The batch applies atomically "+ "and the char limit is ""checked only on the FINAL result β so a single call can remove/replace stale entries ""to free room AND add new ones, even when an add alone would overflow. The response ""reports current/limit chars and confirms completion; one batch call finishes the "@@ -380,7 +395,7 @@ MEMORY_SCHEMA = {"target": {"type": "string","enum": ["memory", "user"],- "description": "Which memory store: 'memory' for personal notes, 'user' for user profile."+ "description": "Required at the top level: 'memory' for personal notes, 'user' for user profile. Applies to every operation in the call; never put target inside an operation."},"content": {"type": "string",@@ -450,7 +465,7 @@ registry.register(toolset="memory",schema=MEMORY_SCHEMA,handler=lambda args, **kw: memory_tool(- action=args.get("action", ""), target=args.get("target", "memory"), store=kw.get("store"),+ action=args.get("action", ""), target=args.get("target"), store=kw.get("store"),**{k: args.get(k) for k in ("content", "old_text", "new_text", "operations")}),check_fn=check_memory_requirements,emoji="π§ ",diff --git a/tools/memory_tool_store.py b/tools/memory_tool_store.pyindex 09753cfe90a..525956e0b87 100644--- a/tools/memory_tool_store.py+++ b/tools/memory_tool_store.py@@ -470,6 +470,9 @@ class MemoryStore:return self._batch(target, operations, commit=False)def _batch(self, target: str, operations: list[dict[str, Any]], *, commit: bool) -> dict[str, Any]:+ from tools.memory_tool import _memory_target_error+ if target_error := _memory_target_error(self, target, operations):+ return target_errorif not operations:return _error("operations list is empty.", "invalid_args")ops = [op or {} for op in operations]diff --git a/website/docs/user-guide/features/memory.md b/website/docs/user-guide/features/memory.mdindex 11311d485b9..70d892a3a2a 100644--- a/website/docs/user-guide/features/memory.md+++ b/website/docs/user-guide/features/memory.md@@ -97,6 +97,16 @@ The agent uses the `memory` tool with these actions: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.+Every tool call requires a top-level `target`: `"memory"` for agent notes or `"user"`+for the user profile. A batch uses that one target for every operation:++```json+{"target": "user", "operations": [{"action": "add", "content": "User prefers metric units"}]}+```++Missing or null targets and targets inside operations return an error before writing+or staging approval. Correct the payload and retry; use separate calls to update both stores.+### Substring MatchingThe `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: