Skip to content

The agent that grows with you

refactor(tools): memory store — inline reload/read helpers, dict-dispatch write-gate text

Teknium0c9b0256d492
diff --git a/tests/tools/test_memory_tool.py b/tests/tools/test_memory_tool.py
index 0582703abb5..2af6107bfc1 100644
--- a/tests/tools/test_memory_tool.py
+++ b/tests/tools/test_memory_tool.py
@@ -686,9 +686,7 @@ class TestBomToleranceInMemoryFiles:
raw, read_ok = MemoryStore._read_raw_checked(path)
assert read_ok is True
assert not raw.startswith("\ufeff")
- entries, ok = MemoryStore._read_entries_checked(path)
- assert ok is True
- assert entries == ["First fact."]
+ assert MemoryStore._read_file(path) == ["First fact."]
def test_bom_file_add_keeps_existing_entry_intact(self, store):
path = store._path_for("memory")
diff --git a/tools/memory_tool.py b/tools/memory_tool.py
index b4e0c7bd98f..f3d5ecc037f 100644
--- a/tools/memory_tool.py
+++ b/tools/memory_tool.py
@@ -46,7 +46,7 @@ def get_memory_dir() -> Path:
from tools.memory_tool_store import ( # noqa: E402,F401 (re-exports)
- ENTRY_DELIMITER, MEMORY_BLOCK_HEADERS, MemoryStore, _READ_FAILED,
+ ENTRY_DELIMITER, MEMORY_BLOCK_HEADERS, MemoryStore,
_drift_error, _read_failed_error, _scan_memory_content,
)
@@ -75,13 +75,7 @@ def load_on_disk_store() -> "MemoryStore":
return store
-# ---------------------------------------------------------------------------
-# Write-approval gate
-# ---------------------------------------------------------------------------
-
-def _target_label(target: str) -> str:
- return "user profile" if target == "user" else "memory"
-
+# -- Write-approval gate --
def _gate_or_stage(summary: str, detail: str, payload: Dict[str, Any]) -> Optional[str]:
"""Run the memory write gate. Returns a JSON tool-result string when the
@@ -101,24 +95,26 @@ def _gate_or_stage(summary: str, detail: str, payload: Dict[str, Any]) -> Option
ensure_ascii=False)
+# action -> (gate summary verb, gate detail) for a single mutating op.
+_GATE_TEXT = {
+ "add": lambda label, content, old_text: (f"add to {label}", content or ""),
+ "replace": lambda label, content, old_text: (f"replace in {label}", f"old: {old_text}\nnew: {content}"),
+ "remove": lambda label, content, old_text: (f"remove from {label}", old_text or ""),
+}
+
+
def _apply_write_gate(action: str, target: str, content: Optional[str], old_text: Optional[str]) -> Optional[str]:
"""Gate a single mutating op (add/replace/remove); other actions pass."""
- if action not in _STORE_ACTIONS:
+ if action not in _GATE_TEXT:
return None
- label = _target_label(target)
- if action == "add":
- summary, detail = f"add to {label}", content or ""
- elif action == "replace":
- summary, detail = f"replace in {label}", f"old: {old_text}\nnew: {content}"
- else:
- summary, detail = f"remove from {label}", old_text or ""
+ summary, detail = _GATE_TEXT[action]("user profile" if target == "user" else "memory", content, old_text)
payload = {"action": action, "target": target, "content": content, "old_text": old_text}
return _gate_or_stage(summary, detail, payload)
def _apply_batch_write_gate(target: str, operations: List[Dict[str, Any]]) -> Optional[str]:
"""Gate a whole batch as a single unit."""
- summary = f"apply {len(operations)} op(s) to {_target_label(target)}"
+ summary = f"apply {len(operations)} op(s) to {'user profile' if target == 'user' else 'memory'}"
detail_lines = []
for op in operations:
op = op or {}
@@ -134,32 +130,25 @@ def _apply_batch_write_gate(target: str, operations: List[Dict[str, Any]]) -> Op
return _gate_or_stage(summary, "\n".join(detail_lines), payload)
-# ---------------------------------------------------------------------------
-# Tool entry point
-# ---------------------------------------------------------------------------
-
-def _missing_old_text_error(store: "MemoryStore", target: str, action: str) -> str:
- """Recoverable error for replace/remove without ``old_text``. It can't be
- schema-required (needs a combinator the Codex backend rejects — see
- test_memory_tool_schema.py) and some clients omit it, so return the current
- inventory plus a retry instruction instead of a dead-end."""
- return json.dumps({
- "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."),
- "current_entries": store._entries_for(target),
- "usage": store._usage(target),
- }, ensure_ascii=False)
-
+# -- Tool entry point --
def _validate_single_op(store, action, target, content, old_text) -> Optional[str]:
"""Validate required params BEFORE the gate so an invalid write is rejected
- now rather than staged and failing at approve time."""
+ now rather than staged and failing at approve time. A missing ``old_text``
+ is recoverable (it can't be schema-required — needs a combinator the Codex
+ backend rejects, see test_memory_tool_schema.py — and some clients omit it),
+ so return the current inventory plus a retry instruction, not a dead-end."""
if action == "add" and not content:
return tool_error("Content is required for 'add' action.", success=False)
if action in ("replace", "remove") and not old_text:
- return _missing_old_text_error(store, target, action)
+ return json.dumps({
+ "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."),
+ "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)
return None
@@ -282,9 +271,7 @@ def apply_memory_pending(payload: Dict[str, Any], store: "MemoryStore") -> Dict[
return run(store, target, payload.get("content") or "", payload.get("old_text") or "")
-# =============================================================================
-# OpenAI Function-Calling Schema
-# =============================================================================
+# -- OpenAI Function-Calling Schema --
MEMORY_SCHEMA = {
"name": "memory",
diff --git a/tools/memory_tool_store.py b/tools/memory_tool_store.py
index 2c9005cf71f..b5cffcdf0a8 100644
--- a/tools/memory_tool_store.py
+++ b/tools/memory_tool_store.py
@@ -24,12 +24,6 @@ MEMORY_BLOCK_HEADERS = {
ENTRY_DELIMITER = "\n§\n"
-# Sentinel from ``_reload_target``: the file EXISTS but could not be read.
-# Distinct from a drift-backup path (str) and a clean reload (None); the caller
-# must abort rather than persist over an unreadable file.
-_READ_FAILED = object()
-
-
def _memory_dir() -> Path:
from tools import memory_tool
@@ -37,16 +31,15 @@ def _memory_dir() -> Path:
def _scan_memory_content(content: str) -> Optional[str]:
- """Scan memory content for injection/exfil patterns ("strict" scope: memory
- enters the system prompt as a frozen snapshot, so a poisoned entry persists
- across sessions). Returns the error string if blocked."""
+ """Scan for injection/exfil patterns ("strict" scope: memory enters the system
+ prompt as a frozen snapshot, so a poisoned entry persists across sessions).
+ Returns the error string if blocked."""
return _first_threat_message(content, scope="strict")
def _drift_error(path: "Path", bak_path: str) -> Dict[str, Any]:
- """Error dict for external drift: the on-disk file wouldn't round-trip
- through the parser/serializer, so flushing would discard content added by a
- patch tool, shell append, manual edit, or sister session."""
+ """Error dict for external drift: the on-disk file wouldn't round-trip through
+ the parser/serializer, so flushing would discard externally added content."""
return {
"success": False,
"error": (
@@ -65,7 +58,7 @@ def _drift_error(path: "Path", bak_path: str) -> Dict[str, Any]:
def _read_failed_error(path: "Path") -> Dict[str, Any]:
- """Error dict for an unreadable (but existing) memory file. Treating it as
+ """Error dict for an unreadable (but existing) memory file: treating it as
empty and saving would rewrite the whole file from ``[]`` — wiping memory."""
return {"success": False, "error": (
f"Refusing to write {path.name}: the file exists on disk but could not be read right now "
@@ -119,10 +112,10 @@ class MemoryStore:
self._consolidation_failures = 0
def _consolidation_failure(self, response: Dict[str, Any]) -> Dict[str, Any]:
- """Count an at-capacity consolidation failure. Under the per-turn cap
- return ``response`` unchanged (it says how to retry); past it return a
- TERMINAL result so the model stops looping — a failed memory side effect
- must never block the turn's reply."""
+ """Count an at-capacity consolidation failure. Under the per-turn cap return
+ ``response`` unchanged (it says how to retry); past it return a TERMINAL
+ result so the model stops looping — a failed memory side effect must never
+ block the turn's reply."""
self._consolidation_failures += 1
if self._consolidation_failures <= self._MAX_CONSOLIDATION_FAILURES_PER_TURN:
return response
@@ -146,16 +139,14 @@ class MemoryStore:
self._system_prompt_snapshot = {
target: self._render_block(target, self._sanitize_entries_for_snapshot(entries, filename))
for target, entries, filename in (
- ("memory", self.memory_entries, "MEMORY.md"),
- ("user", self.user_entries, "USER.md"),
- )
+ ("memory", self.memory_entries, "MEMORY.md"), ("user", self.user_entries, "USER.md"))
}
@staticmethod
def _sanitize_entries_for_snapshot(entries: List[str], filename: str) -> List[str]:
- """Return *entries* with any threat-matching entry replaced by a
- ``[BLOCKED: …]`` placeholder (strict scope, same as writes). Empty or
- already-blocked entries pass through unchanged."""
+ """*entries* with any threat-matching entry replaced by a ``[BLOCKED: …]``
+ placeholder (strict scope, same as writes). Empty or already-blocked
+ entries pass through unchanged."""
from tools.threat_patterns import scan_for_threats
sanitized: List[str] = []
@@ -205,32 +196,21 @@ class MemoryStore:
def _path_for(target: str) -> Path:
return _memory_dir() / ("USER.md" if target == "user" else "MEMORY.md")
- def _reload_target(self, target: str, *, skip_drift: bool = False):
- """Re-read entries from disk (under file lock) before mutating.
-
- Returns ``None`` on a clean reload; the backup path (str) on external
- drift (caller must abort — flushing would discard un-roundtrippable
- content); or ``_READ_FAILED`` when the file exists but could not be
- read (caller MUST abort — rewriting from an assumed-empty view would
- wipe it; even append-only ``add`` rewrites the whole file). Drift check
- and parse use the SAME raw snapshot — a failed second read used to count
- as "no drift". *skip_drift* skips the round-trip check (``add``).
- """
- raw, read_ok = self._read_raw_checked(self._path_for(target))
+ def _reload_or_error(self, target: str, *, skip_drift: bool = False) -> Optional[Dict[str, Any]]:
+ """Re-read entries from disk (under file lock) before mutating; return the
+ abort error dict, or None to proceed. Aborts on external drift (flushing
+ would discard un-roundtrippable content) and when the file exists but can't
+ be read (rewriting from an assumed-empty view would wipe it — even
+ append-only ``add`` rewrites the whole file). Drift check and parse use the
+ SAME raw snapshot — a failed second read used to count as "no drift".
+ *skip_drift* skips the round-trip check (``add``)."""
+ path = self._path_for(target)
+ raw, read_ok = self._read_raw_checked(path)
if not read_ok:
- return _READ_FAILED
+ return _read_failed_error(path)
bak = None if skip_drift else self._detect_external_drift(target, raw)
self._set_entries(target, list(dict.fromkeys(self._parse_entries(raw))))
- return bak
-
- def _reload_or_error(self, target: str, *, skip_drift: bool = False) -> Optional[Dict[str, Any]]:
- """Reload under lock; return the abort error dict, or None to proceed."""
- bak = self._reload_target(target, skip_drift=skip_drift)
- if bak is _READ_FAILED:
- return _read_failed_error(self._path_for(target))
- if bak:
- return _drift_error(self._path_for(target), bak)
- return None
+ return _drift_error(path, bak) if bak else None
def save_to_disk(self, target: str):
"""Persist entries to the appropriate file. Called after every mutation."""
@@ -256,8 +236,8 @@ class MemoryStore:
return f"{self._char_count(target):,}/{self._char_limit(target):,}"
def _failure_with_entries(self, target: str, message: str) -> Dict[str, Any]:
- """Consolidation failure that shows the live entries so the model can
- decide what to consolidate."""
+ """Consolidation failure showing the live entries so the model can decide
+ what to consolidate."""
return self._consolidation_failure({"success": False, "error": message,
"current_entries": self._entries_for(target), "usage": self._usage(target)})
@@ -386,13 +366,11 @@ class MemoryStore:
def apply_batch(self, target: str, operations: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Apply a sequence of add/replace/remove ops to one target atomically.
-
- Ops are validated and applied against the FINAL budget only — so a single
- call can free space (remove/replace) and add new entries without the
- multi-turn consolidate-then-retry dance. All-or-nothing: if any op is
- malformed, doesn't match, or the net result exceeds the char limit,
- NOTHING is written and the first failure plus live state is returned.
- """
+ Ops are validated and applied against the FINAL budget only — so one call
+ can free space (remove/replace) and add new entries without the multi-turn
+ consolidate-then-retry dance. All-or-nothing: if any op is malformed,
+ doesn't match, or the net result exceeds the char limit, NOTHING is written
+ and the first failure plus live state is returned."""
if not operations:
return {"success": False, "error": "operations list is empty."}
@@ -419,7 +397,9 @@ class MemoryStore:
pos = f"Operation {i + 1} ({act or 'unknown'})"
msg = self._apply_batch_op(working, act, content, old_text, pos)
if msg:
- return self._batch_error(target, msg)
+ # Batch-abort error reporting live (uncommitted) state.
+ return self._failure_with_entries(
+ target, msg + " No operations were applied (batch is all-or-nothing).")
# Budget check against the FINAL state only.
new_total = len(ENTRY_DELIMITER.join(working))
if new_total > limit:
@@ -430,16 +410,10 @@ class MemoryStore:
))
return self._commit(target, working, f"Applied {len(operations)} operation(s).")
- def _batch_error(self, target: str, message: str) -> Dict[str, Any]:
- """Build a batch-abort error that reports live (uncommitted) state."""
- return self._failure_with_entries(
- target, message + " No operations were applied (batch is all-or-nothing)."
- )
-
def format_for_system_prompt(self, target: str) -> Optional[str]:
- """Return the frozen load-time snapshot for system-prompt injection (NOT
- live state — mid-session writes don't affect it, preserving the prefix
- cache). None if the snapshot is empty."""
+ """The frozen load-time snapshot for system-prompt injection (NOT live
+ state — mid-session writes don't affect it, preserving the prefix cache).
+ None if the snapshot is empty."""
return self._system_prompt_snapshot.get(target, "") or None
# -- Internal helpers --
@@ -482,11 +456,11 @@ class MemoryStore:
@staticmethod
def _read_raw_checked(path: Path) -> Tuple[str, bool]:
"""Read raw text as ``(raw, read_ok)``. ``read_ok`` is False ONLY when the
- file EXISTS but can't be read (absent file → ``("", True)``). Invalid
- UTF-8 counts as unreadable; decoding stays STRICT because
- ``errors="replace"`` would hand callers a lossy view that a save then
- persists over the real bytes. ``utf-8-sig`` strips a Notepad BOM that
- otherwise glues U+FEFF onto the first entry forever."""
+ file EXISTS but can't be read (absent file → ``("", True)``). Invalid UTF-8
+ counts as unreadable; decoding stays STRICT because ``errors="replace"``
+ would hand callers a lossy view that a save then persists over the real
+ bytes. ``utf-8-sig`` strips a Notepad BOM that otherwise glues U+FEFF onto
+ the first entry forever."""
if not path.exists():
return "", True
try:
@@ -500,26 +474,20 @@ class MemoryStore:
the full ENTRY_DELIMITER so a bare "§" inside an entry is preserved."""
return [e for e in (x.strip() for x in raw.split(ENTRY_DELIMITER)) if e]
- @staticmethod
- def _read_entries_checked(path: Path) -> Tuple[List[str], bool]:
- """Read + parse as ``(entries, read_ok)`` — see ``_read_raw_checked``."""
- raw, read_ok = MemoryStore._read_raw_checked(path)
- return MemoryStore._parse_entries(raw), read_ok
-
@staticmethod
def _read_file(path: Path) -> List[str]:
"""Read a memory file into entries (empty list on any error). Only for
- read-only callers (``load_from_disk``, learning_mutations); mutation
- paths must use ``_read_raw_checked`` so they can refuse to overwrite an
+ read-only callers (``load_from_disk``, learning_mutations); mutation paths
+ must use ``_read_raw_checked`` so they can refuse to overwrite an
unreadable file."""
- return MemoryStore._read_entries_checked(path)[0]
+ return MemoryStore._parse_entries(MemoryStore._read_raw_checked(path)[0])
def _detect_external_drift(self, target: str, raw: str) -> Optional[str]:
"""Backup-path string if *raw* (the caller's checked-read snapshot) shows
external drift, else None. Signals: round-trip mismatch, or one parsed
- entry exceeding the whole-file char limit (no tool-written entry can —
- an external writer appended free-form content a flush would truncate).
- The file is snapshotted to ``.bak.<ts>`` so the operator can recover it."""
+ entry exceeding the whole-file char limit (no tool-written entry can — an
+ external writer appended free-form content a flush would truncate). The
+ file is snapshotted to ``.bak.<ts>`` so the operator can recover it."""
if not raw.strip():
return None
parsed = self._parse_entries(raw)