Skip to content

An always-on second brain you talk to. Voice notes in Telegram → typed, linked knowledge in your Obsidian vault. Runs 24/7 on the Claude subscription you already have.

feat: add session persistence and automation scripts

smixs599e92c765fe
diff --git a/.claude/settings.local.example.json b/.claude/settings.local.example.json
new file mode 100644
index 0000000..e93b21b
--- /dev/null
+++ b/.claude/settings.local.example.json
@@ -0,0 +1,8 @@
+{
+ "permissions": {
+ "allow": [
+ "Bash(git push origin main)",
+ "Bash(mcp-cli :*)"
+ ]
+ }
+}
diff --git a/README.md b/README.md
index 5f99b89..48fe259 100644
--- a/README.md
+++ b/README.md
@@ -953,6 +953,26 @@ claude auth login
<details>
<summary><strong>Технические детали (для продвинутых)</strong></summary>
+### Автоматизация
+
+Система включает автоматическую обработку записей:
+
+**Ежедневная обработка (21:00):**
+- Скрипт `scripts/process.sh` запускает Claude с dbrain-processor skill
+- Классифицирует записи, создаёт задачи в Todoist
+- Отправляет отчёт в Telegram
+- Коммитит изменения в Git
+
+**Недельный дайджест (воскресенье 20:00):**
+- Скрипт `scripts/weekly.py` генерирует сводку за неделю
+- Анализирует прогресс по целям
+- Отправляет в Telegram
+
+**Session Persistence (JSONL):**
+- Все взаимодействия сохраняются в `vault/sessions/YYYY-MM-DD.jsonl`
+- Append-only формат для надёжности
+- Методы API: `append()`, `get_today()`, `get_recent()`, `get_stats()`
+
### Полезные команды
```bash
diff --git a/deploy/d-brain-process.service b/deploy/d-brain-process.service
index 5ba85d0..6840b33 100644
--- a/deploy/d-brain-process.service
+++ b/deploy/d-brain-process.service
@@ -4,6 +4,6 @@ Description=d-brain Daily Processing
[Service]
Type=oneshot
User=shima
-WorkingDirectory=/home/shima/projects/dbrain
-ExecStart=/home/shima/projects/dbrain/scripts/process.sh
+WorkingDirectory=/home/shima/projects/agent-second-brain
+ExecStart=/home/shima/projects/agent-second-brain/scripts/process.sh
Environment=PYTHONUNBUFFERED=1
diff --git a/deploy/d-brain-weekly.service b/deploy/d-brain-weekly.service
index 83ac99c..d0baf90 100644
--- a/deploy/d-brain-weekly.service
+++ b/deploy/d-brain-weekly.service
@@ -5,8 +5,8 @@ After=network.target
[Service]
Type=oneshot
User=shima
-WorkingDirectory=/home/shima/projects/dbrain
+WorkingDirectory=/home/shima/projects/agent-second-brain
ExecStart=/home/shima/.local/bin/uv run python scripts/weekly.py
-EnvironmentFile=/home/shima/projects/dbrain/.env
+EnvironmentFile=/home/shima/projects/agent-second-brain/.env
StandardOutput=journal
StandardError=journal
diff --git a/scripts/process.sh b/scripts/process.sh
new file mode 100755
index 0000000..089677b
--- /dev/null
+++ b/scripts/process.sh
@@ -0,0 +1,60 @@
+#!/bin/bash
+set -e
+
+# PATH for systemd (claude, uv, npx in ~/.local/bin and node)
+export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin:$PATH"
+export HOME="/home/shima"
+
+# Paths
+PROJECT_DIR="/home/shima/projects/agent-second-brain"
+VAULT_DIR="$PROJECT_DIR/vault"
+ENV_FILE="$PROJECT_DIR/.env"
+
+# Load environment variables
+if [ -f "$ENV_FILE" ]; then
+ export $(grep -v '^#' "$ENV_FILE" | xargs)
+fi
+
+# Check token
+if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
+ echo "ERROR: TELEGRAM_BOT_TOKEN not set"
+ exit 1
+fi
+
+# Date and chat_id
+TODAY=$(date +%Y-%m-%d)
+CHAT_ID="${ALLOWED_USER_IDS//[\[\]]/}" # remove brackets from [123456]
+
+cd "$PROJECT_DIR" # MCP configured for project root
+
+echo "=== d-brain processing for $TODAY ==="
+
+# Run Claude with --dangerously-skip-permissions and MCP
+REPORT=$(claude --print --dangerously-skip-permissions \
+ --mcp-config "$PROJECT_DIR/mcp-config.json" \
+ -p "Today is $TODAY. Execute daily processing according to dbrain-processor skill." \
+ 2>&1) || true
+
+echo "=== Claude output ==="
+echo "$REPORT"
+echo "===================="
+
+# Git commit
+git add -A
+git commit -m "chore: process daily $TODAY" || true
+git push || true
+
+# Send to Telegram
+if [ -n "$REPORT" ] && [ -n "$CHAT_ID" ]; then
+ echo "=== Sending to Telegram ==="
+ curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
+ -d "chat_id=$CHAT_ID" \
+ -d "text=$REPORT" \
+ -d "parse_mode=HTML" || \
+ # Fallback: send without HTML parsing
+ curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
+ -d "chat_id=$CHAT_ID" \
+ -d "text=$REPORT"
+fi
+
+echo "=== Done ==="
diff --git a/scripts/weekly.py b/scripts/weekly.py
new file mode 100644
index 0000000..2b128d3
--- /dev/null
+++ b/scripts/weekly.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+"""Weekly digest script - generates and sends to Telegram."""
+
+import asyncio
+import logging
+import sys
+from pathlib import Path
+
+# Add project root to path
+sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
+
+from aiogram import Bot
+from aiogram.client.default import DefaultBotProperties
+from aiogram.enums import ParseMode
+
+from d_brain.config import get_settings
+from d_brain.services.git import VaultGit
+from d_brain.services.processor import ClaudeProcessor
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
+)
+logger = logging.getLogger(__name__)
+
+
+async def main() -> None:
+ """Generate weekly digest and send to Telegram."""
+ settings = get_settings()
+ processor = ClaudeProcessor(settings.vault_path, settings.todoist_api_key)
+ git = VaultGit(settings.vault_path)
+
+ logger.info("Starting weekly digest generation...")
+
+ result = processor.generate_weekly()
+
+ if "error" in result:
+ report = f"Error: {result['error']}"
+ logger.error("Weekly digest failed: %s", result["error"])
+ else:
+ report = result.get("report", "No output")
+ logger.info("Weekly digest generated successfully")
+ # Commit any changes
+ git.commit_and_push("chore: weekly digest")
+
+ # Send to Telegram
+ bot = Bot(
+ token=settings.telegram_bot_token,
+ default=DefaultBotProperties(parse_mode=ParseMode.HTML),
+ )
+ try:
+ user_id = settings.allowed_user_ids[0] if settings.allowed_user_ids else None
+ if not user_id:
+ logger.error("No allowed user IDs configured")
+ return
+
+ try:
+ await bot.send_message(chat_id=user_id, text=report)
+ except Exception:
+ # Fallback: send without HTML parsing
+ await bot.send_message(chat_id=user_id, text=report, parse_mode=None)
+
+ logger.info("Weekly digest sent to user %s", user_id)
+ finally:
+ await bot.session.close()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/src/d_brain/services/session.py b/src/d_brain/services/session.py
new file mode 100644
index 0000000..d4b79cd
--- /dev/null
+++ b/src/d_brain/services/session.py
@@ -0,0 +1,164 @@
+"""JSONL-based session persistence for storing all interactions."""
+
+import json
+from dataclasses import asdict, dataclass
+from datetime import date, datetime
+from pathlib import Path
+from typing import Any
+
+
+@dataclass
+class SessionEntry:
+ """Single session entry."""
+
+ timestamp: str
+ type: str # voice, text, photo, forward, command
+ content: str
+ metadata: dict[str, Any] | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to dictionary for JSON serialization."""
+ return {k: v for k, v in asdict(self).items() if v is not None}
+
+
+class SessionStorage:
+ """JSONL-based session storage for append-only reliability.
+
+ Stores all interactions in daily JSONL files for later analysis
+ and context retrieval.
+ """
+
+ def __init__(self, vault_path: Path) -> None:
+ self.vault_path = Path(vault_path)
+ self.sessions_path = self.vault_path / "sessions"
+
+ def _ensure_dirs(self) -> None:
+ """Ensure sessions directory exists."""
+ self.sessions_path.mkdir(parents=True, exist_ok=True)
+
+ def _get_session_file(self, day: date) -> Path:
+ """Get path to session file for given date."""
+ self._ensure_dirs()
+ return self.sessions_path / f"{day.isoformat()}.jsonl"
+
+ def append(
+ self,
+ entry_type: str,
+ content: str,
+ timestamp: datetime | None = None,
+ metadata: dict[str, Any] | None = None,
+ ) -> None:
+ """Append entry to session file.
+
+ Args:
+ entry_type: Type of entry (voice, text, photo, forward, command)
+ content: Entry content
+ timestamp: Entry timestamp (defaults to now)
+ metadata: Optional metadata dict
+ """
+ if timestamp is None:
+ timestamp = datetime.now()
+
+ entry = SessionEntry(
+ timestamp=timestamp.isoformat(),
+ type=entry_type,
+ content=content,
+ metadata=metadata,
+ )
+
+ file_path = self._get_session_file(timestamp.date())
+ with file_path.open("a", encoding="utf-8") as f:
+ f.write(json.dumps(entry.to_dict(), ensure_ascii=False) + "\n")
+
+ def get_today(self) -> list[SessionEntry]:
+ """Get all entries for today."""
+ return self.get_day(date.today())
+
+ def get_day(self, day: date) -> list[SessionEntry]:
+ """Get all entries for a specific day."""
+ file_path = self._get_session_file(day)
+ if not file_path.exists():
+ return []
+
+ entries = []
+ with file_path.open("r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ data = json.loads(line)
+ entries.append(
+ SessionEntry(
+ timestamp=data["timestamp"],
+ type=data["type"],
+ content=data["content"],
+ metadata=data.get("metadata"),
+ )
+ )
+ return entries
+
+ def get_recent(self, days: int = 7) -> list[SessionEntry]:
+ """Get entries from the last N days.
+
+ Args:
+ days: Number of days to look back (default 7)
+
+ Returns:
+ List of entries sorted by timestamp (oldest first)
+ """
+ from datetime import timedelta
+
+ entries = []
+ today = date.today()
+
+ for i in range(days):
+ day = today - timedelta(days=i)
+ entries.extend(self.get_day(day))
+
+ # Sort by timestamp (oldest first)
+ entries.sort(key=lambda e: e.timestamp)
+ return entries
+
+ def get_stats(self) -> dict[str, Any]:
+ """Get statistics about stored sessions.
+
+ Returns:
+ Dict with stats: total_entries, by_type, by_day, date_range
+ """
+ stats: dict[str, Any] = {
+ "total_entries": 0,
+ "by_type": {},
+ "by_day": {},
+ "date_range": {"first": None, "last": None},
+ }
+
+ if not self.sessions_path.exists():
+ return stats
+
+ session_files = sorted(self.sessions_path.glob("*.jsonl"))
+ if not session_files:
+ return stats
+
+ # Parse first and last dates from filenames
+ stats["date_range"]["first"] = session_files[0].stem
+ stats["date_range"]["last"] = session_files[-1].stem
+
+ for file_path in session_files:
+ day = file_path.stem
+ day_count = 0
+
+ with file_path.open("r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ data = json.loads(line)
+ entry_type = data.get("type", "unknown")
+
+ stats["total_entries"] += 1
+ day_count += 1
+ stats["by_type"][entry_type] = (
+ stats["by_type"].get(entry_type, 0) + 1
+ )
+
+ stats["by_day"][day] = day_count
+
+ return stats