fix: persist runtime memory across Docker restarts #3

Merged
timka123 merged 9 commits from fix/persistence-minimal into master 2026-11-13 23:47:48 +03:00
Showing only changes of commit aa6680d076 - Show all commits
+35 -20
View File
@@ -2,6 +2,8 @@
import json
import logging
import os
import tempfile
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime
@@ -20,10 +22,15 @@ class MemoryItem:
class GlobalMemory:
"""Persistent global memory store shared across all forum topics."""
"""Persistent global memory store shared across all forum topics.
The target file is replaced only after a complete JSON document has been
written and flushed. This prevents a restart during a write from leaving
a truncated ``global_memory.json``.
"""
def __init__(self, storage_path: Path):
self.storage_path = storage_path
self.storage_path = Path(storage_path).expanduser().resolve()
self._items: dict[str, MemoryItem] = {}
self._load()
@@ -31,7 +38,7 @@ class GlobalMemory:
if not self.storage_path.exists():
return
try:
with open(self.storage_path, "r", encoding="utf-8") as f:
with self.storage_path.open("r", encoding="utf-8") as f:
data = json.load(f)
for item_data in data:
item = MemoryItem(**item_data)
@@ -41,15 +48,31 @@ class GlobalMemory:
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
def _save(self) -> None:
try:
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.storage_path, "w", encoding="utf-8") as f:
json.dump([asdict(item) for item in self._items.values()], f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error("Failed to save global memory to %s: %s", self.storage_path, e)
payload = json.dumps(
[asdict(item) for item in self._items.values()],
ensure_ascii=False,
indent=2,
)
fd, temporary_path = tempfile.mkstemp(
prefix=f".{self.storage_path.name}.",
suffix=".tmp",
dir=self.storage_path.parent,
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(payload)
f.flush()
os.fsync(f.fileno())
os.replace(temporary_path, self.storage_path)
except Exception:
try:
os.unlink(temporary_path)
except OSError:
pass
raise
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
"""Add a new fact or preference to global memory."""
item_id = str(uuid.uuid4())[:8]
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
self._items[item_id] = item
@@ -58,22 +81,19 @@ class GlobalMemory:
return item
def remove_fact(self, fact_id: str) -> bool:
"""Remove a fact by its ID."""
if fact_id in self._items:
if fact_id not in self._items:
return False
del self._items[fact_id]
self._save()
return True
return False
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
"""List all facts, optionally filtered by category."""
if category:
cat = category.strip().lower()
return [item for item in self._items.values() if item.category == cat]
return list(self._items.values())
def search(self, query: str) -> list[MemoryItem]:
"""Search memory for keywords in query."""
q = query.lower()
return [
item for item in self._items.values()
@@ -81,23 +101,18 @@ class GlobalMemory:
]
def clear(self) -> None:
"""Clear all stored memory."""
self._items.clear()
self._save()
def get_memory_summary(self, max_items: int = 30) -> str:
"""Produce a formatted summary of remembered facts for the system prompt."""
if not self._items:
return ""
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
items = list(self._items.values())[-max_items:]
for item in items:
for item in list(self._items.values())[-max_items:]:
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
return "\n".join(lines)
# Singleton instance container
_global_memory_instance: Optional[GlobalMemory] = None