Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(memory): harden PersistentMemory.add() for control bytes, length, empty names (#112)

Teerapat Vatpitakdce3eb94c2e1
diff --git a/agent/src/memory/persistent.py b/agent/src/memory/persistent.py
index fc6890f2f..e50eef077 100644
--- a/agent/src/memory/persistent.py
+++ b/agent/src/memory/persistent.py
@@ -10,6 +10,7 @@ Storage layout:
from __future__ import annotations
+import hashlib
import logging
import re
from dataclasses import dataclass
@@ -83,6 +84,42 @@ def _tokenize(text: str) -> set[str]:
return set(_TOKEN_RE.findall(text.lower()))
+# Strip C0 (U+0000-U+001F except \t \n) and C1 (U+0080-U+009F) bytes from
+# user-supplied body content. These never carry useful payload from agent
+# writes but can be replayed back through `memory show` to inject ANSI
+# escape sequences into the user's terminal (see issue #108).
+_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
+
+# Truncation marker appended when content exceeds MAX_ENTRY_CHARS. Read
+# semantics are unchanged (clipped at MAX_ENTRY_CHARS), but the marker
+# makes the silent clip surfaceable to anyone inspecting the file directly
+# (see issue #109).
+_TRUNCATION_MARKER = "\n\n[truncated at {limit} chars]\n"
+
+
+def _sanitize_body(content: str) -> str:
+ """Strip C0/C1 control bytes from `content` while keeping ``\n`` and ``\t``."""
+ return _CONTROL_CHAR_RE.sub("", content)
+
+
+def _truncate_body(content: str, limit: int = None) -> str:
+ """Clip `content` to `limit` chars total, leaving room for the marker.
+
+ The marker is reserved inside the limit (not appended on top) so the on-
+ disk body length stays <= MAX_ENTRY_CHARS and the marker survives the
+ matching read-side clip in `_scan_entries`. Callers that inspect
+ `entry.body` see the marker; the original tail content past the head
+ window is dropped.
+ """
+ if limit is None:
+ limit = MAX_ENTRY_CHARS
+ if len(content) <= limit:
+ return content
+ marker = _TRUNCATION_MARKER.format(limit=limit)
+ head_len = max(0, limit - len(marker))
+ return content[:head_len] + marker
+
+
def _coerce_str(value: object, default: str = "") -> str:
"""Coerce frontmatter values to a display string.
@@ -230,32 +267,58 @@ class PersistentMemory:
"""Save a new memory entry and update the index.
Args:
- name: Memory name (used as filename slug).
- content: Memory body text.
+ name: Memory name (used as filename slug). Empty or whitespace-
+ only names are rejected.
+ content: Memory body text. C0/C1 control bytes (other than
+ ``\n`` and ``\t``) are stripped; the body is truncated to
+ ``MAX_ENTRY_CHARS`` with a visible marker.
memory_type: One of user/feedback/project/reference.
description: One-line description for retrieval scoring.
Returns:
Path to the created memory file.
+
+ Raises:
+ ValueError: If `name` is empty or whitespace-only.
"""
+ # Reject empty / whitespace-only names so they cannot all collapse
+ # to the same `{type}_.md` filename and silently overwrite each
+ # other (issue #110).
+ stripped_name = name.strip()
+ if not stripped_name:
+ raise ValueError("memory name must not be empty or whitespace-only")
+
# Preserve non-Latin script characters in the slug — collapsing
# them all to ``_`` caused two same-length non-Latin names to share a
- # filename and silently overwrite each other (see PR #95 for CJK;
- # this generalizes to Thai/Arabic/Hebrew/Cyrillic).
- slug = _SLUG_DISALLOWED_RE.sub("_", name.lower().strip())[:60]
+ # filename and silently overwrite each other (PR #95 + #104).
+ slug = _SLUG_DISALLOWED_RE.sub("_", stripped_name.lower())[:60]
+
+ # If the slug normalized to all underscores (emoji-only, punctuation-
+ # only, etc.) the on-disk filename would still collide between any
+ # two such names. Append a short deterministic hash so distinct
+ # inputs produce distinct files (issue #110).
+ if slug.strip("_") == "":
+ digest = hashlib.sha256(stripped_name.encode("utf-8")).hexdigest()[:6]
+ slug = f"{slug}_{digest}" if slug else digest
+
filename = f"{memory_type}_{slug}.md"
path = self._dir / filename
- safe_name = name.replace("\n", " ").replace("\r", " ")
- safe_desc = (description or name).replace("\n", " ").replace("\r", " ")
+ safe_name = stripped_name.replace("\n", " ").replace("\r", " ")
+ safe_desc = (description or stripped_name).replace("\n", " ").replace("\r", " ")
+
+ # Strip control bytes (#108) before truncation (#109) so the marker
+ # is computed against the user-visible content length.
+ clean_content = _truncate_body(_sanitize_body(content))
+
frontmatter = (
f"---\nname: {safe_name}\n"
f"description: {safe_desc}\n"
f"type: {memory_type}\n---\n\n"
- f"{content}"
+ f"{clean_content}"
)
path.write_text(frontmatter, encoding="utf-8")
- self._update_index(name, filename, description or name)
+ self._update_index(stripped_name, filename, description or stripped_name)
return path
def remove(self, name: str) -> bool:
diff --git a/agent/tests/test_persistent_memory.py b/agent/tests/test_persistent_memory.py
index f9144d144..5b1c6a42b 100644
--- a/agent/tests/test_persistent_memory.py
+++ b/agent/tests/test_persistent_memory.py
@@ -6,7 +6,15 @@ from pathlib import Path
import pytest
-from src.memory.persistent import PersistentMemory, MemoryEntry, _coerce_str, _tokenize
+from src.memory.persistent import (
+ MAX_ENTRY_CHARS,
+ MemoryEntry,
+ PersistentMemory,
+ _coerce_str,
+ _sanitize_body,
+ _tokenize,
+ _truncate_body,
+)
class TestCoerceStr:
@@ -312,3 +320,123 @@ class TestSnapshot:
def test_empty_dir_snapshot(self, tmp_path: Path) -> None:
pm = PersistentMemory(memory_dir=tmp_path)
assert pm.snapshot == ""
+
+
+class TestSanitizeBody:
+ """Regression for #108 — strip C0/C1 control bytes from agent-supplied content."""
+
+ def test_strips_ansi_escape(self) -> None:
+ assert _sanitize_body("hello\x1b[31mred\x1b[0m world") == "hello[31mred[0m world"
+
+ def test_strips_null_and_bell(self) -> None:
+ assert _sanitize_body("a\x00b\x07c") == "abc"
+
+ def test_preserves_tab_and_newline(self) -> None:
+ assert _sanitize_body("line1\nline2\tindented") == "line1\nline2\tindented"
+
+ def test_strips_c1_range(self) -> None:
+ # U+0080 to U+009F are C1 controls (PAD, NEL, etc.)
+ assert _sanitize_body("a\x80b\x9fc") == "abc"
+
+ def test_empty_passthrough(self) -> None:
+ assert _sanitize_body("") == ""
+
+
+class TestTruncateBody:
+ """Regression for #109 — enforce MAX_ENTRY_CHARS at write with visible marker."""
+
+ def test_short_passthrough(self) -> None:
+ assert _truncate_body("short") == "short"
+
+ def test_at_limit_passthrough(self) -> None:
+ text = "x" * MAX_ENTRY_CHARS
+ assert _truncate_body(text) == text
+
+ def test_over_limit_truncated_with_marker(self) -> None:
+ text = "x" * (MAX_ENTRY_CHARS + 100)
+ out = _truncate_body(text)
+ # Total body length stays within MAX_ENTRY_CHARS so the marker survives
+ # the read-side clip in _scan_entries.
+ assert len(out) <= MAX_ENTRY_CHARS
+ # Marker is at the tail; head still starts with content.
+ assert out.startswith("x")
+ assert out.endswith("chars]\n")
+ assert "[truncated at" in out
+ assert str(MAX_ENTRY_CHARS) in out
+
+ def test_custom_limit(self) -> None:
+ # Custom limit must be large enough to fit the marker plus some head.
+ text = "abcdef" * 100 # 600 chars
+ out = _truncate_body(text, limit=100)
+ assert len(out) <= 100
+ assert out.startswith("abc")
+ assert "[truncated at 100 chars]" in out
+
+
+class TestAddRejectsEmptyName:
+ """Regression for #110 — reject empty / whitespace-only names."""
+
+ def test_empty_raises(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ with pytest.raises(ValueError, match="empty or whitespace"):
+ pm.add("", "body", "user")
+
+ def test_whitespace_only_raises(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ with pytest.raises(ValueError, match="empty or whitespace"):
+ pm.add(" ", "body", "user")
+
+ def test_tab_only_raises(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ with pytest.raises(ValueError):
+ pm.add("\t\n ", "body", "user")
+
+
+class TestAddHashSuffixForCollapsedSlug:
+ """Regression for #110 — distinct emoji-only / punctuation-only names must
+ produce distinct files via deterministic hash suffix."""
+
+ def test_two_distinct_emoji_names_no_collision(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ p1 = pm.add("🚀", "rocket body", "reference") # 🚀
+ p2 = pm.add("🎯", "target body", "reference") # 🎯
+ assert p1 != p2
+ assert "rocket body" in p1.read_text(encoding="utf-8")
+ assert "target body" in p2.read_text(encoding="utf-8")
+
+ def test_hash_is_deterministic(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ p1 = pm.add("🚀", "v1", "reference")
+ p2 = pm.add("🚀", "v2", "reference")
+ # Same name → same slug → overwrite (this is expected and desired
+ # for the "edit memory" workflow).
+ assert p1 == p2
+ assert "v2" in p1.read_text(encoding="utf-8")
+
+ def test_punctuation_only_name_gets_hash(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ path = pm.add("???", "body", "user")
+ # Slug ??? -> _ after sanitization; hash appended.
+ # File name must not be just "user_.md".
+ assert path.name != "user_.md"
+ assert path.exists()
+
+
+class TestAddSanitizesAndTruncates:
+ """Regression for #108 + #109 wired into `PersistentMemory.add()`."""
+
+ def test_add_strips_control_bytes_in_body(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ path = pm.add("ctrl-test", "before\x1b[31mred\x1b[0mafter", "user")
+ body_on_disk = path.read_text(encoding="utf-8")
+ # ESC byte must be gone; surrounding text preserved.
+ assert "\x1b" not in body_on_disk
+ assert "before" in body_on_disk and "after" in body_on_disk
+ assert "[31m" in body_on_disk # the textual remainder is fine
+
+ def test_add_truncates_long_body_with_marker(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ path = pm.add("long-content", "x" * (MAX_ENTRY_CHARS + 500), "reference")
+ body_on_disk = path.read_text(encoding="utf-8").split("---\n\n", 1)[1]
+ assert len(body_on_disk) <= MAX_ENTRY_CHARS + len("\n\n[truncated at chars]\n") + 20
+ assert "[truncated at" in body_on_disk