"""Global shared memory across all topics and chats.""" import json import logging import os import tempfile import uuid from dataclasses import asdict, dataclass, field from datetime import datetime from pathlib import Path from typing import Optional logger = logging.getLogger(__name__) @dataclass class MemoryItem: id: str fact: str category: str = "general" created_at: str = field(default_factory=lambda: datetime.now().isoformat()) class GlobalMemory: """Persistent global memory store shared across all forum topics.""" def __init__(self, storage_path: Path): self.storage_path = Path(storage_path).expanduser().resolve() self._items: dict[str, MemoryItem] = {} self._load() def _load(self) -> None: if not self.storage_path.exists(): return try: with self.storage_path.open("r", encoding="utf-8") as f: data = json.load(f) if not isinstance(data, list): raise ValueError("memory file must contain a JSON list") for item_data in data: item = MemoryItem(**item_data) self._items[item.id] = item logger.info("Loaded %d items into global memory from %s", len(self._items), self.storage_path) except Exception as e: logger.error("Failed to load global memory from %s: %s", self.storage_path, e) def _save(self) -> None: self.storage_path.parent.mkdir(parents=True, exist_ok=True) 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: item = MemoryItem(id=str(uuid.uuid4())[:8], fact=fact.strip(), category=category.strip().lower()) self._items[item.id] = item self._save() logger.info("Added fact [%s] in category '%s': %s", item.id, item.category, item.fact) return item def remove_fact(self, fact_id: str) -> bool: if fact_id not in self._items: return False del self._items[fact_id] self._save() return True def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]: 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]: q = query.lower() return [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()] def clear(self) -> None: self._items.clear() self._save() def get_memory_summary(self, max_items: int = 30) -> str: if not self._items: return "" lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"] for item in list(self._items.values())[-max_items:]: lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}") return "\n".join(lines) _global_memory_instances: dict[Path, GlobalMemory] = {} def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory: """Get the memory store keyed by its absolute path. DATA_DIR is used in Docker and keeps this store aligned with the mounted application directory even when the process working directory changes. """ if storage_path is None: storage_path = Path(os.environ.get("DATA_DIR", "data")) / "global_memory.json" path = Path(storage_path).expanduser().resolve() if path not in _global_memory_instances: _global_memory_instances[path] = GlobalMemory(path) return _global_memory_instances[path]