diff --git a/src/homeagent/memory/global_memory.py b/src/homeagent/memory/global_memory.py index e568c6a..8619f4e 100644 --- a/src/homeagent/memory/global_memory.py +++ b/src/homeagent/memory/global_memory.py @@ -22,12 +22,7 @@ class MemoryItem: class GlobalMemory: - """Persistent global memory store shared across all forum topics. - - Writes are atomic: a complete file is fsynced and then renamed into place, - so a container restart cannot leave a truncated JSON file behind. - """ - + """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] = {} @@ -50,52 +45,34 @@ class GlobalMemory: 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, tmp_name = tempfile.mkstemp( - prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent - ) + payload = json.dumps([asdict(item) for item in self._items.values()], ensure_ascii=False, indent=2) + fd, tmp_name = 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(tmp_name, self.storage_path) - # Persist the directory entry as well (important on abrupt shutdown). try: dir_fd = os.open(self.storage_path.parent, os.O_DIRECTORY) - try: - os.fsync(dir_fd) - finally: - os.close(dir_fd) - except OSError: - logger.debug("Directory fsync is unavailable for %s", self.storage_path.parent) + try: os.fsync(dir_fd) + finally: os.close(dir_fd) + except OSError: logger.debug("Directory fsync unavailable for %s", self.storage_path.parent) except Exception: - try: - os.unlink(tmp_name) - except OSError: - pass + try: os.unlink(tmp_name) + except OSError: pass raise def add_fact(self, fact: str, category: str = "general") -> MemoryItem: - item_id = str(uuid.uuid4())[:8] - item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower()) - self._items[item_id] = item - try: - self._save() - except OSError as e: - logger.error("Failed to persist global memory to %s: %s", self.storage_path, e) - raise - logger.info("Added fact [%s] in category '%s': %s", item_id, item.category, item.fact) + 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 + 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: @@ -108,12 +85,10 @@ class GlobalMemory: 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() + self._items.clear(); self._save() def get_memory_summary(self, max_items: int = 30) -> str: - if not self._items: - return "" + 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}") @@ -121,16 +96,18 @@ class GlobalMemory: _global_memory_instances: dict[Path, GlobalMemory] = {} +_configured_memory_path: Optional[Path] = None + + +def configure_global_memory_path(storage_path: Path) -> None: + """Set the process-wide memory file before agents and handlers are created.""" + global _configured_memory_path + _configured_memory_path = Path(storage_path).expanduser().resolve() def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory: - """Return the memory store for the requested persistent path. - - The cache is keyed by the resolved path, preventing one process/test/config - from accidentally reusing memory loaded from another DATA_DIR. - """ if storage_path is None: - storage_path = Path(os.getenv("DATA_DIR", "data")) / "global_memory.json" + storage_path = _configured_memory_path or (Path(os.getenv("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)