"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(memory): address code review findings for Phase 1
shadowinlifec79d9a3e5697
diff --git a/agent/src/memory/lifecycle.py b/agent/src/memory/lifecycle.pyindex 905a00856..77ead0515 100644--- a/agent/src/memory/lifecycle.py+++ b/agent/src/memory/lifecycle.py@@ -13,12 +13,15 @@ Feature flags (env vars):from __future__ import annotationsimport logging+import osimport timefrom pathlib import Path+from types import MappingProxyTypefrom src.memory.persistent import (MemoryEntry,PersistentMemory,+ _is_hotness_decay_enabled as is_hotness_decay_enabled,compute_importance,memory_lock,)@@ -51,13 +54,6 @@ def is_decay_enabled() -> bool:return get_env_config().memory.decay_enabled-def is_hotness_decay_enabled() -> bool:- """Check if hotness decay is enabled via VT_MEMORY_HOTNESS_DECAY env var."""- from src.config.accessor import get_env_config-- return get_env_config().memory.hotness_decay_enabled--# ---------------------------------------------------------------------------# Helper# ---------------------------------------------------------------------------@@ -81,14 +77,13 @@ class MemoryLifecycle:file-level locking."""- # Event -> delta mapping- _EVENT_DELTAS: dict[str, float] = {+ _EVENT_DELTAS: MappingProxyType[str, float] = MappingProxyType({"task_success": 0.1,"task_failure": -0.15,"user_confirm": 0.2,"user_reject": -0.3,"passive_decay": -0.05,- }+ })# Safety: per-memory per-session cap_MAX_SESSION_DELTA = 0.5@@ -293,12 +288,19 @@ class MemoryLifecycle:def _update_frontmatter_field(self, path: Path, field: str, value: str) -> None:- """Update a single frontmatter field in a memory file."""+ """Update a single frontmatter field in a memory file.++ Uses an atomic write-then-rename strategy to prevent file corruption+ if the process crashes mid-write.+ """text = path.read_text(encoding="utf-8")lines = text.split("\n")- # Find frontmatter boundariesif not lines or lines[0].strip() != "---":+ logger.warning(+ "_update_frontmatter_field(%s): no frontmatter delimiters in %s",+ field, path,+ )returnend_idx = Nonefor i in range(1, len(lines)):@@ -306,9 +308,12 @@ class MemoryLifecycle:end_idx = ibreakif end_idx is None:+ logger.warning(+ "_update_frontmatter_field(%s): no closing delimiter in %s",+ field, path,+ )return- # Update or insert fieldfield_found = Falsefor i in range(1, end_idx):if lines[i].startswith(f"{field}:"):@@ -318,4 +323,6 @@ class MemoryLifecycle:if not field_found:lines.insert(end_idx, f"{field}: {value}")- path.write_text("\n".join(lines), encoding="utf-8")+ tmp_path = path.with_suffix(path.suffix + ".tmp")+ tmp_path.write_text("\n".join(lines), encoding="utf-8")+ os.replace(tmp_path, path)diff --git a/agent/src/memory/persistent.py b/agent/src/memory/persistent.pyindex e389fd7b7..bd950eaab 100644--- a/agent/src/memory/persistent.py+++ b/agent/src/memory/persistent.py@@ -361,13 +361,20 @@ class PersistentMemory:"""new_hash = content_hash(name, description, content)now = _time.time()- # Check recent writes cache (in-memory dict, not persisted)+ self._cleanup_expired_hashes(now)if new_hash in self._recent_hashes:if now - self._recent_hashes[new_hash] < DEDUP_WINDOW_SECONDS:return Trueself._recent_hashes[new_hash] = nowreturn False+ def _cleanup_expired_hashes(self, now: float) -> None:+ """Remove hash entries older than the dedup window to bound memory use."""+ threshold = now - DEDUP_WINDOW_SECONDS+ expired = [h for h, ts in self._recent_hashes.items() if ts < threshold]+ for h in expired:+ del self._recent_hashes[h]+def add(self, name: str, content: str, memory_type: str = "project",description: str = "") -> Optional[Path]:"""Save a new memory entry and update the index."""diff --git a/agent/src/tools/remember_tool.py b/agent/src/tools/remember_tool.pyindex 0118e6d67..682755b56 100644--- a/agent/src/tools/remember_tool.py+++ b/agent/src/tools/remember_tool.py@@ -105,6 +105,8 @@ class RememberTool(BaseTool):path = self._memory.add(title, content, memory_type, description=title)except ValueError as exc:return json.dumps({"status": "error", "error": str(exc)})+ if path is None:+ return json.dumps({"status": "skipped", "message": f"Duplicate write blocked for: {title}"})return json.dumps({"status": "ok", "message": f"Saved: {title}", "path": str(path)})def _recall(self, kwargs: dict) -> str:@@ -112,6 +114,10 @@ class RememberTool(BaseTool):if not query:return json.dumps({"status": "error", "error": "query required"})entries = self._memory.find_relevant(query)+ # Track access for each recalled entry so importance decay+ # reflects actual usage patterns.+ for e in entries:+ self._lifecycle.track_access(e)results = [{"title": e.title, "type": e.memory_type, "content": e.body[:2000]}for e in entries