Skip to content

"Vibe-Trading: Your Personal Trading Agent"

style(memory): apply black formatting per CONTRIBUTING.md

shadowinlifed92e362cd647
diff --git a/agent/src/memory/lifecycle.py b/agent/src/memory/lifecycle.py
index d40aaf4e0..b884f8913 100644
--- a/agent/src/memory/lifecycle.py
+++ b/agent/src/memory/lifecycle.py
@@ -76,13 +76,15 @@ class MemoryLifecycle:
file-level locking.
"""
- _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,
- })
+ _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
@@ -170,9 +172,7 @@ class MemoryLifecycle:
self._update_frontmatter_field(
entry.path, "access_count", str(entry.access_count + 1)
)
- self._update_frontmatter_field(
- entry.path, "last_accessed", _now_iso()
- )
+ 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)
@@ -251,9 +251,7 @@ class MemoryLifecycle:
)
entry.path.unlink()
except (OSError, IOError) as exc:
- logger.warning(
- "GC action(%s, %s) failed: %s", entry.title, action, exc
- )
+ logger.warning("GC action(%s, %s) failed: %s", entry.title, action, exc)
return
# Rebuild index after removal
@@ -282,9 +280,7 @@ class MemoryLifecycle:
# Frontmatter manipulation
# ------------------------------------------------------------------
- def _update_frontmatter_field(
- self, path: Path, field: str, value: str
- ) -> None:
+ def _update_frontmatter_field(self, path: Path, field: str, value: str) -> None:
"""Update a single frontmatter field in a memory file.
Uses an atomic write-then-rename strategy to prevent file corruption
@@ -296,7 +292,8 @@ class MemoryLifecycle:
if not lines or lines[0].strip() != "---":
logger.warning(
"_update_frontmatter_field(%s): no frontmatter delimiters in %s",
- field, path,
+ field,
+ path,
)
return
end_idx = None
@@ -307,7 +304,8 @@ class MemoryLifecycle:
if end_idx is None:
logger.warning(
"_update_frontmatter_field(%s): no closing delimiter in %s",
- field, path,
+ field,
+ path,
)
return
diff --git a/agent/src/memory/persistent.py b/agent/src/memory/persistent.py
index c5c0a55c4..7532091fc 100644
--- a/agent/src/memory/persistent.py
+++ b/agent/src/memory/persistent.py
@@ -45,6 +45,7 @@ def memory_lock(memory_dir: Path) -> Generator[bool, None, None]:
yield True
return
import fcntl
+
lock_path = memory_dir / ".lock"
lock_path.touch(exist_ok=True)
fd = None
@@ -58,9 +59,7 @@ def memory_lock(memory_dir: Path) -> Generator[bool, None, None]:
return
except (OSError, BlockingIOError):
if _time.monotonic() >= deadline:
- logger.warning(
- "memory_lock: timeout after %.1fs", _LOCK_TIMEOUT_S
- )
+ logger.warning("memory_lock: timeout after %.1fs", _LOCK_TIMEOUT_S)
yield False
return
_time.sleep(0.1)
@@ -123,6 +122,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."""
+
path: Path
title: str
description: str
@@ -235,8 +235,10 @@ class PersistentMemory:
)[: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
+ str(r)
+ for r in (raw_related if isinstance(raw_related, list) else [])
+ if isinstance(r, str)
+ and len(r) == 6
and all(c in "0123456789abcdef" for c in r.lower())
)
@@ -266,23 +268,25 @@ class PersistentMemory:
days_since = max(0.0, (now - last_acc) / 86400.0)
importance = compute_importance(qs, ac, days_since)
- 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=mtime,
- id=entry_id,
- created_at=created,
- updated_at=updated,
- keywords=keywords,
- quality_score=qs,
- access_count=ac,
- last_accessed=last_acc,
- importance=importance,
- related_memories=related,
- ))
+ 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=mtime,
+ id=entry_id,
+ created_at=created,
+ updated_at=updated,
+ keywords=keywords,
+ quality_score=qs,
+ access_count=ac,
+ last_accessed=last_acc,
+ importance=importance,
+ related_memories=related,
+ )
+ )
return entries
def list_entries(self) -> List[MemoryEntry]:
@@ -317,7 +321,9 @@ class PersistentMemory:
self._rebuild_index()
return True
- def find_relevant(self, query: str, max_results: int = MAX_RESULTS) -> List[MemoryEntry]:
+ def find_relevant(
+ self, query: str, max_results: int = MAX_RESULTS
+ ) -> List[MemoryEntry]:
"""Keyword search across all entries, weighted by importance."""
query_tokens = _tokenize(query)
if not query_tokens:
@@ -336,7 +342,7 @@ class PersistentMemory:
if token_score > 0:
final_score = token_score
if _is_decay_enabled():
- final_score *= (0.5 + 0.5 * entry.importance)
+ final_score *= 0.5 + 0.5 * entry.importance
scored.append((final_score, entry))
scored.sort(key=lambda x: (-x[0], -x[1].modified_at))
@@ -364,8 +370,13 @@ class PersistentMemory:
for h in expired:
del self._recent_hashes[h]
- def add(self, name: str, content: str, memory_type: str = "project",
- description: str = "") -> Optional[Path]:
+ def add(
+ self,
+ name: str,
+ content: str,
+ memory_type: str = "project",
+ description: str = "",
+ ) -> Optional[Path]:
"""Save a new memory entry and update the index."""
if _is_quality_enabled() and self.is_duplicate(name, description, content):
logger.debug(
@@ -415,7 +426,9 @@ class PersistentMemory:
)
with memory_lock(self._dir) as acquired:
if not acquired:
- logger.warning("add(%s): lock timeout, best-effort write", stripped_name)
+ logger.warning(
+ "add(%s): lock timeout, best-effort write", stripped_name
+ )
path.write_text(frontmatter, encoding="utf-8")
self._update_index(stripped_name, filename, description or stripped_name)
return path
@@ -456,4 +469,6 @@ class PersistentMemory:
"""Rebuild MEMORY.md from all existing entry files."""
entries = self._scan_entries()
lines = [f"- [{e.title}]({e.path.name}) — {e.description}" for e in entries]
- self._index_path.write_text("\n".join(lines[:MAX_INDEX_LINES]), encoding="utf-8")
+ self._index_path.write_text(
+ "\n".join(lines[:MAX_INDEX_LINES]), encoding="utf-8"
+ )
diff --git a/agent/src/tools/remember_tool.py b/agent/src/tools/remember_tool.py
index 682755b56..851987461 100644
--- a/agent/src/tools/remember_tool.py
+++ b/agent/src/tools/remember_tool.py
@@ -99,15 +99,24 @@ class RememberTool(BaseTool):
title = kwargs.get("title", "")
content = kwargs.get("content", "")
if not title or not content:
- return json.dumps({"status": "error", "error": "title and content required"})
+ return json.dumps(
+ {"status": "error", "error": "title and content required"}
+ )
memory_type = kwargs.get("memory_type", "project")
try:
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)})
+ 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:
query = kwargs.get("query", "")
@@ -122,7 +131,10 @@ class RememberTool(BaseTool):
{"title": e.title, "type": e.memory_type, "content": e.body[:2000]}
for e in entries
]
- return json.dumps({"status": "ok", "count": len(results), "memories": results}, ensure_ascii=False)
+ return json.dumps(
+ {"status": "ok", "count": len(results), "memories": results},
+ ensure_ascii=False,
+ )
def _forget(self, kwargs: dict) -> str:
title = kwargs.get("title", "")
@@ -142,5 +154,9 @@ class RememberTool(BaseTool):
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}"})
+ return json.dumps(
+ {"status": "ok", "message": f"Reinforced: {title} ({event})"}
+ )
+ return json.dumps(
+ {"status": "skipped", "message": f"Reinforce skipped for: {title}"}
+ )