From f43209486846c05b46c139caf00527c17e85a05f Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:13:52 +0300 Subject: [PATCH 1/9] fix: persist Docker runtime state on host --- docker-compose.yml | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 4fc7797..61699ca 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,17 +8,13 @@ services: init: true env_file: - .env + environment: + # All runtime state must live on the bind-mounted host directory. + DATA_DIR: /app/data extra_hosts: - # Allows reaching host services (e.g. local Ollama, SearXNG, local Gitea) via host.docker.internal - "host.docker.internal:host-gateway" volumes: - # Persistent data: sessions, global memory, scratchpad notes, tokens - ./data:/app/data - # Skills and extensions mounted for customization without rebuilding - ./skills:/app/skills:ro - ./extensions:/app/extensions:ro - ./gcal.json:/app/gcal.json:ro - # Uncomment to mount credentials files if placed in project root: - # - ./service_account.json:/app/service_account.json:ro - # - ./credentials.json:/app/credentials.json:ro - # - ./gcal.json:/app/gcal.json:ro -- 2.34.1 From 276b338b9c0080702fdefc6e71aeb9f214b390a4 Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:14:13 +0300 Subject: [PATCH 2/9] docs: add safe persistence migration and verification steps --- docs/DATA_PERSISTENCE.md | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 docs/DATA_PERSISTENCE.md diff --git a/docs/DATA_PERSISTENCE.md b/docs/DATA_PERSISTENCE.md new file mode 100644 index 0000000..8e8cdcd --- /dev/null +++ b/docs/DATA_PERSISTENCE.md @@ -0,0 +1,52 @@ +# Durable Docker state + +The bot stores runtime state in `/app/data`: + +- `global_memory.json` — global facts and preferences; +- `sessions/` — conversation history; +- `calendar_token.json` — Google OAuth token, if enabled. + +`docker-compose.yml` mounts the host directory `${DATA_DIR_HOST:-./data}` to `/app/data` and sets `DATA_DIR=/app/data` inside the container. + +## First deployment / migration + +Back up the existing state before recreating the container: + +```bash +mkdir -p data +cp -a data "data.backup.$(date +%Y%m%d-%H%M%S)" + +# If the old container has the only copy, copy it BEFORE removing it: +docker cp homeagent:/app/data/. ./data/ + +docker compose config +docker compose up -d --build +``` + +If the old state was written into the container layer at another path, find it first: + +```bash +docker exec homeagent sh -lc 'find /app /root -maxdepth 4 -type f \( -name global_memory.json -o -path "*/sessions/*.json" \) -print' +``` + +## Verify after restart + +```bash +docker compose exec homeagent sh -lc '\ +printf "DATA_DIR=%s\\n" "$DATA_DIR"; \ +mount | grep /app/data; \ +ls -la /app/data; \ +find /app/data/sessions -type f 2>/dev/null | head' +``` + +Then restart and verify the same files remain: + +```bash +docker compose restart homeagent +``` + +## Important + +- Do not run `docker compose down -v` before backing up `data/`. +- Check `df -h .` and `docker system df`: a previous `No space left on device` error can prevent writes. +- This change cannot recover data that was already deleted; it only prevents future loss once deployed. -- 2.34.1 From 64deeae19096dad26d514900bb80f042bdaaebbc Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:14:27 +0300 Subject: [PATCH 3/9] fix: allow explicit host path for persistent data --- docker-compose.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 61699ca..a0b42ce 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,12 +9,13 @@ services: env_file: - .env environment: - # All runtime state must live on the bind-mounted host directory. + # Application path inside the container; this must match the mount target. DATA_DIR: /app/data extra_hosts: - "host.docker.internal:host-gateway" volumes: - - ./data:/app/data + # Override DATA_DIR_HOST in .env for a path outside the project directory. + - "${DATA_DIR_HOST:-./data}:/app/data" - ./skills:/app/skills:ro - ./extensions:/app/extensions:ro - ./gcal.json:/app/gcal.json:ro -- 2.34.1 From 11479c5e943bc750c57ec71d3f0475e6c11f1221 Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:14:38 +0300 Subject: [PATCH 4/9] docs: document configurable host persistence directory --- docs/DATA_PERSISTENCE.env.example | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 docs/DATA_PERSISTENCE.env.example diff --git a/docs/DATA_PERSISTENCE.env.example b/docs/DATA_PERSISTENCE.env.example new file mode 100644 index 0000000..cd11f43 --- /dev/null +++ b/docs/DATA_PERSISTENCE.env.example @@ -0,0 +1,7 @@ +# ============================================================================== +# Persistent Docker data directory (host path) +# ============================================================================== +# Compose mounts this path to /app/data inside the container. +# Default: ./data relative to the directory containing docker-compose.yml +# DATA_DIR_HOST=/srv/homeagent/data + -- 2.34.1 From b4837d63c4543c1f8e68a020bde7f8da3a425127 Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:16:09 +0300 Subject: [PATCH 5/9] docs: expose optional host data directory setting --- docs/DATA_PERSISTENCE.env.example | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/DATA_PERSISTENCE.env.example b/docs/DATA_PERSISTENCE.env.example index cd11f43..946c5a7 100644 --- a/docs/DATA_PERSISTENCE.env.example +++ b/docs/DATA_PERSISTENCE.env.example @@ -1,7 +1,8 @@ # ============================================================================== -# Persistent Docker data directory (host path) +# 5. Persistent Docker data directory (optional) # ============================================================================== -# Compose mounts this path to /app/data inside the container. -# Default: ./data relative to the directory containing docker-compose.yml +# Host directory mounted to /app/data by docker-compose.yml. +# Default is ./data next to docker-compose.yml. +# Set an absolute path if the project directory is ephemeral: # DATA_DIR_HOST=/srv/homeagent/data -- 2.34.1 From aa6680d076f7dc2e4a8c2749ffd278a85cf714c3 Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:17:55 +0300 Subject: [PATCH 6/9] fix: atomically persist global memory file --- src/homeagent/memory/global_memory.py | 67 ++++++++++++++++----------- 1 file changed, 41 insertions(+), 26 deletions(-) diff --git a/src/homeagent/memory/global_memory.py b/src/homeagent/memory/global_memory.py index 3f32ff6..4e97d29 100644 --- a/src/homeagent/memory/global_memory.py +++ b/src/homeagent/memory/global_memory.py @@ -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,25 +38,41 @@ 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) - self._items[item.id] = item + 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: - 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) + 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: - del self._items[fact_id] - self._save() - return True - return False + 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]: - """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 -- 2.34.1 From f68dddf162f047ad35c5b6d005a53862e764b292 Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:18:30 +0300 Subject: [PATCH 7/9] fix: honor DATA_DIR when locating global memory --- src/homeagent/memory/global_memory.py | 50 +++++++++++---------------- 1 file changed, 21 insertions(+), 29 deletions(-) diff --git a/src/homeagent/memory/global_memory.py b/src/homeagent/memory/global_memory.py index 4e97d29..c57f836 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. - - 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``. - """ + """Persistent global memory store shared across all forum topics.""" def __init__(self, storage_path: Path): self.storage_path = Path(storage_path).expanduser().resolve() @@ -40,6 +35,8 @@ class GlobalMemory: 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 @@ -49,15 +46,9 @@ 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, - ) + 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, + prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent ) try: with os.fdopen(fd, "w", encoding="utf-8") as f: @@ -73,11 +64,10 @@ class GlobalMemory: 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 + 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) + 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: @@ -95,10 +85,7 @@ class GlobalMemory: 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() - ] + 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() @@ -113,13 +100,18 @@ class GlobalMemory: return "\n".join(lines) -_global_memory_instance: Optional[GlobalMemory] = None +_global_memory_instances: dict[Path, GlobalMemory] = {} def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory: - global _global_memory_instance - if _global_memory_instance is None: - if storage_path is None: - storage_path = Path("data") / "global_memory.json" - _global_memory_instance = GlobalMemory(storage_path) - return _global_memory_instance + """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] -- 2.34.1 From 9a4f4612d7db95c6efd2b02c8228380b523c099e Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:18:46 +0300 Subject: [PATCH 8/9] test: cover memory persistence and path isolation --- tests/test_persistent_memory.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 tests/test_persistent_memory.py diff --git a/tests/test_persistent_memory.py b/tests/test_persistent_memory.py new file mode 100644 index 0000000..0826997 --- /dev/null +++ b/tests/test_persistent_memory.py @@ -0,0 +1,24 @@ +"""Regression tests for durable global memory.""" + +from homeagent.memory.global_memory import GlobalMemory, get_global_memory + + +def test_memory_survives_new_instance(tmp_path): + path = tmp_path / "data" / "global_memory.json" + memory = GlobalMemory(path) + item = memory.add_fact("сохранить после рестарта", category="reliability") + + restarted = GlobalMemory(path) + assert restarted.search("рестарта")[0].id == item.id + assert not list(path.parent.glob("*.tmp")) + + +def test_memory_uses_distinct_paths(tmp_path): + first_path = tmp_path / "one" / "global_memory.json" + second_path = tmp_path / "two" / "global_memory.json" + first = get_global_memory(first_path) + second = get_global_memory(second_path) + + assert first is not second + first.add_fact("только в первом") + assert second.list_facts() == [] -- 2.34.1 From 840288a17d07b2fe2a5a9ef46648f1f1deb4bc00 Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:19:01 +0300 Subject: [PATCH 9/9] docs: add DATA_DIR_HOST to environment template --- docs/DATA_PERSISTENCE.env.example | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/DATA_PERSISTENCE.env.example b/docs/DATA_PERSISTENCE.env.example index 946c5a7..fdc2751 100644 --- a/docs/DATA_PERSISTENCE.env.example +++ b/docs/DATA_PERSISTENCE.env.example @@ -3,6 +3,6 @@ # ============================================================================== # Host directory mounted to /app/data by docker-compose.yml. # Default is ./data next to docker-compose.yml. -# Set an absolute path if the project directory is ephemeral: +# Use an absolute path if the project directory is ephemeral: # DATA_DIR_HOST=/srv/homeagent/data -- 2.34.1