5 changed files with 129 additions and 41 deletions

No files matched your search

+5 -8
View File
@@ -8,17 +8,14 @@ services:
init: true init: true
env_file: env_file:
- .env - .env
environment:
# Application path inside the container; this must match the mount target.
DATA_DIR: /app/data
extra_hosts: extra_hosts:
# Allows reaching host services (e.g. local Ollama, SearXNG, local Gitea) via host.docker.internal
- "host.docker.internal:host-gateway" - "host.docker.internal:host-gateway"
volumes: volumes:
# Persistent data: sessions, global memory, scratchpad notes, tokens # Override DATA_DIR_HOST in .env for a path outside the project directory.
- ./data:/app/data - "${DATA_DIR_HOST:-./data}:/app/data"
# Skills and extensions mounted for customization without rebuilding
- ./skills:/app/skills:ro - ./skills:/app/skills:ro
- ./extensions:/app/extensions:ro - ./extensions:/app/extensions:ro
- ./gcal.json:/app/gcal.json: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
+8
View File
@@ -0,0 +1,8 @@
# ==============================================================================
# 5. Persistent Docker data directory (optional)
# ==============================================================================
# Host directory mounted to /app/data by docker-compose.yml.
# Default is ./data next to docker-compose.yml.
# Use an absolute path if the project directory is ephemeral:
# DATA_DIR_HOST=/srv/homeagent/data
+52
View File
@@ -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.
+40 -33
View File
@@ -2,6 +2,8 @@
import json import json
import logging import logging
import os
import tempfile
import uuid import uuid
from dataclasses import asdict, dataclass, field from dataclasses import asdict, dataclass, field
from datetime import datetime from datetime import datetime
@@ -23,7 +25,7 @@ class GlobalMemory:
"""Persistent global memory store shared across all forum topics.""" """Persistent global memory store shared across all forum topics."""
def __init__(self, storage_path: Path): 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._items: dict[str, MemoryItem] = {}
self._load() self._load()
@@ -31,8 +33,10 @@ class GlobalMemory:
if not self.storage_path.exists(): if not self.storage_path.exists():
return return
try: 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) data = json.load(f)
if not isinstance(data, list):
raise ValueError("memory file must contain a JSON list")
for item_data in data: for item_data in data:
item = MemoryItem(**item_data) item = MemoryItem(**item_data)
self._items[item.id] = item self._items[item.id] = item
@@ -41,70 +45,73 @@ class GlobalMemory:
logger.error("Failed to load global memory from %s: %s", self.storage_path, e) logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
def _save(self) -> None: def _save(self) -> None:
try:
self.storage_path.parent.mkdir(parents=True, exist_ok=True) self.storage_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.storage_path, "w", encoding="utf-8") as f: payload = json.dumps([asdict(item) for item in self._items.values()], ensure_ascii=False, indent=2)
json.dump([asdict(item) for item in self._items.values()], f, ensure_ascii=False, indent=2) fd, temporary_path = tempfile.mkstemp(
except Exception as e: prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent
logger.error("Failed to save global memory to %s: %s", self.storage_path, e) )
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: def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
"""Add a new fact or preference to global memory.""" item = MemoryItem(id=str(uuid.uuid4())[:8], fact=fact.strip(), category=category.strip().lower())
item_id = str(uuid.uuid4())[:8] self._items[item.id] = item
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
self._items[item_id] = item
self._save() 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 return item
def remove_fact(self, fact_id: str) -> bool: def remove_fact(self, fact_id: str) -> bool:
"""Remove a fact by its ID.""" if fact_id not in self._items:
if fact_id in self._items: return False
del self._items[fact_id] del self._items[fact_id]
self._save() self._save()
return True return True
return False
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]: def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
"""List all facts, optionally filtered by category."""
if category: if category:
cat = category.strip().lower() cat = category.strip().lower()
return [item for item in self._items.values() if item.category == cat] return [item for item in self._items.values() if item.category == cat]
return list(self._items.values()) return list(self._items.values())
def search(self, query: str) -> list[MemoryItem]: def search(self, query: str) -> list[MemoryItem]:
"""Search memory for keywords in query."""
q = query.lower() q = query.lower()
return [ return [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()]
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:
"""Clear all stored memory."""
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:
"""Produce a formatted summary of remembered facts for the system prompt."""
if not self._items: if not self._items:
return "" return ""
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"] lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
items = list(self._items.values())[-max_items:] for item in list(self._items.values())[-max_items:]:
for item in items:
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}") lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
return "\n".join(lines) return "\n".join(lines)
# Singleton instance container _global_memory_instances: dict[Path, GlobalMemory] = {}
_global_memory_instance: Optional[GlobalMemory] = None
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory: def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
global _global_memory_instance """Get the memory store keyed by its absolute path.
if _global_memory_instance is None:
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: if storage_path is None:
storage_path = Path("data") / "global_memory.json" storage_path = Path(os.environ.get("DATA_DIR", "data")) / "global_memory.json"
_global_memory_instance = GlobalMemory(storage_path) path = Path(storage_path).expanduser().resolve()
return _global_memory_instance if path not in _global_memory_instances:
_global_memory_instances[path] = GlobalMemory(path)
return _global_memory_instances[path]
+24
View File
@@ -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() == []