import os, json, tempfile _DATA_DIR = os.environ.get("PRECIZ_DATA_DIR", "/tmp") def _data_dir(username=None): d = _DATA_DIR if username: d = os.path.join(d, username) return d def load_memory(): p = os.path.join(_data_dir(), "memory", "memory.json") os.makedirs(os.path.dirname(p), exist_ok=True) if not os.path.exists(p): return {"ttl_days": 7, "model_cache": {}} try: with open(p) as f: return json.load(f) except json.JSONDecodeError: return {"ttl_days": 7, "model_cache": {}} def save_memory(memory): p = os.path.join(_data_dir(), "memory", "memory.json") os.makedirs(os.path.dirname(p), exist_ok=True) fd, tmp = tempfile.mkstemp(dir=os.path.dirname(p), suffix=".json") try: with os.fdopen(fd, "w") as f: json.dump(memory, f, indent=2) os.replace(tmp, p) except Exception: try: os.unlink(tmp) except Exception: pass raise