fix: configure memory singleton from application DATA_DIR
This commit is contained in:
1 parent
870b3ffec4
commit
cc385be9cf
1 file changed
+24
-47
@@ -22,12 +22,7 @@ class MemoryItem:
|
|||||||
|
|
||||||
|
|
||||||
class GlobalMemory:
|
class GlobalMemory:
|
||||||
"""Persistent global memory store shared across all forum topics.
|
"""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.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, storage_path: Path):
|
def __init__(self, storage_path: Path):
|
||||||
self.storage_path = Path(storage_path).expanduser().resolve()
|
self.storage_path = Path(storage_path).expanduser().resolve()
|
||||||
self._items: dict[str, MemoryItem] = {}
|
self._items: dict[str, MemoryItem] = {}
|
||||||
@@ -50,52 +45,34 @@ class GlobalMemory:
|
|||||||
|
|
||||||
def _save(self) -> None:
|
def _save(self) -> None:
|
||||||
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
payload = json.dumps(
|
payload = json.dumps([asdict(item) for item in self._items.values()], ensure_ascii=False, indent=2)
|
||||||
[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)
|
||||||
)
|
|
||||||
fd, tmp_name = tempfile.mkstemp(
|
|
||||||
prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||||
f.write(payload)
|
f.write(payload)
|
||||||
f.flush()
|
f.flush()
|
||||||
os.fsync(f.fileno())
|
os.fsync(f.fileno())
|
||||||
os.replace(tmp_name, self.storage_path)
|
os.replace(tmp_name, self.storage_path)
|
||||||
# Persist the directory entry as well (important on abrupt shutdown).
|
|
||||||
try:
|
try:
|
||||||
dir_fd = os.open(self.storage_path.parent, os.O_DIRECTORY)
|
dir_fd = os.open(self.storage_path.parent, os.O_DIRECTORY)
|
||||||
try:
|
try: os.fsync(dir_fd)
|
||||||
os.fsync(dir_fd)
|
finally: os.close(dir_fd)
|
||||||
finally:
|
except OSError: logger.debug("Directory fsync unavailable for %s", self.storage_path.parent)
|
||||||
os.close(dir_fd)
|
|
||||||
except OSError:
|
|
||||||
logger.debug("Directory fsync is unavailable for %s", self.storage_path.parent)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
try:
|
try: os.unlink(tmp_name)
|
||||||
os.unlink(tmp_name)
|
except OSError: pass
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
||||||
item_id = str(uuid.uuid4())[:8]
|
item = MemoryItem(id=str(uuid.uuid4())[:8], fact=fact.strip(), category=category.strip().lower())
|
||||||
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
|
self._items[item.id] = item
|
||||||
self._items[item_id] = item
|
self._save()
|
||||||
try:
|
logger.info("Added fact [%s] in category '%s': %s", item.id, item.category, item.fact)
|
||||||
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)
|
|
||||||
return item
|
return item
|
||||||
|
|
||||||
def remove_fact(self, fact_id: str) -> bool:
|
def remove_fact(self, fact_id: str) -> bool:
|
||||||
if fact_id not in self._items:
|
if fact_id not in self._items: return False
|
||||||
return False
|
del self._items[fact_id]; self._save(); return True
|
||||||
del self._items[fact_id]
|
|
||||||
self._save()
|
|
||||||
return True
|
|
||||||
|
|
||||||
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
||||||
if category:
|
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()]
|
return [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()]
|
||||||
|
|
||||||
def clear(self) -> None:
|
def clear(self) -> None:
|
||||||
self._items.clear()
|
self._items.clear(); self._save()
|
||||||
self._save()
|
|
||||||
|
|
||||||
def get_memory_summary(self, max_items: int = 30) -> str:
|
def get_memory_summary(self, max_items: int = 30) -> str:
|
||||||
if not self._items:
|
if not self._items: return ""
|
||||||
return ""
|
|
||||||
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
||||||
for item in list(self._items.values())[-max_items:]:
|
for item in list(self._items.values())[-max_items:]:
|
||||||
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
||||||
@@ -121,16 +96,18 @@ class GlobalMemory:
|
|||||||
|
|
||||||
|
|
||||||
_global_memory_instances: dict[Path, 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:
|
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:
|
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()
|
path = Path(storage_path).expanduser().resolve()
|
||||||
if path not in _global_memory_instances:
|
if path not in _global_memory_instances:
|
||||||
_global_memory_instances[path] = GlobalMemory(path)
|
_global_memory_instances[path] = GlobalMemory(path)
|
||||||
|
|||||||
Reference in new issue
Block a user