Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(memory): implement Phase 1 lifecycle management

shadowinlife6628c4a83304
diff --git a/agent/src/memory/lifecycle.py b/agent/src/memory/lifecycle.py
new file mode 100644
index 000000000..bf5723c7b
--- /dev/null
+++ b/agent/src/memory/lifecycle.py
@@ -0,0 +1,381 @@
+"""Memory lifecycle management: quality scoring, decay, and garbage collection.
+
+Provides reinforcement learning-style quality updates, Ebbinghaus-inspired
+importance decay, and capacity-based garbage collection. All write operations
+are guarded by file-level locking (single-writer model).
+
+Feature flags (env vars):
+ VT_MEMORY_QUALITY – enable quality scoring / access tracking
+ VT_MEMORY_GC – enable garbage collection
+ VT_MEMORY_DECAY – enable importance decay formula
+"""
+
+from __future__ import annotations
+
+import fcntl
+import logging
+import math
+import os
+import time
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Generator
+
+from src.memory.persistent import MemoryEntry, PersistentMemory
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Feature flags
+# ---------------------------------------------------------------------------
+
+
+def is_quality_enabled() -> bool:
+ """Check if quality scoring is enabled via VT_MEMORY_QUALITY env var."""
+ return os.environ.get("VT_MEMORY_QUALITY", "0") == "1"
+
+
+def is_gc_enabled() -> bool:
+ """Check if garbage collection is enabled via VT_MEMORY_GC env var."""
+ return os.environ.get("VT_MEMORY_GC", "0") == "1"
+
+
+def is_decay_enabled() -> bool:
+ """Check if importance decay is enabled via VT_MEMORY_DECAY env var."""
+ return os.environ.get("VT_MEMORY_DECAY", "0") == "1"
+
+
+# ---------------------------------------------------------------------------
+# File lock
+# ---------------------------------------------------------------------------
+
+LOCK_TIMEOUT_S = 5.0
+
+
+@contextmanager
+def memory_lock(memory_dir: Path) -> Generator[bool, None, None]:
+ """Acquire exclusive file lock for write operations.
+
+ Single-writer model: only one agent session writes at a time.
+ On timeout (5s), the operation is skipped with a warning.
+
+ Yields:
+ True if lock acquired, False if timed out.
+ """
+ lock_path = memory_dir / ".lock"
+ lock_path.touch(exist_ok=True)
+ fd = None
+ try:
+ fd = open(lock_path, "w") # noqa: SIM115
+ deadline = time.monotonic() + LOCK_TIMEOUT_S
+ while True:
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ yield True
+ return
+ except (OSError, BlockingIOError):
+ if time.monotonic() >= deadline:
+ logger.warning(
+ "memory_lock: timeout after %.1fs, skipping write",
+ LOCK_TIMEOUT_S,
+ )
+ yield False
+ return
+ time.sleep(0.1)
+ finally:
+ if fd:
+ try:
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ except OSError:
+ pass
+ fd.close()
+
+
+# ---------------------------------------------------------------------------
+# Importance / decay
+# ---------------------------------------------------------------------------
+
+HALF_LIFE_DAYS = 14.0
+DECAY_LAMBDA = math.log(2) / HALF_LIFE_DAYS
+ACCESS_BOOST = 0.1
+MAX_IMPORTANCE = 1.0
+
+
+def compute_importance(
+ quality_score: float,
+ access_count: int,
+ days_since_last_access: float,
+) -> float:
+ """Compute importance score using Ebbinghaus-inspired decay.
+
+ importance = quality * retention
+ retention = exp(-lambda * t) + access_bonus
+
+ Args:
+ quality_score: Memory quality in [0.0, 1.0].
+ access_count: Number of times recalled.
+ days_since_last_access: Days since last access.
+
+ Returns:
+ Importance in [0.0, 1.0].
+ """
+ if not is_decay_enabled():
+ return quality_score # Fallback: importance = quality when decay disabled
+ retention = math.exp(-DECAY_LAMBDA * max(0.0, days_since_last_access))
+ access_bonus = min(0.3, access_count * ACCESS_BOOST)
+ raw = quality_score * (retention + access_bonus)
+ return min(MAX_IMPORTANCE, max(0.0, raw))
+
+
+# ---------------------------------------------------------------------------
+# Helper
+# ---------------------------------------------------------------------------
+
+
+def _now_iso() -> str:
+ """Current time as ISO-8601 string."""
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
+
+
+# ---------------------------------------------------------------------------
+# MemoryLifecycle
+# ---------------------------------------------------------------------------
+
+
+class MemoryLifecycle:
+ """Lifecycle management for persistent memory: quality scoring, decay, GC.
+
+ Wraps a PersistentMemory instance and provides reinforcement, garbage
+ collection, and access tracking. All write operations are guarded by
+ file-level locking.
+ """
+
+ # Event -> delta mapping
+ _EVENT_DELTAS: dict[str, float] = {
+ "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
+
+ # GC thresholds
+ ARCHIVE_THRESHOLD = 0.15
+ DELETE_THRESHOLD = 0.05
+ MIN_AGE_DAYS = 7
+ MAX_MEMORY_COUNT = 500
+ ENABLE_DELETE = False # Tier 1: archive only
+
+ def __init__(self, memory: PersistentMemory) -> None:
+ self._memory = memory
+ self._session_deltas: dict[str, float] = {} # name -> cumulative delta
+
+ @property
+ def memory_dir(self) -> Path:
+ """Return the underlying memory directory."""
+ return self._memory._dir
+
+ # ------------------------------------------------------------------
+ # Reinforcement
+ # ------------------------------------------------------------------
+
+ def reinforce(self, name: str, event: str, source: str = "system") -> bool:
+ """Update quality score based on usage feedback.
+
+ Args:
+ name: Memory entry name (exact match).
+ event: One of "task_success", "task_failure", "user_confirm",
+ "user_reject", "passive_decay".
+ source: "user" (full confidence) or "system" (0.7x discount).
+
+ Returns:
+ True if reinforced successfully, False if skipped.
+ """
+ if not is_quality_enabled():
+ return False
+ if event not in self._EVENT_DELTAS:
+ logger.warning("reinforce: unknown event %r", event)
+ return False
+
+ delta = self._EVENT_DELTAS[event]
+ if source == "system":
+ delta *= 0.7
+
+ # Session cap check
+ current = self._session_deltas.get(name, 0.0)
+ if abs(current + delta) > self._MAX_SESSION_DELTA:
+ logger.info("reinforce(%s): session cap reached (%.2f)", name, current)
+ return False
+
+ entry = self._memory.find(name)
+ if entry is None:
+ logger.warning("reinforce(%s): not found", name)
+ return False
+
+ with memory_lock(self.memory_dir) as acquired:
+ if not acquired:
+ return False
+ try:
+ new_qs = max(0.0, min(1.0, entry.quality_score + delta))
+ self._update_frontmatter_field(
+ entry.path, "quality_score", f"{new_qs:.2f}"
+ )
+ self._update_frontmatter_field(entry.path, "updated_at", _now_iso())
+ self._session_deltas[name] = current + delta
+ return True
+ except (FileNotFoundError, IOError) as exc:
+ logger.warning("reinforce(%s) skipped: %s", name, exc)
+ return False
+
+ # ------------------------------------------------------------------
+ # Access tracking
+ # ------------------------------------------------------------------
+
+ def track_access(self, entry: MemoryEntry) -> None:
+ """Increment access_count and update last_accessed for a recalled entry."""
+ if not is_quality_enabled():
+ return
+ with memory_lock(self.memory_dir) as acquired:
+ if not acquired:
+ return
+ try:
+ self._update_frontmatter_field(
+ entry.path, "access_count", str(entry.access_count + 1)
+ )
+ self._update_frontmatter_field(
+ entry.path, "last_accessed", _now_iso()
+ )
+ except (FileNotFoundError, IOError) as exc:
+ logger.warning("track_access(%s) skipped: %s", entry.title, exc)
+
+ # ------------------------------------------------------------------
+ # Garbage collection
+ # ------------------------------------------------------------------
+
+ def run_gc(self, dry_run: bool = True) -> list[dict]:
+ """Run garbage collection on memory store.
+
+ Args:
+ dry_run: If True (default), log actions without modifying files.
+
+ Returns:
+ List of action records [{name, action, importance, reason}].
+ """
+ if not is_gc_enabled():
+ return []
+
+ entries = self._memory.list_entries()
+ if len(entries) <= self.MAX_MEMORY_COUNT and dry_run:
+ return [] # Under capacity in dry-run = nothing to report
+
+ now = time.time()
+ actions: list[dict] = []
+
+ for entry in entries:
+ age_days = (now - entry.created_at) / 86400.0
+ if age_days < self.MIN_AGE_DAYS:
+ continue
+
+ days_since_access = (now - entry.last_accessed) / 86400.0
+ imp = compute_importance(
+ entry.quality_score, entry.access_count, days_since_access
+ )
+
+ action = None
+ reason = ""
+ if imp < self.DELETE_THRESHOLD and self.ENABLE_DELETE:
+ action = "delete"
+ reason = f"importance {imp:.3f} < delete threshold"
+ elif imp < self.ARCHIVE_THRESHOLD:
+ action = "archive"
+ reason = f"importance {imp:.3f} < archive threshold"
+
+ if action:
+ record = {
+ "name": entry.title,
+ "action": action,
+ "importance": round(imp, 4),
+ "reason": reason,
+ }
+ actions.append(record)
+ if not dry_run:
+ # Tier 1: force archive even if classified as delete
+ effective = "archive" if not self.ENABLE_DELETE else action
+ self._execute_gc_action(entry, effective)
+
+ self._append_gc_log(actions, dry_run)
+ return actions
+
+ def _execute_gc_action(self, entry: MemoryEntry, action: str) -> None:
+ """Execute a GC action (archive or delete) on an entry."""
+ archive_dir = self.memory_dir / "archive"
+ archive_dir.mkdir(exist_ok=True)
+
+ with memory_lock(self.memory_dir) as acquired:
+ if not acquired:
+ return
+ if action == "archive":
+ dest = archive_dir / entry.path.name
+ entry.path.rename(dest)
+ elif action == "delete":
+ dest = archive_dir / entry.path.name
+ dest.write_text(
+ entry.path.read_text(encoding="utf-8"), encoding="utf-8"
+ )
+ entry.path.unlink()
+
+ # Rebuild index after removal
+ self._memory._rebuild_index()
+
+ def _append_gc_log(self, actions: list[dict], dry_run: bool) -> None:
+ """Append GC decisions to gc.log."""
+ log_path = self.memory_dir / "gc.log"
+ timestamp = _now_iso()
+ mode = "dry_run" if dry_run else "execute"
+ lines = [f"[{timestamp}] mode={mode} actions={len(actions)}"]
+ for a in actions:
+ lines.append(
+ f" {a['action']}: {a['name']} "
+ f"(importance={a['importance']}, {a['reason']})"
+ )
+ lines.append("")
+
+ with open(log_path, "a", encoding="utf-8") as f:
+ f.write("\n".join(lines))
+
+ # ------------------------------------------------------------------
+ # Frontmatter manipulation
+ # ------------------------------------------------------------------
+
+ def _update_frontmatter_field(
+ self, path: Path, field: str, value: str
+ ) -> None:
+ """Update a single frontmatter field in a memory file."""
+ text = path.read_text(encoding="utf-8")
+ lines = text.split("\n")
+
+ # Find frontmatter boundaries
+ if not lines or lines[0].strip() != "---":
+ return
+ end_idx = None
+ for i in range(1, len(lines)):
+ if lines[i].strip() == "---":
+ end_idx = i
+ break
+ if end_idx is None:
+ return
+
+ # Update or insert field
+ field_found = False
+ for i in range(1, end_idx):
+ if lines[i].startswith(f"{field}:"):
+ lines[i] = f"{field}: {value}"
+ field_found = True
+ break
+ if not field_found:
+ lines.insert(end_idx, f"{field}: {value}")
+
+ path.write_text("\n".join(lines), encoding="utf-8")
diff --git a/agent/src/memory/persistent.py b/agent/src/memory/persistent.py
index 736d5aa1d..38b308376 100644
--- a/agent/src/memory/persistent.py
+++ b/agent/src/memory/persistent.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import hashlib
import logging
import re
+import time as _time
from dataclasses import dataclass
from pathlib import Path
@@ -46,16 +47,7 @@ _SLUG_DISALLOWED_RE = re.compile(rf"[^a-z0-9_\-{_NON_LATIN_SCRIPT_RANGES}]")
@dataclass(frozen=True)
class MemoryEntry:
- """A single memory entry on disk.
-
- Attributes:
- path: File path.
- title: Memory title.
- description: One-line description (used for retrieval scoring).
- memory_type: Category (user/feedback/project/reference).
- body: Body text content.
- modified_at: File modification timestamp.
- """
+ """A single memory entry on disk."""
path: Path
title: str
@@ -63,54 +55,42 @@ class MemoryEntry:
memory_type: str
body: str
modified_at: float
+ # Phase 1 fields — all have defaults for backward compatibility
+ id: str = "" # 6-char hex; generated from name+mtime if empty
+ created_at: float = 0.0 # epoch seconds; 0 means use modified_at
+ updated_at: float = 0.0 # epoch seconds; 0 means use modified_at
+ keywords: tuple[str, ...] = () # max 5 tags
+ quality_score: float = 0.5 # [0.0, 1.0]; neutral default
+ access_count: int = 0 # cumulative recall hits
+ last_accessed: float = 0.0 # epoch; 0 means use modified_at
+ importance: float = 0.5 # computed via decay formula
+ related_memories: tuple[str, ...] = () # linked IDs
def _tokenize(text: str) -> set[str]:
"""Split text into searchable tokens.
- ASCII words >= 3 chars + individual characters from non-Latin scripts
- listed in ``_NON_LATIN_SCRIPT_RANGES`` (CJK, Thai, Arabic, Hebrew,
- Cyrillic). Underscores are
- treated as word boundaries so snake_case titles (e.g. ``mcp_wiring_test``)
- match natural-language queries (``"mcp wiring"``) as well as verbatim
- lookups.
-
- Args:
- text: Input text.
-
- Returns:
- Set of tokens.
+ ASCII words >= 3 chars + individual characters from non-Latin scripts.
+ Underscores are treated as word boundaries so snake_case titles match
+ natural-language queries.
"""
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).
+# Strip C0 (U+0000-U+001F except \t \n) and C1 (U+0080-U+009F) bytes.
_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 appended when content exceeds MAX_ENTRY_CHARS.
_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``."""
+ """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.
- """
+ """Clip `content` to `limit` chars, leaving room for the marker."""
if limit is None:
limit = MAX_ENTRY_CHARS
if len(content) <= limit:
@@ -123,9 +103,7 @@ def _truncate_body(content: str, limit: int = None) -> str:
def _coerce_str(value: object, default: str = "") -> str:
"""Coerce frontmatter values to a display string.
- ``parse_frontmatter`` returns lists for ``[a, b]`` syntax and bools for
- ``true``/``false``. ``MemoryEntry`` annotates these fields as ``str`` so
- callers (CLI rendering, recall scoring) can rely on string operations.
+ Handles lists (``[a, b]``), bools, None, etc.
"""
if value is None:
return default
@@ -138,24 +116,31 @@ def _coerce_str(value: object, default: str = "") -> str:
return str(value)
+def _parse_timestamp(value: object, fallback: float) -> float:
+ """Parse a timestamp from frontmatter. Returns epoch float."""
+ if value is None:
+ return fallback
+ if isinstance(value, (int, float)):
+ return float(value)
+ if isinstance(value, str):
+ try:
+ from datetime import datetime
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ return dt.timestamp()
+ except (ValueError, TypeError):
+ pass
+ return fallback
+
+
class PersistentMemory:
"""File-based persistent memory that survives across sessions.
- Design:
- - Frozen snapshot injected into system prompt at session start (preserves prompt cache).
- - Disk writes via add()/remove() update files immediately but do NOT change the snapshot.
- - Next session picks up the updated state.
-
- Attributes:
- snapshot: Frozen memory index text for system prompt injection.
+ Frozen snapshot injected into system prompt at session start.
+ Disk writes via add()/remove() update files immediately but do NOT
+ change the snapshot. Next session picks up the updated state.
"""
def __init__(self, memory_dir: Optional[Path] = None) -> None:
- """Initialize PersistentMemory.
-
- Args:
- memory_dir: Override memory directory (default: ~/.vibe-trading/memory/).
- """
self._dir = memory_dir or MEMORY_BASE
self._dir.mkdir(parents=True, exist_ok=True)
self._index_path = self._dir / "MEMORY.md"
@@ -178,11 +163,7 @@ class PersistentMemory:
return self._snapshot
def _scan_entries(self) -> List[MemoryEntry]:
- """Scan all .md files (except MEMORY.md) and parse frontmatter.
-
- Returns:
- List of parsed memory entries.
- """
+ """Scan all .md files (except MEMORY.md) and parse frontmatter."""
entries: List[MemoryEntry] = []
for path in sorted(self._dir.glob("*.md")):
if path.name == "MEMORY.md":
@@ -192,13 +173,60 @@ class PersistentMemory:
except OSError:
continue
meta, body = _parse_frontmatter(text)
+ mtime = path.stat().st_mtime
+
+ # Parse new fields with safe defaults
+ raw_kw = meta.get("keywords", [])
+ keywords = tuple(
+ str(k)[:30] for k in (raw_kw if isinstance(raw_kw, list) else [])
+ )[:5]
+
+ raw_related = meta.get("related_memories", [])
+ related = tuple(
+ str(r) for r in (raw_related if isinstance(raw_related, list) else [])
+ if isinstance(r, str) and len(r) == 6
+ )
+
+ qs = meta.get("quality_score", 0.5)
+ try:
+ qs = max(0.0, min(1.0, float(qs)))
+ except (TypeError, ValueError):
+ qs = 0.5
+
+ ac = meta.get("access_count", 0)
+ try:
+ ac = max(0, int(ac))
+ except (TypeError, ValueError):
+ ac = 0
+
+ # Generate id if missing
+ entry_id = str(meta.get("id", ""))
+ if not entry_id or len(entry_id) != 6:
+ entry_id = hashlib.sha256(
+ f"{meta.get('name', path.stem)}{mtime}".encode()
+ ).hexdigest()[:6]
+
+ # Parse timestamps
+ created = _parse_timestamp(meta.get("created_at"), mtime)
+ updated = _parse_timestamp(meta.get("updated_at"), mtime)
+ last_acc = _parse_timestamp(meta.get("last_accessed"), mtime)
+
entries.append(MemoryEntry(
path=path,
title=_coerce_str(meta.get("name"), default=path.stem),
description=_coerce_str(meta.get("description")),
memory_type=_coerce_str(meta.get("type"), default="project"),
body=body[:MAX_ENTRY_CHARS],
- modified_at=path.stat().st_mtime,
+ modified_at=mtime,
+ id=entry_id,
+ created_at=created,
+ updated_at=updated,
+ keywords=keywords,
+ quality_score=qs,
+ access_count=ac,
+ last_accessed=last_acc,
+ importance=0.5,
+ related_memories=related,
))
return entries
@@ -210,7 +238,7 @@ class PersistentMemory:
"""Resolve a memory by exact title, then by on-disk filename stem.
Stem fallback accepts both the full ``{type}_{slug}`` form and the
- bare ``slug`` suffix so users can paste either form from the index.
+ bare ``slug`` suffix.
"""
needle = name.strip()
if not needle:
@@ -238,14 +266,8 @@ class PersistentMemory:
def find_relevant(self, query: str, max_results: int = MAX_RESULTS) -> List[MemoryEntry]:
"""Keyword search across all memory entries.
- Scoring: metadata_hits * 2.0 + body_hits * 1.0.
-
- Args:
- query: Search query.
- max_results: Maximum entries to return.
-
- Returns:
- Top-scoring memory entries.
+ Scoring: (metadata_hits + keyword_hits) * 2.0 + body_hits * 1.0,
+ weighted by importance.
"""
query_tokens = _tokenize(query)
if not query_tokens:
@@ -255,9 +277,15 @@ class PersistentMemory:
for entry in self._scan_entries():
meta_tokens = _tokenize(f"{entry.title} {entry.description}")
body_tokens = _tokenize(entry.body)
- score = len(query_tokens & meta_tokens) * METADATA_WEIGHT + len(query_tokens & body_tokens)
- if score > 0:
- scored.append((score, entry))
+ kw_tokens = _tokenize(" ".join(entry.keywords))
+ token_score = (
+ len(query_tokens & meta_tokens) * METADATA_WEIGHT
+ + len(query_tokens & kw_tokens) * METADATA_WEIGHT
+ + len(query_tokens & body_tokens)
+ )
+ if token_score > 0:
+ final_score = token_score * (0.5 + 0.5 * entry.importance)
+ scored.append((final_score, entry))
scored.sort(key=lambda x: (-x[0], -x[1].modified_at))
return [entry for _, entry in scored[:max_results]]
@@ -266,24 +294,9 @@ class PersistentMemory:
description: str = "") -> Path:
"""Save a new memory entry and update the index.
- Args:
- 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.
+ ValueError: If `name` is empty/whitespace-only or type is invalid.
"""
- # 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")
@@ -292,15 +305,10 @@ class PersistentMemory:
allowed = ", ".join(MEMORY_TYPES)
raise ValueError(f"memory_type must be one of: {allowed}")
- # 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 (PR #95 + #104).
+ # Preserve non-Latin script characters in the slug
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 normalized to all underscores, append a hash
if slug.strip("_") == "":
digest = hashlib.sha256(stripped_name.encode("utf-8")).hexdigest()[:6]
slug = f"{slug}_{digest}" if slug else digest
@@ -311,14 +319,28 @@ class PersistentMemory:
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))
+ # Generate Phase 1 metadata
+ entry_id = hashlib.sha256(
+ f"{stripped_name}{_time.time()}".encode()
+ ).hexdigest()[:6]
+ now_iso = _time.strftime("%Y-%m-%dT%H:%M:%S", _time.gmtime())
+
frontmatter = (
f"---\nname: {safe_name}\n"
f"description: {safe_desc}\n"
- f"type: {memory_type}\n---\n\n"
+ f"type: {memory_type}\n"
+ f"id: {entry_id}\n"
+ f"created_at: {now_iso}\n"
+ f"updated_at: {now_iso}\n"
+ f"keywords: []\n"
+ f"quality_score: 0.5\n"
+ f"access_count: 0\n"
+ f"last_accessed: {now_iso}\n"
+ f"importance: 0.5\n"
+ f"related_memories: []\n"
+ f"---\n\n"
f"{clean_content}"
)
path.write_text(frontmatter, encoding="utf-8")
@@ -326,14 +348,7 @@ class PersistentMemory:
return path
def remove(self, name: str) -> bool:
- """Remove a memory entry by name.
-
- Args:
- name: Memory name to remove.
-
- Returns:
- True if found and removed.
- """
+ """Remove a memory entry by name. Returns True if found and removed."""
for entry in self._scan_entries():
if entry.title == name:
entry.path.unlink(missing_ok=True)
diff --git a/agent/src/tools/remember_tool.py b/agent/src/tools/remember_tool.py
index 3b6a3f7a2..0118e6d67 100644
--- a/agent/src/tools/remember_tool.py
+++ b/agent/src/tools/remember_tool.py
@@ -1,4 +1,4 @@
-"""Remember tool: LLM-initiated persistent memory operations (save / recall / forget)."""
+"""Remember tool: LLM-initiated persistent memory operations (save / recall / forget / reinforce)."""
from __future__ import annotations
@@ -6,6 +6,7 @@ import json
from typing import Any
from src.agent.tools import BaseTool
+from src.memory.lifecycle import MemoryLifecycle
from src.memory.persistent import PersistentMemory
@@ -20,7 +21,8 @@ class RememberTool(BaseTool):
"Persistent cross-session memory. "
"save: store user preferences, strategy insights, or project context. "
"recall: search past memories by keyword. "
- "forget: remove a memory by title."
+ "forget: remove a memory by title. "
+ "reinforce: provide quality feedback on a memory."
)
is_readonly = False
parameters = {
@@ -28,8 +30,8 @@ class RememberTool(BaseTool):
"properties": {
"action": {
"type": "string",
- "enum": ["save", "recall", "forget"],
- "description": "save | recall | forget",
+ "enum": ["save", "recall", "forget", "reinforce"],
+ "description": "save | recall | forget | reinforce",
},
"title": {
"type": "string",
@@ -48,6 +50,16 @@ class RememberTool(BaseTool):
"type": "string",
"description": "Search query (for recall)",
},
+ "event": {
+ "type": "string",
+ "enum": ["task_success", "task_failure", "user_confirm", "user_reject"],
+ "description": "Feedback event type (for reinforce)",
+ },
+ "source": {
+ "type": "string",
+ "enum": ["user", "system"],
+ "description": "Feedback source: user (full confidence) or system (discounted). Default: system",
+ },
},
"required": ["action"],
}
@@ -60,6 +72,7 @@ class RememberTool(BaseTool):
memory: PersistentMemory instance (auto-created if omitted).
"""
self._memory = memory or PersistentMemory()
+ self._lifecycle = MemoryLifecycle(self._memory)
def execute(self, **kwargs: Any) -> str:
"""Execute a memory action.
@@ -78,6 +91,8 @@ class RememberTool(BaseTool):
return self._recall(kwargs)
if action == "forget":
return self._forget(kwargs)
+ if action == "reinforce":
+ return self._reinforce(kwargs)
return json.dumps({"status": "error", "error": f"Unknown action: {action}"})
def _save(self, kwargs: dict) -> str:
@@ -110,3 +125,16 @@ class RememberTool(BaseTool):
removed = self._memory.remove(title)
msg = f"Removed: {title}" if removed else f"Not found: {title}"
return json.dumps({"status": "ok" if removed else "not_found", "message": msg})
+
+ def _reinforce(self, kwargs: dict) -> str:
+ title = kwargs.get("title", "")
+ event = kwargs.get("event", "")
+ if not title or not event:
+ return json.dumps({"status": "error", "error": "title and event required"})
+ source = kwargs.get("source", "system")
+ if source not in ("user", "system"):
+ source = "system"
+ success = self._lifecycle.reinforce(title, event, source)
+ if success:
+ return json.dumps({"status": "ok", "message": f"Reinforced: {title} ({event})"})
+ return json.dumps({"status": "skipped", "message": f"Reinforce skipped for: {title}"})
diff --git a/agent/tests/test_memory_gc.py b/agent/tests/test_memory_gc.py
new file mode 100644
index 000000000..aef274f6c
--- /dev/null
+++ b/agent/tests/test_memory_gc.py
@@ -0,0 +1,229 @@
+"""Tests for memory GC, find_relevant weighting, and RememberTool reinforce."""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+
+from src.memory.lifecycle import MemoryLifecycle
+from src.memory.persistent import PersistentMemory
+from src.tools.remember_tool import RememberTool
+
+
+# ---------------------------------------------------------------------------
+# Helper
+# ---------------------------------------------------------------------------
+
+
+def _create_memory_file(
+ tmp_path: Path,
+ name: str,
+ content: str = "test body",
+ memory_type: str = "project",
+ quality_score: float = 0.5,
+ access_count: int = 0,
+ keywords: list | None = None,
+ created_at: str = "2025-01-01T00:00:00",
+ last_accessed: str = "2025-01-01T00:00:00",
+ related_memories: list | None = None,
+ entry_id: str = "ab12cd",
+ importance: float = 0.5,
+) -> Path:
+ """Helper to create a memory file with extended frontmatter."""
+ kw_str = ", ".join(keywords) if keywords else ""
+ rel_str = ", ".join(related_memories) if related_memories else ""
+ slug = name.lower().replace(" ", "_")[:40]
+ filename = f"{memory_type}_{slug}.md"
+ path = tmp_path / filename
+ frontmatter = (
+ f"---\n"
+ f"name: {name}\n"
+ f"description: {name}\n"
+ f"type: {memory_type}\n"
+ f"id: {entry_id}\n"
+ f"created_at: {created_at}\n"
+ f"updated_at: {created_at}\n"
+ f"keywords: [{kw_str}]\n"
+ f"quality_score: {quality_score}\n"
+ f"access_count: {access_count}\n"
+ f"last_accessed: {last_accessed}\n"
+ f"importance: {importance}\n"
+ f"related_memories: [{rel_str}]\n"
+ f"---\n\n"
+ f"{content}"
+ )
+ path.write_text(frontmatter, encoding="utf-8")
+ return path
+
+
+# ---------------------------------------------------------------------------
+# 1. run_gc
+# ---------------------------------------------------------------------------
+
+
+class TestRunGC:
+ def test_gc_dry_run_no_file_changes(self, tmp_path: Path, monkeypatch) -> None:
+ """dry_run=True should not modify or move any files."""
+ monkeypatch.setenv("VT_MEMORY_GC", "1")
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ # Create old, low-quality entry that should be flagged
+ _create_memory_file(
+ tmp_path, "old-bad", quality_score=0.05, access_count=0,
+ created_at="2024-01-01T00:00:00", last_accessed="2024-01-01T00:00:00",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ # Override MAX_MEMORY_COUNT so dry_run still processes entries
+ lc.MAX_MEMORY_COUNT = 0
+ actions = lc.run_gc(dry_run=True)
+ # File still exists — not moved
+ assert (tmp_path / "project_old-bad.md").exists()
+ assert len(actions) >= 1
+
+ def test_gc_archives_low_importance(self, tmp_path: Path, monkeypatch) -> None:
+ """Entries below ARCHIVE_THRESHOLD should be moved to archive/."""
+ monkeypatch.setenv("VT_MEMORY_GC", "1")
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ _create_memory_file(
+ tmp_path, "garbage", quality_score=0.01, access_count=0,
+ created_at="2024-01-01T00:00:00", last_accessed="2024-01-01T00:00:00",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ actions = lc.run_gc(dry_run=False)
+ # Should be archived
+ assert len(actions) >= 1
+ assert actions[0]["action"] == "archive"
+ assert (tmp_path / "archive" / "project_garbage.md").exists()
+ assert not (tmp_path / "project_garbage.md").exists()
+
+ def test_gc_respects_min_age(self, tmp_path: Path, monkeypatch) -> None:
+ """Entries younger than MIN_AGE_DAYS should not be gc'd."""
+ monkeypatch.setenv("VT_MEMORY_GC", "1")
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ # Recent entry (created_at = now)
+ now_iso = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
+ _create_memory_file(
+ tmp_path, "young", quality_score=0.01, access_count=0,
+ created_at=now_iso, last_accessed=now_iso,
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ actions = lc.run_gc(dry_run=False)
+ # Young entry should be untouched
+ assert len(actions) == 0
+ assert (tmp_path / "project_young.md").exists()
+
+ def test_gc_disabled_when_flag_off(self, tmp_path: Path, monkeypatch) -> None:
+ """run_gc() returns [] when VT_MEMORY_GC=0."""
+ monkeypatch.setenv("VT_MEMORY_GC", "0")
+ _create_memory_file(
+ tmp_path, "should-stay", quality_score=0.01,
+ created_at="2024-01-01T00:00:00", last_accessed="2024-01-01T00:00:00",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ assert lc.run_gc(dry_run=False) == []
+
+ def test_gc_log_created(self, tmp_path: Path, monkeypatch) -> None:
+ """GC actions should be logged to gc.log."""
+ monkeypatch.setenv("VT_MEMORY_GC", "1")
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ _create_memory_file(
+ tmp_path, "log-test", quality_score=0.01, access_count=0,
+ created_at="2024-01-01T00:00:00", last_accessed="2024-01-01T00:00:00",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ # Override MAX_MEMORY_COUNT so dry_run processes entries
+ lc.MAX_MEMORY_COUNT = 0
+ lc.run_gc(dry_run=True)
+ log_path = tmp_path / "gc.log"
+ assert log_path.exists()
+ log_content = log_path.read_text(encoding="utf-8")
+ assert "dry_run" in log_content
+ assert "log-test" in log_content
+
+ def test_gc_delete_disabled_in_tier1(self, tmp_path: Path, monkeypatch) -> None:
+ """ENABLE_DELETE=False should force archive even for very low scores."""
+ monkeypatch.setenv("VT_MEMORY_GC", "1")
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ _create_memory_file(
+ tmp_path, "very-low", quality_score=0.001, access_count=0,
+ created_at="2024-01-01T00:00:00", last_accessed="2024-01-01T00:00:00",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ # Tier 1: ENABLE_DELETE is False by default
+ assert lc.ENABLE_DELETE is False
+ lc.run_gc(dry_run=False)
+ # Even with importance below DELETE_THRESHOLD, it is archived not deleted
+ assert (tmp_path / "archive" / "project_very-low.md").exists()
+ assert not (tmp_path / "project_very-low.md").exists()
+
+
+# ---------------------------------------------------------------------------
+# 2. find_relevant importance weighting
+# ---------------------------------------------------------------------------
+
+
+class TestFindRelevantImportanceWeighting:
+ def test_higher_importance_ranks_higher(self, tmp_path: Path) -> None:
+ """Entry with more metadata overlap should rank above body-only match."""
+ # "trading strategy" appears in title/description (metadata, 2x weight)
+ _create_memory_file(
+ tmp_path, "trading strategy notes", content="general notes",
+ quality_score=0.9, importance=0.9, entry_id="hi1234",
+ )
+ # "trading strategy" only in body (1x weight)
+ _create_memory_file(
+ tmp_path, "random notes", content="trading strategy details here",
+ quality_score=0.1, importance=0.1, entry_id="lo5678",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ results = pm.find_relevant("trading strategy")
+ assert len(results) == 2
+ # Metadata-weighted entry ranks first
+ assert results[0].title == "trading strategy notes"
+
+ def test_keywords_participate_in_scoring(self, tmp_path: Path) -> None:
+ """Keywords in frontmatter should contribute to retrieval score."""
+ _create_memory_file(
+ tmp_path, "kw-entry", content="unrelated body",
+ keywords=["momentum", "alpha"], entry_id="kw1234",
+ )
+ _create_memory_file(
+ tmp_path, "no-kw", content="unrelated body two",
+ entry_id="nk5678",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ results = pm.find_relevant("momentum alpha")
+ # The keyword-bearing entry should be found
+ assert any(e.title == "kw-entry" for e in results)
+
+
+# ---------------------------------------------------------------------------
+# 3. RememberTool reinforce
+# ---------------------------------------------------------------------------
+
+
+class TestRememberToolReinforce:
+ def test_reinforce_action_success(self, tmp_path: Path, monkeypatch) -> None:
+ """RememberTool reinforce action should return ok status."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "1")
+ _create_memory_file(tmp_path, "tool-mem", quality_score=0.5)
+ pm = PersistentMemory(memory_dir=tmp_path)
+ tool = RememberTool(memory=pm)
+ result = tool.execute(action="reinforce", title="tool-mem", event="task_success")
+ assert '"status": "ok"' in result
+
+ def test_reinforce_missing_params(self, tmp_path: Path) -> None:
+ """Missing title or event should return error."""
+ pm = PersistentMemory(memory_dir=tmp_path)
+ tool = RememberTool(memory=pm)
+ # Missing event
+ result = tool.execute(action="reinforce", title="some-mem")
+ assert '"status": "error"' in result
+ # Missing title
+ result2 = tool.execute(action="reinforce", event="task_success")
+ assert '"status": "error"' in result2
diff --git a/agent/tests/test_memory_lifecycle.py b/agent/tests/test_memory_lifecycle.py
new file mode 100644
index 000000000..092e37582
--- /dev/null
+++ b/agent/tests/test_memory_lifecycle.py
@@ -0,0 +1,338 @@
+"""Tests for memory lifecycle: quality scoring, decay, and reinforcement."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from src.memory.lifecycle import (
+ MemoryLifecycle,
+ compute_importance,
+ is_decay_enabled,
+ is_gc_enabled,
+ is_quality_enabled,
+ memory_lock,
+)
+from src.memory.persistent import PersistentMemory
+
+
+# ---------------------------------------------------------------------------
+# Helper
+# ---------------------------------------------------------------------------
+
+
+def _create_memory_file(
+ tmp_path: Path,
+ name: str,
+ content: str = "test body",
+ memory_type: str = "project",
+ quality_score: float = 0.5,
+ access_count: int = 0,
+ keywords: list | None = None,
+ created_at: str = "2025-01-01T00:00:00",
+ last_accessed: str = "2025-01-01T00:00:00",
+ related_memories: list | None = None,
+ entry_id: str = "ab12cd",
+ importance: float = 0.5,
+) -> Path:
+ """Helper to create a memory file with extended frontmatter."""
+ kw_str = ", ".join(keywords) if keywords else ""
+ rel_str = ", ".join(related_memories) if related_memories else ""
+ slug = name.lower().replace(" ", "_")[:40]
+ filename = f"{memory_type}_{slug}.md"
+ path = tmp_path / filename
+ frontmatter = (
+ f"---\n"
+ f"name: {name}\n"
+ f"description: {name}\n"
+ f"type: {memory_type}\n"
+ f"id: {entry_id}\n"
+ f"created_at: {created_at}\n"
+ f"updated_at: {created_at}\n"
+ f"keywords: [{kw_str}]\n"
+ f"quality_score: {quality_score}\n"
+ f"access_count: {access_count}\n"
+ f"last_accessed: {last_accessed}\n"
+ f"importance: {importance}\n"
+ f"related_memories: [{rel_str}]\n"
+ f"---\n\n"
+ f"{content}"
+ )
+ path.write_text(frontmatter, encoding="utf-8")
+ return path
+
+
+# ---------------------------------------------------------------------------
+# 1. MemoryEntry new fields (backward compatibility)
+# ---------------------------------------------------------------------------
+
+
+class TestMemoryEntryNewFields:
+ def test_old_file_without_new_fields_uses_defaults(self, tmp_path: Path) -> None:
+ """Legacy files without new frontmatter fields should parse with safe defaults."""
+ path = tmp_path / "project_old.md"
+ path.write_text(
+ "---\nname: old-mem\ndescription: legacy\ntype: project\n---\n\nold body\n",
+ encoding="utf-8",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ entries = pm.list_entries()
+ assert len(entries) == 1
+ e = entries[0]
+ assert e.quality_score == 0.5
+ assert e.access_count == 0
+ assert e.keywords == ()
+ assert e.related_memories == ()
+ assert len(e.id) == 6
+
+ def test_new_file_with_all_fields(self, tmp_path: Path) -> None:
+ """Files with extended frontmatter should parse all fields correctly."""
+ _create_memory_file(
+ tmp_path, "full-entry", quality_score=0.8, access_count=5,
+ keywords=["alpha", "beta"], entry_id="aa11bb",
+ related_memories=["cc22dd", "ee33ff"],
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ entries = pm.list_entries()
+ assert len(entries) == 1
+ e = entries[0]
+ assert e.quality_score == 0.8
+ assert e.access_count == 5
+ assert e.keywords == ("alpha", "beta")
+ assert e.id == "aa11bb"
+ assert e.related_memories == ("cc22dd", "ee33ff")
+
+ def test_invalid_quality_score_clamped(self, tmp_path: Path) -> None:
+ """quality_score outside [0,1] should be clamped."""
+ path = tmp_path / "project_high.md"
+ path.write_text(
+ "---\nname: high\ndescription: x\ntype: project\nquality_score: 2.5\n---\n\nbody\n",
+ encoding="utf-8",
+ )
+ path2 = tmp_path / "project_low.md"
+ path2.write_text(
+ "---\nname: low\ndescription: x\ntype: project\nquality_score: -0.5\n---\n\nbody\n",
+ encoding="utf-8",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ entries = {e.title: e for e in pm.list_entries()}
+ assert entries["high"].quality_score == 1.0
+ assert entries["low"].quality_score == 0.0
+
+ def test_invalid_access_count_reset(self, tmp_path: Path) -> None:
+ """Non-integer access_count should reset to 0."""
+ path = tmp_path / "project_badac.md"
+ path.write_text(
+ "---\nname: badac\ndescription: x\ntype: project\naccess_count: abc\n---\n\nbody\n",
+ encoding="utf-8",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ entries = pm.list_entries()
+ assert entries[0].access_count == 0
+
+ def test_keywords_truncated_to_five(self, tmp_path: Path) -> None:
+ """More than 5 keywords should be truncated."""
+ _create_memory_file(
+ tmp_path, "many-kw",
+ keywords=["a", "b", "c", "d", "e", "f", "g"],
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ entries = pm.list_entries()
+ assert len(entries[0].keywords) == 5
+
+ def test_related_memories_filters_invalid_ids(self, tmp_path: Path) -> None:
+ """Non-6-char IDs in related_memories should be dropped."""
+ _create_memory_file(
+ tmp_path, "bad-rel",
+ related_memories=["ab12cd", "too_long_id", "ok33ff", "x"],
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ entries = pm.list_entries()
+ # Only 6-char IDs survive
+ assert entries[0].related_memories == ("ab12cd", "ok33ff")
+
+ def test_id_generated_when_missing(self, tmp_path: Path) -> None:
+ """Missing id field should auto-generate 6-char hex."""
+ path = tmp_path / "project_noid.md"
+ path.write_text(
+ "---\nname: noid\ndescription: x\ntype: project\n---\n\nbody\n",
+ encoding="utf-8",
+ )
+ pm = PersistentMemory(memory_dir=tmp_path)
+ entries = pm.list_entries()
+ assert len(entries[0].id) == 6
+ assert all(c in "0123456789abcdef" for c in entries[0].id)
+
+
+# ---------------------------------------------------------------------------
+# 2. compute_importance
+# ---------------------------------------------------------------------------
+
+
+class TestComputeImportance:
+ def test_high_quality_recent_access(self, monkeypatch) -> None:
+ """High quality + recent access = high importance."""
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ result = compute_importance(0.9, 3, 0.0)
+ # retention=1.0, access_bonus=min(0.3, 3*0.1)=0.3 => 0.9*(1.0+0.3)=1.17 => capped 1.0
+ assert result == pytest.approx(1.0)
+
+ def test_low_quality_old_access(self, monkeypatch) -> None:
+ """Low quality + old access = low importance."""
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ result = compute_importance(0.2, 0, 30.0)
+ # retention=exp(-lambda*30), access_bonus=0 => small value
+ assert result < 0.15
+
+ def test_decay_disabled_returns_quality(self, monkeypatch) -> None:
+ """When VT_MEMORY_DECAY=0, importance equals quality_score."""
+ monkeypatch.setenv("VT_MEMORY_DECAY", "0")
+ assert compute_importance(0.7, 10, 100.0) == 0.7
+
+ def test_access_bonus_capped_at_0_3(self, monkeypatch) -> None:
+ """Access bonus should not exceed 0.3."""
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ # access_count=100 => bonus = min(0.3, 100*0.1) = 0.3
+ r1 = compute_importance(0.5, 100, 0.0)
+ r2 = compute_importance(0.5, 3, 0.0)
+ # Both should use 0.3 cap: 0.5*(1.0+0.3)=0.65
+ assert r1 == r2 == pytest.approx(0.65)
+
+ def test_importance_capped_at_1_0(self, monkeypatch) -> None:
+ """Output should never exceed 1.0."""
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ result = compute_importance(1.0, 10, 0.0)
+ assert result <= 1.0
+
+ def test_zero_quality_always_zero(self, monkeypatch) -> None:
+ """quality_score=0 should produce importance=0 regardless of access."""
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ assert compute_importance(0.0, 100, 0.0) == 0.0
+
+
+# ---------------------------------------------------------------------------
+# 3. reinforce
+# ---------------------------------------------------------------------------
+
+
+class TestReinforce:
+ def test_reinforce_task_success_increases_score(self, tmp_path: Path, monkeypatch) -> None:
+ """task_success event should increase quality_score by 0.1."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "1")
+ _create_memory_file(tmp_path, "my-mem", quality_score=0.5)
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ assert lc.reinforce("my-mem", "task_success", source="user") is True
+ # Re-read from disk
+ entries = pm.list_entries()
+ assert entries[0].quality_score == pytest.approx(0.6, abs=0.01)
+
+ def test_reinforce_user_reject_decreases_score(self, tmp_path: Path, monkeypatch) -> None:
+ """user_reject event should decrease quality_score by 0.3."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "1")
+ _create_memory_file(tmp_path, "reject-mem", quality_score=0.7)
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ assert lc.reinforce("reject-mem", "user_reject", source="user") is True
+ entries = pm.list_entries()
+ assert entries[0].quality_score == pytest.approx(0.4, abs=0.01)
+
+ def test_reinforce_system_source_discounted(self, tmp_path: Path, monkeypatch) -> None:
+ """source='system' should apply 0.7x discount to delta."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "1")
+ _create_memory_file(tmp_path, "sys-mem", quality_score=0.5)
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ assert lc.reinforce("sys-mem", "task_success", source="system") is True
+ entries = pm.list_entries()
+ # delta = 0.1 * 0.7 = 0.07 => 0.5 + 0.07 = 0.57
+ assert entries[0].quality_score == pytest.approx(0.57, abs=0.01)
+
+ def test_reinforce_clamped_to_bounds(self, tmp_path: Path, monkeypatch) -> None:
+ """Score should never go below 0.0 or above 1.0."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "1")
+ # Test lower bound
+ _create_memory_file(tmp_path, "low-mem", quality_score=0.1, entry_id="lo1234")
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ lc.reinforce("low-mem", "user_reject", source="user") # -0.3
+ entries = pm.list_entries()
+ assert entries[0].quality_score == 0.0
+
+ def test_reinforce_session_cap(self, tmp_path: Path, monkeypatch) -> None:
+ """Per-memory per-session delta should not exceed 0.5."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "1")
+ _create_memory_file(tmp_path, "cap-mem", quality_score=0.5)
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ # Each task_success = +0.1 (user). 5 calls = 0.5 cap reached.
+ for _ in range(5):
+ lc.reinforce("cap-mem", "task_success", source="user")
+ # 6th call should be blocked by session cap
+ assert lc.reinforce("cap-mem", "task_success", source="user") is False
+
+ def test_reinforce_disabled_when_flag_off(self, tmp_path: Path, monkeypatch) -> None:
+ """reinforce() returns False when VT_MEMORY_QUALITY=0."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "0")
+ _create_memory_file(tmp_path, "off-mem")
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ assert lc.reinforce("off-mem", "task_success") is False
+
+ def test_reinforce_nonexistent_memory(self, tmp_path: Path, monkeypatch) -> None:
+ """reinforce() on non-existent memory should return False."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "1")
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ assert lc.reinforce("ghost", "task_success") is False
+
+ def test_reinforce_unknown_event(self, tmp_path: Path, monkeypatch) -> None:
+ """reinforce() with unknown event should return False."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "1")
+ _create_memory_file(tmp_path, "evt-mem")
+ pm = PersistentMemory(memory_dir=tmp_path)
+ lc = MemoryLifecycle(pm)
+ assert lc.reinforce("evt-mem", "unknown_event") is False
+
+
+# ---------------------------------------------------------------------------
+# 4. Feature flags
+# ---------------------------------------------------------------------------
+
+
+class TestFeatureFlags:
+ def test_flags_default_off(self, monkeypatch) -> None:
+ """All flags should default to disabled (0)."""
+ monkeypatch.delenv("VT_MEMORY_QUALITY", raising=False)
+ monkeypatch.delenv("VT_MEMORY_GC", raising=False)
+ monkeypatch.delenv("VT_MEMORY_DECAY", raising=False)
+ assert is_quality_enabled() is False
+ assert is_gc_enabled() is False
+ assert is_decay_enabled() is False
+
+ def test_flags_enabled_when_set(self, monkeypatch) -> None:
+ """Flags should be enabled when env var = '1'."""
+ monkeypatch.setenv("VT_MEMORY_QUALITY", "1")
+ monkeypatch.setenv("VT_MEMORY_GC", "1")
+ monkeypatch.setenv("VT_MEMORY_DECAY", "1")
+ assert is_quality_enabled() is True
+ assert is_gc_enabled() is True
+ assert is_decay_enabled() is True
+
+
+# ---------------------------------------------------------------------------
+# 5. memory_lock
+# ---------------------------------------------------------------------------
+
+
+class TestMemoryLock:
+ def test_lock_acquired_yields_true(self, tmp_path: Path) -> None:
+ """Normal lock acquisition should yield True."""
+ with memory_lock(tmp_path) as acquired:
+ assert acquired is True
+
+ def test_lock_file_created(self, tmp_path: Path) -> None:
+ """Lock file .lock should be created in memory dir."""
+ with memory_lock(tmp_path):
+ assert (tmp_path / ".lock").exists()