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.
Python ai-agentsai-automationclaudeclaude-codeebbinghausknowledge-graphllmmemory-systemobsidianpersonal-assistantpkmproductivitypythonsecond-braintelegram-botvoice-assistant
refactor(processor): drive ClaudeSession instead of claude -p
smixsf7300a3e28d0
diff --git a/src/d_brain/services/processor.py b/src/d_brain/services/processor.pyindex 41bd0da..c6cfa77 100644--- a/src/d_brain/services/processor.py+++ b/src/d_brain/services/processor.py@@ -1,65 +1,84 @@-"""Claude processing service."""+"""Claude processing service.++Migrated from spawning `claude --print -p` per call to driving a shared+persistent interactive ClaudeSession (tmux). This keeps usage on the+subscription after the 2026-06-15 Agent SDK billing change. The public+methods and their {report|error} return shape are unchanged so the bot+handlers don't need to change.+"""import logging-import os-import subprocessfrom datetime import datefrom pathlib import Pathfrom typing import Any+from d_brain.services.claude_session import DEFAULT_TIMEOUT, AskResult, ClaudeSessionfrom d_brain.services.session import SessionStorelogger = logging.getLogger(__name__)-DEFAULT_TIMEOUT = 1200 # 20 minutes+# User-facing messages for non-ok session outcomes (Telegram HTML).+_STATUS_MESSAGES = {+ "rate_limited": "⏳ <b>Лимит подписки исчерпан.</b> Вернусь, когда он обновится.",+ "logged_out": (+ "🔑 <b>Сессии нужен повторный вход.</b> Админу: <code>dbrain login</code>."+ ),+ "timeout": "⌛ <b>Превышено время ожидания ответа.</b> Попробуйте ещё раз.",+ "error": "❌ <b>Ошибка сессии.</b> Попробуйте позже.",+}class ClaudeProcessor:- """Service for triggering Claude Code processing."""-- def __init__(self, vault_path: Path, todoist_api_key: str = "") -> None:+ """Builds prompts and runs them through the shared ClaudeSession."""++ def __init__(+ self,+ vault_path: Path,+ todoist_api_key: str = "",+ session: ClaudeSession | None = None,+ ) -> None:self.vault_path = Path(vault_path)self.todoist_api_key = todoist_api_key- self._mcp_config_path = (self.vault_path.parent / "mcp-config.json").resolve()+ self.session = session- def _load_skill_content(self) -> str:- """Load dbrain-processor skill content for inclusion in prompt.+ # ── result mapping ───────────────────────────────────────────────++ def _to_report(self, res: AskResult) -> dict[str, Any]:+ if res.ok:+ return {"report": res.reply or "", "processed_entries": 1}+ logger.error("session returned %s: %s", res.status, res.detail)+ return {+ "error": _STATUS_MESSAGES.get(res.status, res.detail or "session error"),+ "processed_entries": 0,+ }- NOTE: @vault/ references don't work in --print mode,- so we must include skill content directly in the prompt.- """+ def _ask(self, prompt: str) -> dict[str, Any]:+ if self.session is None:+ return {"error": "session not configured", "processed_entries": 0}+ return self._to_report(self.session.ask(prompt, timeout=DEFAULT_TIMEOUT))++ # ── content helpers (unchanged) ──────────────────────────────────++ def _load_skill_content(self) -> str:skill_path = self.vault_path / ".claude/skills/dbrain-processor/SKILL.md"- if skill_path.exists():- return skill_path.read_text()- return ""+ return skill_path.read_text() if skill_path.exists() else ""def _load_todoist_reference(self) -> str:- """Load Todoist reference for inclusion in prompt."""- ref_path = self.vault_path / ".claude/skills/dbrain-processor/references/todoist.md"- if ref_path.exists():- return ref_path.read_text()- return ""+ ref_path = (+ self.vault_path / ".claude/skills/dbrain-processor/references/todoist.md"+ )+ return ref_path.read_text() if ref_path.exists() else ""def _get_session_context(self, user_id: int) -> str:- """Get today's session context for Claude.-- Args:- user_id: Telegram user ID-- Returns:- Recent session entries formatted for inclusion in prompt.- """if user_id == 0:return ""-session = SessionStore(self.vault_path)today_entries = session.get_today(user_id)if not today_entries:return ""-lines = ["=== TODAY'S SESSION ==="]for entry in today_entries[-10:]:- ts = entry.get("ts", "")[11:16] # HH:MM from ISO+ ts = entry.get("ts", "")[11:16]entry_type = entry.get("type", "unknown")text = entry.get("text", "")[:80]if text:@@ -68,180 +87,71 @@ class ClaudeProcessor:return "\n".join(lines)def _html_to_markdown(self, html: str) -> str:- """Convert Telegram HTML to Obsidian Markdown."""import retext = html- # <b>text</b> → **text**text = re.sub(r"<b>(.*?)</b>", r"**\1**", text)- # <i>text</i> → *text*text = re.sub(r"<i>(.*?)</i>", r"*\1*", text)- # <code>text</code> → `text`text = re.sub(r"<code>(.*?)</code>", r"`\1`", text)- # <s>text</s> → ~~text~~text = re.sub(r"<s>(.*?)</s>", r"~~\1~~", text)- # Remove <u> (no Markdown equivalent, just keep text)text = re.sub(r"</?u>", "", text)- # <a href="url">text</a> → [text](url)text = re.sub(r'<a href="([^"]+)">([^<]+)</a>', r"[\2](\1)", text)-return textdef _save_weekly_summary(self, report_html: str, week_date: date) -> Path:- """Save weekly summary to vault/summaries/YYYY-WXX-summary.md."""- # Calculate ISO week numberyear, week, _ = week_date.isocalendar()filename = f"{year}-W{week:02d}-summary.md"summary_path = self.vault_path / "summaries" / filename-- # Convert HTML to Markdown for Obsidiancontent = self._html_to_markdown(report_html)-- # Add frontmatter- frontmatter = f"""----date: {week_date.isoformat()}-type: weekly-summary-week: {year}-W{week:02d}------"""+ frontmatter = (+ f"---\ndate: {week_date.isoformat()}\n"+ f"type: weekly-summary\nweek: {year}-W{week:02d}\n---\n\n"+ )summary_path.write_text(frontmatter + content)logger.info("Weekly summary saved to %s", summary_path)return summary_pathdef _update_weekly_moc(self, summary_path: Path) -> None:- """Add link to new summary in MOC-weekly.md."""moc_path = self.vault_path / "MOC" / "MOC-weekly.md"if moc_path.exists():content = moc_path.read_text()link = f"- [[summaries/{summary_path.name}|{summary_path.stem}]]"- # Insert after "## Previous Weeks" if not already thereif summary_path.stem not in content:content = content.replace(- "## Previous Weeks\n",- f"## Previous Weeks\n\n{link}\n",+ "## Previous Weeks\n", f"## Previous Weeks\n\n{link}\n")moc_path.write_text(content)- logger.info("Updated MOC-weekly.md with link to %s", summary_path.stem)+ logger.info("Updated MOC-weekly.md with %s", summary_path.stem)- def process_daily(self, day: date | None = None) -> dict[str, Any]:- """Process daily file with Claude.+ # ── public operations ────────────────────────────────────────────- Args:- day: Date to process (default: today)-- Returns:- Processing report as dict- """+ def process_daily(self, day: date | None = None) -> dict[str, Any]:if day is None:day = date.today()-daily_file = self.vault_path / "daily" / f"{day.isoformat()}.md"-if not daily_file.exists():logger.warning("No daily file for %s", day)- return {- "error": f"No daily file for {day}",- "processed_entries": 0,- }+ return {"error": f"No daily file for {day}", "processed_entries": 0}- # Load skill content directly (@ references don't work in --print mode)skill_content = self._load_skill_content()-prompt = f"""Сегодня {day}. Выполни ежедневную обработку.=== SKILL INSTRUCTIONS ==={skill_content}=== END SKILL ===-ПЕРВЫМ ДЕЛОМ: вызови mcp__todoist__user-info чтобы убедиться что MCP работает.--CRITICAL MCP RULE:-- ТЫ ИМЕЕШЬ ДОСТУП к mcp__todoist__* tools — ВЫЗЫВАЙ ИХ НАПРЯМУЮ-- НИКОГДА не пиши "MCP недоступен" или "добавь вручную"-- Для задач: вызови mcp__todoist__add-tasks tool-- Если tool вернул ошибку — покажи ТОЧНУЮ ошибку в отчёте-CRITICAL OUTPUT FORMAT:- Return ONLY raw HTML for Telegram (parse_mode=HTML)- NO markdown: no **, no ## , no ```, no tables- Start directly with 📊 <b>Обработка за {day}</b>- Allowed tags: <b>, <i>, <code>, <s>, <u>- If entries already processed, return status report in same HTML format"""-- try:- # Pass TODOIST_API_KEY to Claude subprocess- env = os.environ.copy()- if self.todoist_api_key:- env["TODOIST_API_KEY"] = self.todoist_api_key-- result = subprocess.run(- [- "claude",- "--print",- "--dangerously-skip-permissions",- "--mcp-config",- str(self._mcp_config_path),- "-p",- prompt,- ],- cwd=self.vault_path.parent,- capture_output=True,- text=True,- timeout=DEFAULT_TIMEOUT,- check=False,- env=env,- )-- if result.returncode != 0:- logger.error("Claude processing failed: %s", result.stderr)- return {- "error": result.stderr or "Claude processing failed",- "processed_entries": 0,- }-- # Return human-readable output- output = result.stdout.strip()- return {- "report": output,- "processed_entries": 1, # успешно обработано- }-- except subprocess.TimeoutExpired:- logger.error("Claude processing timed out")- return {- "error": "Processing timed out",- "processed_entries": 0,- }- except FileNotFoundError:- logger.error("Claude CLI not found")- return {- "error": "Claude CLI not installed",- "processed_entries": 0,- }- except Exception as e:- logger.exception("Unexpected error during processing")- return {- "error": str(e),- "processed_entries": 0,- }+ return self._ask(prompt)def execute_prompt(self, user_prompt: str, user_id: int = 0) -> dict[str, Any]:- """Execute arbitrary prompt with Claude.-- Args:- user_prompt: User's natural language request- user_id: Telegram user ID for session context-- Returns:- Execution report as dict- """today = date.today()-- # Load contexttodoist_ref = self._load_todoist_reference()session_context = self._get_session_context(user_id)-prompt = f"""Ты - персональный ассистент d-brain.CONTEXT:@@ -252,13 +162,6 @@ CONTEXT:{todoist_ref}=== END REFERENCE ===-ПЕРВЫМ ДЕЛОМ: вызови mcp__todoist__user-info чтобы убедиться что MCP работает.--CRITICAL MCP RULE:-- ТЫ ИМЕЕШЬ ДОСТУП к mcp__todoist__* tools — ВЫЗЫВАЙ ИХ НАПРЯМУЮ-- НИКОГДА не пиши "MCP недоступен" или "добавь вручную"-- Если tool вернул ошибку — покажи ТОЧНУЮ ошибку в отчёте-USER REQUEST:{user_prompt}@@ -273,70 +176,12 @@ EXECUTION:1. Analyze the request2. Call MCP tools directly (mcp__todoist__*, read/write files)3. Return HTML status report with results"""-- try:- env = os.environ.copy()- if self.todoist_api_key:- env["TODOIST_API_KEY"] = self.todoist_api_key-- result = subprocess.run(- [- "claude",- "--print",- "--dangerously-skip-permissions",- "--mcp-config",- str(self._mcp_config_path),- "-p",- prompt,- ],- cwd=self.vault_path.parent,- capture_output=True,- text=True,- timeout=DEFAULT_TIMEOUT,- check=False,- env=env,- )-- if result.returncode != 0:- logger.error("Claude execution failed: %s", result.stderr)- return {- "error": result.stderr or "Claude execution failed",- "processed_entries": 0,- }-- return {- "report": result.stdout.strip(),- "processed_entries": 1,- }-- except subprocess.TimeoutExpired:- logger.error("Claude execution timed out")- return {"error": "Execution timed out", "processed_entries": 0}- except FileNotFoundError:- logger.error("Claude CLI not found")- return {"error": "Claude CLI not installed", "processed_entries": 0}- except Exception as e:- logger.exception("Unexpected error during execution")- return {"error": str(e), "processed_entries": 0}+ return self._ask(prompt)def generate_weekly(self) -> dict[str, Any]:- """Generate weekly digest with Claude.-- Returns:- Weekly digest report as dict- """today = date.today()-prompt = f"""Сегодня {today}. Сгенерируй недельный дайджест.-ПЕРВЫМ ДЕЛОМ: вызови mcp__todoist__user-info чтобы убедиться что MCP работает.--CRITICAL MCP RULE:-- ТЫ ИМЕЕШЬ ДОСТУП к mcp__todoist__* tools — ВЫЗЫВАЙ ИХ НАПРЯМУЮ-- НИКОГДА не пиши "MCP недоступен" или "добавь вручную"-- Для выполненных задач: вызови mcp__todoist__find-completed-tasks tool-- Если tool вернул ошибку — покажи ТОЧНУЮ ошибку в отчёте-WORKFLOW:1. Собери данные за неделю (daily файлы в vault/daily/, completed tasks через MCP)2. Проанализируй прогресс по целям (goals/3-weekly.md)@@ -349,57 +194,11 @@ CRITICAL OUTPUT FORMAT:- Start with 📅 <b>Недельный дайджест</b>- Allowed tags: <b>, <i>, <code>, <s>, <u>- Be concise - Telegram has 4096 char limit"""-- try:- env = os.environ.copy()- if self.todoist_api_key:- env["TODOIST_API_KEY"] = self.todoist_api_key-- result = subprocess.run(- [- "claude",- "--print",- "--dangerously-skip-permissions",- "--mcp-config",- str(self._mcp_config_path),- "-p",- prompt,- ],- cwd=self.vault_path.parent,- capture_output=True,- text=True,- timeout=DEFAULT_TIMEOUT,- check=False,- env=env,- )-- if result.returncode != 0:- logger.error("Weekly digest failed: %s", result.stderr)- return {- "error": result.stderr or "Weekly digest failed",- "processed_entries": 0,- }-- output = result.stdout.strip()-- # Save to summaries/ and update MOC+ result = self._ask(prompt)+ if "report" in result and result["report"]:try:- summary_path = self._save_weekly_summary(output, today)+ summary_path = self._save_weekly_summary(result["report"], today)self._update_weekly_moc(summary_path)- except Exception as e:+ except Exception as e: # noqa: BLE001logger.warning("Failed to save weekly summary: %s", e)-- return {- "report": output,- "processed_entries": 1,- }-- except subprocess.TimeoutExpired:- logger.error("Weekly digest timed out")- return {"error": "Weekly digest timed out", "processed_entries": 0}- except FileNotFoundError:- logger.error("Claude CLI not found")- return {"error": "Claude CLI not installed", "processed_entries": 0}- except Exception as e:- logger.exception("Unexpected error during weekly digest")- return {"error": str(e), "processed_entries": 0}+ return resultdiff --git a/tests/test_processor.py b/tests/test_processor.pynew file mode 100644index 0000000..8203377--- /dev/null+++ b/tests/test_processor.py@@ -0,0 +1,80 @@+"""Tests for ClaudeProcessor after migration to ClaudeSession.++A FakeSession replaces the real tmux session; we assert the processor builds+a prompt, calls ask(), and maps AskResult into the {report|error} dict the+bot handlers already expect.+"""++from datetime import date++from d_brain.services.claude_session import AskResult+from d_brain.services.processor import ClaudeProcessor+++class FakeSession:+ def __init__(self, result: AskResult) -> None:+ self.result = result+ self.prompts: list[str] = []++ def ask(self, prompt: str, *, timeout: float = 1200, request_id=None) -> AskResult: # noqa: ANN001+ self.prompts.append(prompt)+ return self.result+++def test_execute_prompt_returns_report_on_ok(tmp_path):+ sess = FakeSession(AskResult("ok", reply="<b>done</b>"))+ p = ClaudeProcessor(tmp_path, session=sess)+ r = p.execute_prompt("move overdue tasks", user_id=0)+ assert r["report"] == "<b>done</b>"+ assert r["processed_entries"] == 1+ assert sess.prompts and "move overdue tasks" in sess.prompts[0]+++def test_execute_prompt_maps_rate_limited(tmp_path):+ sess = FakeSession(AskResult("rate_limited"))+ p = ClaudeProcessor(tmp_path, session=sess)+ r = p.execute_prompt("x")+ assert "error" in r and r["processed_entries"] == 0+++def test_execute_prompt_maps_logged_out(tmp_path):+ sess = FakeSession(AskResult("logged_out"))+ p = ClaudeProcessor(tmp_path, session=sess)+ r = p.execute_prompt("x")+ assert "error" in r+++def test_execute_prompt_maps_timeout(tmp_path):+ sess = FakeSession(AskResult("timeout", detail="no reply"))+ p = ClaudeProcessor(tmp_path, session=sess)+ r = p.execute_prompt("x")+ assert "error" in r+++def test_process_daily_missing_file_does_not_call_session(tmp_path):+ sess = FakeSession(AskResult("ok", reply="x"))+ p = ClaudeProcessor(tmp_path, session=sess)+ r = p.process_daily(date(2026, 6, 7))+ assert "error" in r+ assert sess.prompts == [] # never reached the session+++def test_process_daily_ok(tmp_path):+ (tmp_path / "daily").mkdir()+ (tmp_path / "daily" / "2026-06-07.md").write_text(+ "# 2026-06-07\n## 10:00 [text]\nbuy milk\n"+ )+ sess = FakeSession(AskResult("ok", reply="<b>processed</b>"))+ p = ClaudeProcessor(tmp_path, session=sess)+ r = p.process_daily(date(2026, 6, 7))+ assert r["report"] == "<b>processed</b>"+ assert sess.prompts+++def test_generate_weekly_ok(tmp_path):+ (tmp_path / "summaries").mkdir()+ sess = FakeSession(AskResult("ok", reply="<b>weekly</b>"))+ p = ClaudeProcessor(tmp_path, session=sess)+ r = p.generate_weekly()+ assert r["report"] == "<b>weekly</b>"+ assert sess.prompts