memory_tool.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. #!/usr/bin/env python3
  2. """Memory Tool - persistent curated memory (MEMORY.md = agent notes, USER.md = user
  3. profile). Both enter the system prompt as a FROZEN snapshot at session start;
  4. mid-session writes hit disk but never change the prompt (prefix cache intact).
  5. Single `memory` tool: add/patch/remove or a batch `operations` list."""
  6. import copy
  7. import json
  8. import logging
  9. from contextvars import ContextVar
  10. from pathlib import Path
  11. from hermes_constants import get_hermes_home
  12. from typing import Dict, Any, List, Optional, Tuple
  13. from utils import is_truthy_value
  14. from tools.registry import no_cache_check_fn
  15. # fcntl is Unix-only; Windows uses msvcrt. MemoryStore reads both lazily from
  16. # this module (tests patch ``memory_tool.fcntl``).
  17. msvcrt = None
  18. try:
  19. import fcntl
  20. except ImportError:
  21. fcntl = None
  22. try:
  23. import msvcrt
  24. except ImportError:
  25. pass
  26. logger = logging.getLogger(__name__)
  27. # One tool-definition pass must use ONE config decision for availability and the
  28. # dynamic target schema: the check_fn result flows to the immediately following
  29. # dynamic_schema_overrides call; ContextVar isolates concurrent profile builds.
  30. _memory_surface_flags: ContextVar[Optional[tuple[bool, bool]]] = ContextVar("memory_surface_flags", default=None)
  31. def get_memory_dir() -> Path:
  32. """Profile-scoped memories dir, resolved per call (HERMES_HOME may switch after import)."""
  33. return get_hermes_home() / "memories"
  34. from tools.memory_tool_store import (
  35. ENTRY_DELIMITER, FAILURE_CLASS, MEMORY_BLOCK_HEADERS, PATCH_DROP_HINT, MemoryStore, _scan_memory_content)
  36. def load_on_disk_store() -> MemoryStore:
  37. """Fresh on-disk MemoryStore with configured limits/flags for contexts with no live
  38. agent (gateway, Desktop, ``/memory``) so approvals enforce the SAME caps as
  39. ``agent_init``. Falls back to defaults if config can't load; never raises."""
  40. try:
  41. from hermes_cli.config import load_config
  42. config = load_config() or {}
  43. mem_cfg = get_builtin_memory_config(config)
  44. memory_enabled, user_profile_enabled = get_builtin_memory_store_flags(config)
  45. store = MemoryStore(int(mem_cfg.get("memory_char_limit", 2200)), int(mem_cfg.get("user_char_limit", 1375)),
  46. memory_enabled=memory_enabled, user_profile_enabled=user_profile_enabled)
  47. except Exception:
  48. store = MemoryStore() # config optional — fall back to defaults rather than break /memory
  49. store.load_from_disk()
  50. return store
  51. def _pin_matched_entries(store: MemoryStore, payload: dict[str, Any]) -> Optional[str]:
  52. """Record on each staged replace/remove the FULL entry its old_text selects now. Approval
  53. then applies to exactly the entry the approver reviewed and refuses if it changed:
  54. re-running the old_text search at approve time could hit a newer entry that still
  55. contains it. Returns the JSON error when the search fails now, as the direct write would."""
  56. target = payload.get("target", "memory")
  57. if payload.get("action") == "batch":
  58. result = store.resolve_batch_entries(target, payload["operations"])
  59. if result.get("success"):
  60. payload["operations"] = [op if entry is None else {**op, "matched_entry": entry}
  61. for op, entry in zip(payload["operations"], result["matched_entries"])]
  62. elif payload.get("action") in _BG_DELETE_ACTIONS:
  63. result = store.resolve_entry(target, payload.get("old_text") or "", payload["action"])
  64. if result.get("success"):
  65. payload["matched_entry"] = result["matched_entry"]
  66. else:
  67. return None
  68. return None if result.get("success") else json.dumps(result, ensure_ascii=False)
  69. def _gate_or_stage(store: MemoryStore, summary: str, detail: str, payload: dict[str, Any]) -> Optional[str]:
  70. """JSON tool-result string when the write must NOT proceed (blocked or staged
  71. for approval), None to proceed. Fails open if the gate module can't load."""
  72. try:
  73. from tools import write_approval as wa
  74. except Exception:
  75. return None
  76. decision = wa.evaluate_gate(wa.MEMORY, inline_summary=summary, inline_detail=detail)
  77. if decision.allow:
  78. return None
  79. if decision.blocked:
  80. FAILURE_CLASS.set("gate_refused")
  81. return tool_error(decision.message, success=False)
  82. if (unmatched := _pin_matched_entries(store, payload)) is not None:
  83. return unmatched
  84. FAILURE_CLASS.set("staged")
  85. record = wa.stage_write(wa.MEMORY, payload, summary=f"{summary}: {detail[:120]}", origin=wa.current_origin())
  86. return json.dumps({"success": True, "staged": True, "pending_id": record["id"], "message": decision.message},
  87. ensure_ascii=False)
  88. # action -> (store call, gate (summary, detail) text) for the live tool path and staged replay
  89. # ('replace' only replays writes staged before it was removed from the tool).
  90. _STORE_ACTIONS = {
  91. "add": (lambda store, target, content, old_text, entry=None: store.add(target, content),
  92. lambda label, content, old_text: (f"add to {label}", content or "")),
  93. "replace": (lambda store, target, content, old_text, entry=None: store.replace(target, old_text, content, entry),
  94. lambda label, content, old_text: (f"replace in {label}",
  95. f"entry matching: {old_text}\nwhole entry becomes: {content}")),
  96. "remove": (lambda store, target, content, old_text, entry=None: store.remove(target, old_text, entry),
  97. lambda label, content, old_text: (f"remove from {label}", old_text or "")),
  98. "patch": (lambda store, target, content, old_text, entry=None: store.patch(target, old_text, content, entry),
  99. lambda label, content, old_text: (f"patch in {label}",
  100. f"entry matching: {old_text}\nspan '{old_text}' becomes: {content} "
  101. "(rest of the entry is kept)"))}
  102. def _batch_op_line(op: dict[str, Any]) -> str:
  103. op = op or {}
  104. act, content, old = op.get("action", "?"), op.get("content") or op.get("new_text") or "", op.get("old_text", "")
  105. if act == "remove":
  106. return f"- remove: {old}"
  107. if act == "patch":
  108. return f"- patch span '{old}' -> '{content}' (rest of the entry is kept)"
  109. return f"- {act}: {content}"
  110. def _apply_write_gate(store: MemoryStore, action: str, target: str, content: Optional[str],
  111. old_text: Optional[str], operations: Optional[list[dict[str, Any]]] = None) -> Optional[str]:
  112. """Gate one mutating op, or (``operations`` set) a whole batch as a single unit."""
  113. label = "user profile" if target == "user" else "memory"
  114. if operations is not None:
  115. return _gate_or_stage(store, f"apply {len(operations)} op(s) to {label}",
  116. "\n".join(_batch_op_line(op) for op in operations),
  117. {"action": "batch", "target": target, "operations": operations})
  118. return _gate_or_stage(store, *_STORE_ACTIONS[action][1](label, content, old_text),
  119. {"action": action, "target": target, "content": content, "old_text": old_text})
  120. def _validate_single_op(store, action, target, content, old_text) -> Optional[str]:
  121. """Validate BEFORE the gate so an invalid write is rejected now, not at approve time.
  122. Missing ``old_text`` is recoverable (it can't be schema-required — needs a combinator
  123. the Codex backend rejects): return the inventory plus a retry instruction."""
  124. if action == "add" and not content:
  125. FAILURE_CLASS.set("missing_content")
  126. return tool_error("Content is required for 'add' action.", success=False)
  127. if action in ("remove", "patch") and not old_text:
  128. FAILURE_CLASS.set("missing_old_text")
  129. return json.dumps({
  130. "success": False,
  131. "error": (f"'{action}' needs old_text -- a short unique substring of the entry "
  132. f"to {action}. None was provided. Reissue the {action} with old_text "
  133. f"set to part of one of the current_entries below."),
  134. "current_entries": store._entries_for(target), "usage": store._usage(target)}, ensure_ascii=False)
  135. if action == "patch" and not content:
  136. FAILURE_CLASS.set("missing_content")
  137. return tool_error(f"content (the new text for the old_text span) is required for 'patch' action. "
  138. f"{PATCH_DROP_HINT}", success=False)
  139. return None
  140. # 'replace' is no longer offered to the model; it stays here so writes staged before its
  141. # removal still pin, display and replay.
  142. _BG_DELETE_ACTIONS = ("replace", "remove", "patch")
  143. _REPLACE_REMOVED = ("'replace' is not available; use 'patch'. old_text is the exact span to change and "
  144. "content is its new text; the rest of the entry is kept. To rewrite a whole entry, "
  145. "set old_text to the whole entry. Nothing was written.")
  146. def destructive_ops(payload: dict[str, Any]) -> list[dict[str, Any]]:
  147. """The replace/remove ops of a staged memory payload, single-op or batch shape."""
  148. ops = (payload.get("operations") or []) if payload.get("action") == "batch" else [payload]
  149. return [op for op in ops if (op or {}).get("action") in _BG_DELETE_ACTIONS]
  150. def _background_delete_gate(store, action, operations, target="memory", content=None,
  151. old_text=None) -> Optional[str]:
  152. """Fail-closed operation gate for unattended background-review forks (#105921): ``add``
  153. stays available (it is all any review prompt asks for), while ``patch``/``remove`` —
  154. single or inside a batch — are never applied unattended. The op is staged in the pending
  155. store instead of merely denied: the fork's own review summary is never published back, so
  156. a plain denial would drop the consolidation request with no surfacing path at all. A
  157. staging failure fails closed to a plain denial."""
  158. from tools.skill_provenance import is_unattended_review
  159. if not is_unattended_review():
  160. return None
  161. payload = ({"action": "batch", "target": target, "operations": operations}
  162. if operations is not None else
  163. {"action": action, "target": target, "content": content, "old_text": old_text})
  164. if not destructive_ops(payload):
  165. return None
  166. detail = ("; ".join(_batch_op_line(op) for op in operations) if operations is not None
  167. else _batch_op_line({"action": action, "content": content, "old_text": old_text}))
  168. try:
  169. if (unmatched := _pin_matched_entries(store, payload)) is not None:
  170. return unmatched
  171. from tools import write_approval as wa
  172. FAILURE_CLASS.set("staged")
  173. record = wa.stage_write(
  174. wa.MEMORY, payload,
  175. summary=(f"background review consolidation ({'batch' if operations is not None else action} "
  176. f"on {target}): {detail}")[:200],
  177. origin=wa.current_origin())
  178. return json.dumps({
  179. "success": True, "staged": True, "proposal_staged": True, "pending_id": record["id"],
  180. "message": ("Background review may not delete memory entries unattended. The proposed "
  181. f"{'batch' if operations is not None else action} was staged for your approval — "
  182. "review it with /memory pending (approve to apply, discard to drop)."),
  183. }, ensure_ascii=False)
  184. except Exception:
  185. logger.warning("Failed to stage background-review consolidation; denying", exc_info=True)
  186. FAILURE_CLASS.set("gate_refused")
  187. return tool_error(
  188. "Background review may not delete memory entries ('patch'/'remove', including in a "
  189. "batch); 'add' is still available.", success=False)
  190. def memory_tool(action: str | None = None, target: str = "memory", content: str | None = None, old_text: str | None = None,
  191. new_text: str | None = None, operations: Optional[list[dict[str, Any]]] = None,
  192. store: Optional[MemoryStore] = None) -> str:
  193. """Tool entry point; returns a JSON string. Single op (action + content/old_text)
  194. or batch (``operations``, atomic against the final budget). ``new_text``
  195. aliases ``content``."""
  196. if store is None:
  197. return tool_error("Memory is not available. It may be disabled in config or this environment.", success=False)
  198. token = FAILURE_CLASS.set("other")
  199. try:
  200. outcome, result = _memory_tool(action, target, content, old_text, new_text, operations, store)
  201. failure_class = "none" if outcome == "success" else FAILURE_CLASS.get()
  202. finally:
  203. FAILURE_CLASS.reset(token)
  204. from hermes_cli.observability.shared_metrics_loop import record_builtin_memory_call
  205. record_builtin_memory_call(action, operations, outcome=outcome, failure_class=failure_class)
  206. return result
  207. def _applied(result: dict[str, Any]) -> tuple[str, str]:
  208. return ("success" if result.get("success") else "failed"), json.dumps(result, ensure_ascii=False)
  209. def _invalid(message: str) -> tuple[str, str]:
  210. FAILURE_CLASS.set("invalid_args")
  211. return "rejected", tool_error(message, success=False)
  212. def _memory_tool(action, target, content, old_text, new_text, operations, store) -> tuple[str, str]:
  213. """``(outcome, result_json)``: ``rejected`` when refused or held before touching the store."""
  214. # An omitted optional string can arrive as "" (#90468): let the new_text alias fill it.
  215. if not content and new_text:
  216. content = new_text
  217. target_error = _memory_target_error(store, target, operations)
  218. if target_error is not None:
  219. return "rejected", json.dumps(target_error)
  220. if operations:
  221. if not isinstance(operations, list):
  222. return _invalid("operations must be a list of {action, content?, old_text?} objects.")
  223. if any(isinstance(op, dict) and op.get("action") == "replace" for op in operations):
  224. return _invalid(_REPLACE_REMOVED)
  225. denied = _background_delete_gate(store, action, operations, target)
  226. if denied is not None:
  227. return "rejected", denied
  228. # Approval gate: stages (background/gateway) or prompts inline (CLI); off by default.
  229. gate_result = _apply_write_gate(store, "batch", target, None, None, operations)
  230. if gate_result is not None:
  231. return "rejected", gate_result
  232. return _applied(store.apply_batch(target, operations))
  233. # Reject calls with neither operations[] nor the legacy top-level action.
  234. # Without this guard the dispatch falls through to the generic
  235. # "Unknown action 'None'" error, which gives the model no signal about
  236. # *why* the call was malformed and can trigger repeated retries. (#64291)
  237. if not action and not operations:
  238. return _invalid(
  239. "Missing required parameter: 'operations', a list of {action: add/patch/remove, "
  240. "content?, old_text?} changes; a single change is a one-item list."
  241. )
  242. if action == "replace":
  243. return _invalid(_REPLACE_REMOVED)
  244. if action not in _STORE_ACTIONS:
  245. return _invalid(f"Unknown action '{action}'. Use: add, patch, remove")
  246. invalid = (_validate_single_op(store, action, target, content, old_text)
  247. or _background_delete_gate(store, action, None, target, content, old_text)
  248. or _apply_write_gate(store, action, target, content, old_text))
  249. if invalid is not None:
  250. return "rejected", invalid
  251. return _applied(_STORE_ACTIONS[action][0](store, target, content, old_text))
  252. def get_builtin_memory_config(config: Optional[dict[str, Any]] = None) -> dict[str, Any]:
  253. """Normalized ``memory`` config section ({} when missing/malformed → flags default to
  254. enabled). ``agent_init`` reads the same section so availability and store cannot diverge."""
  255. if config is None:
  256. try:
  257. from hermes_cli.config import load_config_readonly
  258. config = load_config_readonly()
  259. except Exception:
  260. logger.debug("Could not read memory config for availability", exc_info=True)
  261. return {}
  262. section = config.get("memory") if isinstance(config, dict) else None
  263. return section if isinstance(section, dict) else {}
  264. def get_builtin_memory_store_flags(config: Optional[dict[str, Any]] = None) -> tuple[bool, bool]:
  265. """Return ``(memory_enabled, user_profile_enabled)`` from resolved config."""
  266. section = get_builtin_memory_config(config)
  267. return tuple(is_truthy_value(section.get(k), default=True) for k in ("memory_enabled", "user_profile_enabled"))
  268. @no_cache_check_fn
  269. def check_memory_requirements() -> bool:
  270. """Snapshot store flags and report whether the built-in tool is available."""
  271. _memory_surface_flags.set(None)
  272. flags = get_builtin_memory_store_flags()
  273. _memory_surface_flags.set(flags)
  274. return flags[0] or flags[1]
  275. def _memory_target_error(
  276. store: MemoryStore, target: str | None, operations: list[dict[str, Any]] | None = None,
  277. ) -> dict[str, Any] | None:
  278. """Validate one explicit store before writing, staging, or replaying a batch."""
  279. if target is None:
  280. FAILURE_CLASS.set("invalid_args")
  281. return {"success": False, "error": (
  282. "Missing required target. Retry with target='memory' or target='user' at the top level. "
  283. "For a batch, remove target from every operation; use separate calls for different stores. "
  284. "Nothing was written or staged.")}
  285. if not isinstance(target, str) or target not in {"memory", "user"}:
  286. from tools.registry import _bound_error_text
  287. FAILURE_CLASS.set("invalid_args")
  288. return {"success": False,
  289. "error": _bound_error_text(f"Invalid memory target '{target}'. Use 'memory' or 'user'.")}
  290. if isinstance(operations, list):
  291. for index, op in enumerate(operations, 1):
  292. # A nested target equal to the call's (or null) is redundant, not wrong; only a
  293. # different one asks for two stores in one call, which a batch cannot do.
  294. if isinstance(op, dict) and op.get("target") not in (None, target):
  295. FAILURE_CLASS.set("invalid_args")
  296. return {"success": False, "error": (
  297. f"Operation {index} names a different target than the one at the top level. "
  298. "One call writes one store: retry with separate calls for different stores. "
  299. "Nothing was written or staged.")}
  300. if store.target_enabled(target):
  301. return None
  302. label = "USER.md" if target == "user" else "MEMORY.md"
  303. FAILURE_CLASS.set("disabled")
  304. return {"success": False, "error": f"Built-in {label} writes are disabled in memory config.", "target": target}
  305. def apply_memory_pending(payload: dict[str, Any], store: MemoryStore) -> dict[str, Any]:
  306. """Replay a staged write against the store, bypassing the gate (/memory approve). A
  307. replace/remove applies to exactly its pinned ``matched_entry`` or is refused; a record
  308. staged before pinning has no verifiable target, so it is refused rather than replayed by
  309. old_text (which could hit a newer entry the approver never saw)."""
  310. action, target = payload.get("action"), payload.get("target")
  311. target_error = _memory_target_error(store, target, payload.get("operations"))
  312. if target_error is not None:
  313. return target_error
  314. if any(not op.get("matched_entry") for op in destructive_ops(payload)):
  315. return {"success": False, "error": "This destructive pending write predates entry pinning and cannot be "
  316. "verified; nothing was applied. Reject it and recreate the change."}
  317. if action == "batch":
  318. return store.apply_batch(target, payload.get("operations") or [])
  319. if action not in _STORE_ACTIONS:
  320. return {"success": False, "error": f"Unknown staged action '{action}'."}
  321. return _STORE_ACTIONS[action][0](store, target, payload.get("content") or "", payload.get("old_text") or "",
  322. payload.get("matched_entry"))
  323. MEMORY_SCHEMA = {
  324. "name": "memory",
  325. "description": (
  326. "Save durable facts to persistent memory that survive across sessions. Memory is "
  327. "injected into every future turn, so keep entries compact and high-signal.\n\n"
  328. "HOW: make ALL your changes to one target in ONE call via an 'operations' array (each "
  329. "item: {action, content?, old_text?}). The batch applies atomically and the char limit is "
  330. "checked only on the FINAL result — so a single call can remove/patch stale entries "
  331. "to free room AND add new ones, even when an add alone would overflow. The response "
  332. "reports current/limit chars and confirms completion; one batch call finishes the "
  333. "update, so don't repeat it.\n\n"
  334. "WHEN: only for facts that apply to EVERY session regardless of task: who the user "
  335. "is, stable environment facts, standing conventions with no task home. Anything "
  336. "learned while doing a task (procedures, pitfalls, and the user's preferences and "
  337. "corrections for that kind of work) belongs in the task's skill via skill_manage, "
  338. "where it loads only when relevant; memory is injected into every turn and must "
  339. "stay small.\n\n"
  340. "IF FULL: an add is rejected with the current entries shown. Reissue as ONE batch that "
  341. "removes or shortens enough stale entries and adds the new one together.\n\n"
  342. "TARGETS: 'user' = who the user is (name, role, preferences, style). 'memory' = your "
  343. "notes (environment, conventions, tool quirks, lessons).\n\n"
  344. "SKIP: trivial/obvious info, easily re-discovered facts, raw data dumps, task progress, "
  345. "completed-work logs, temporary TODO state (use session_search for those). Reusable "
  346. "procedures belong in a skill, not memory."
  347. ),
  348. # Each field is advertised once, inside operations[]. The handler still ACCEPTS the
  349. # top-level single-op shape (action/content/old_text) and the new_text alias: models
  350. # drift and older transcripts replay them.
  351. "parameters": {
  352. "type": "object",
  353. "properties": {
  354. "target": {
  355. "type": "string",
  356. "enum": ["memory", "user"],
  357. "description": "Which memory store: 'memory' for personal notes, 'user' for user profile."
  358. },
  359. "operations": {
  360. "type": "array",
  361. "description": (
  362. "Changes applied atomically in one call against the final char budget; "
  363. "a single change is a one-item list."
  364. ),
  365. "items": {
  366. "type": "object",
  367. "properties": {
  368. "action": {"type": "string", "enum": ["add", "patch", "remove"]},
  369. "content": {
  370. "type": "string",
  371. "description": ("Required for 'add' and 'patch'. For 'add', the new entry. For 'patch', "
  372. "the text that replaces old_text; the rest of the entry is kept."),
  373. },
  374. "old_text": {
  375. "type": "string",
  376. "description": ("REQUIRED for 'patch' and 'remove': text from one entry. 'patch' replaces "
  377. "exactly this span (it must occur once in the entry); 'remove' deletes the "
  378. "whole entry. Omit for 'add'."),
  379. },
  380. },
  381. "required": ["action"],
  382. "additionalProperties": False,
  383. },
  384. },
  385. },
  386. "required": ["target", "operations"],
  387. },
  388. }
  389. # Schema text when only one built-in store is enabled: (target description, TARGETS replacement).
  390. _SINGLE_TARGET_TEXT = {
  391. ("memory",): ("The enabled built-in store: 'memory' for personal notes.",
  392. "TARGET: only 'memory' is enabled for personal notes (environment, conventions, "
  393. "tool quirks, lessons)."),
  394. ("user",): ("The enabled built-in store: 'user' for user profile.",
  395. "TARGET: only 'user' is enabled for user profile facts (name, role, preferences, style).")}
  396. def _build_memory_schema_overrides() -> dict[str, Any]:
  397. """Narrow the advertised target surface using the availability snapshot."""
  398. flags = _memory_surface_flags.get() or get_builtin_memory_store_flags()
  399. _memory_surface_flags.set(None)
  400. targets = [t for t, on in zip(("memory", "user"), flags) if on]
  401. parameters = copy.deepcopy(MEMORY_SCHEMA["parameters"])
  402. target_schema, description = parameters["properties"]["target"], MEMORY_SCHEMA["description"]
  403. target_schema["enum"] = targets
  404. if narrowed := _SINGLE_TARGET_TEXT.get(tuple(targets)):
  405. target_schema["description"], replacement = narrowed
  406. description = description.replace(
  407. "TARGETS: 'user' = who the user is (name, role, preferences, style). 'memory' = your "
  408. "notes (environment, conventions, tool quirks, lessons).", replacement)
  409. return {"description": description, "parameters": parameters}
  410. from tools.registry import registry, tool_error
  411. registry.register(
  412. name="memory",
  413. toolset="memory",
  414. schema=MEMORY_SCHEMA,
  415. handler=lambda args, **kw: memory_tool(
  416. action=args.get("action", ""), target=args.get("target"), store=kw.get("store"),
  417. **{k: args.get(k) for k in ("content", "old_text", "new_text", "operations")}),
  418. check_fn=check_memory_requirements,
  419. emoji="🧠",
  420. dynamic_schema_overrides=_build_memory_schema_overrides)