Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
840288a17d | ||
|
|
9a4f4612d7 | ||
|
|
f68dddf162 | ||
|
|
aa6680d076 | ||
|
|
b4837d63c4 | ||
|
|
11479c5e94 | ||
|
|
64deeae190 | ||
|
|
276b338b9c | ||
|
|
f432094868 |
No files matched your search
+5
-8
@@ -8,17 +8,14 @@ services:
|
||||
init: true
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
# Application path inside the container; this must match the mount target.
|
||||
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
|
||||
# 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
|
||||
# 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
|
||||
@@ -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
|
||||
|
||||
@@ -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,6 +2,8 @@
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime
|
||||
@@ -23,7 +25,7 @@ class GlobalMemory:
|
||||
"""Persistent global memory store shared across all forum topics."""
|
||||
|
||||
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,8 +33,10 @@ 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)
|
||||
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
|
||||
@@ -41,70 +45,73 @@ class GlobalMemory:
|
||||
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
|
||||
|
||||
def _save(self) -> None:
|
||||
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)
|
||||
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:
|
||||
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
|
||||
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:
|
||||
"""Remove a fact by its ID."""
|
||||
if fact_id in self._items:
|
||||
if fact_id not in self._items:
|
||||
return False
|
||||
del self._items[fact_id]
|
||||
self._save()
|
||||
return True
|
||||
return False
|
||||
|
||||
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()
|
||||
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:
|
||||
"""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
|
||||
_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:
|
||||
"""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("data") / "global_memory.json"
|
||||
_global_memory_instance = GlobalMemory(storage_path)
|
||||
return _global_memory_instance
|
||||
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]
|
||||
@@ -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() == []
|
||||
Reference in new issue
Block a user