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
fix(chat): never steer user text into a maintenance turn
smixs8249e2277247
diff --git a/src/d_brain/bot/handlers/chat.py b/src/d_brain/bot/handlers/chat.pyindex cb11a7b..0413e29 100644--- a/src/d_brain/bot/handlers/chat.py+++ b/src/d_brain/bot/handlers/chat.py@@ -102,6 +102,15 @@ async def _dispatch_text(bot: Bot, chat_id: int, user_id: int, text: str) -> Nonawait bot.send_message(chat_id, "⏹ Останавливаю текущий ответ.")returnif mode == "steer":+ if not manager.is_steerable_turn():+ # Maintenance turn (nightly pipeline / doctor / startup) holds+ # the session — injecting user text would contaminate it.+ await bot.send_message(+ chat_id,+ "🔧 Идёт фоновое обслуживание — повтори сообщение через "+ "пару минут, отвечу как освобожусь.",+ )+ returnawait manager.steer(text)await bot.send_message(chat_id, "↪️ Передал в текущую задачу.")returndiff --git a/src/d_brain/services/chat_session.py b/src/d_brain/services/chat_session.pyindex 210d60e..ed847cc 100644--- a/src/d_brain/services/chat_session.py+++ b/src/d_brain/services/chat_session.py@@ -61,6 +61,9 @@ class ChatSessionManager:def is_turn_active(self) -> bool:return self._session.is_turn_active()+ def is_steerable_turn(self) -> bool:+ return self._session.is_steerable_turn()+async def steer(self, text: str) -> None:await asyncio.to_thread(self._session.steer, text)diff --git a/src/d_brain/services/claude_session.py b/src/d_brain/services/claude_session.pyindex 49ab84d..20d542e 100644--- a/src/d_brain/services/claude_session.py+++ b/src/d_brain/services/claude_session.py@@ -48,6 +48,9 @@ Runner = Callable[..., subprocess.CompletedProcess]DEFAULT_TIMEOUT = 1200 # 20 min, matches the old subprocess pipelineDEFAULT_STALL_TIMEOUT = 180 # no new pane bytes for this long ⇒ wedged+# request_id prefix that marks a turn as maintenance (pipeline, doctor,+# /process) — such turns are never steering targets for chat input.+MAINT_PREFIX = "maint-"_PANE_WIDTH = "200"# Height 50 (not taller): the TUI draws its footer (idle ❯ / bypass line)# just below content, so on a tall pane the footer lands mid-screen with a@@ -308,6 +311,23 @@ class ClaudeSession:with self._locked(blocking=False) as got:return not got+ def is_steerable_turn(self) -> bool:+ """True iff the in-flight turn may receive steering input.++ Maintenance turns (nightly pipeline, doctor canary, /process) tag+ themselves with a ``maint-`` request_id — user text steered into+ them would contaminate the background prompt and never get its own+ answer. A held lock WITHOUT an inflight record is startup/recovery/+ control — also not steerable.+ """+ if not self.is_turn_active():+ return False+ try:+ first = self._inflight.read_text().splitlines()[0]+ except (FileNotFoundError, IndexError):+ return False+ return not first.startswith(MAINT_PREFIX)+def send_control(self, text: str) -> None:"""Type a client-side Claude Code command verbatim, fire-and-forget.diff --git a/src/d_brain/services/doctor.py b/src/d_brain/services/doctor.pyindex ff6d292..91565c6 100644--- a/src/d_brain/services/doctor.py+++ b/src/d_brain/services/doctor.py@@ -59,6 +59,7 @@ class Doctor:res = self.session.ask(f"Reply with exactly {self._canary_token} and nothing else.",timeout=CANARY_TIMEOUT,+ request_id="maint-doctor",)if res.status == "logged_out":return CheckResult("canary", False, "Claude разлогинился — нужен вход")diff --git a/src/d_brain/services/processor.py b/src/d_brain/services/processor.pyindex 9059207..381f5dd 100644--- a/src/d_brain/services/processor.py+++ b/src/d_brain/services/processor.py@@ -52,8 +52,13 @@ class ClaudeProcessor:def _ask(self, prompt: str, *, wrap: bool = True) -> dict[str, Any]:if self.session is None:return {"error": "session not configured", "processed_entries": 0}+ # maint- tag: chat steering must never inject user text into a+ # pipeline turn (see ClaudeSession.is_steerable_turn).return self._to_report(- self.session.ask(prompt, timeout=DEFAULT_TIMEOUT, wrap=wrap)+ self.session.ask(+ prompt, timeout=DEFAULT_TIMEOUT, wrap=wrap,+ request_id="maint-process",+ ))# ── content helpers (unchanged) ──────────────────────────────────diff --git a/tests/test_chat_handler.py b/tests/test_chat_handler.pyindex fbec642..4252858 100644--- a/tests/test_chat_handler.py+++ b/tests/test_chat_handler.py@@ -132,6 +132,9 @@ class SteerableManager(FakeManager):def is_turn_active(self) -> bool:return self.active+ def is_steerable_turn(self) -> bool:+ return self.active # a plain chat turn — steerable while active+async def steer(self, text: str) -> None:self.steered.append(text)@@ -316,3 +319,21 @@ def test_album_items_flush_as_single_prompt(monkeypatch):prompt = mgr.sent[0][1]assert "attachments/a.jpg" in prompt and "attachments/b.jpg" in promptassert "подпись" in prompt+++def test_text_during_maintenance_turn_gets_busy_reply(monkeypatch):+ """A message while the nightly pipeline / doctor holds the session must+ NOT be steered into the maintenance turn — the user gets a busy reply."""+ from d_brain.bot.handlers import chat++ class MaintenanceManager(SteerableManager):+ def is_steerable_turn(self) -> bool:+ return False++ mgr = MaintenanceManager(active=True)+ monkeypatch.setattr(chat, "_get_manager", lambda: mgr)+ bot = FakeBot()+ asyncio.run(chat._dispatch_text(bot, chat_id=10, user_id=1, text="пиши короче"))+ assert mgr.steered == [] # nothing injected into the pipeline turn+ assert mgr.sent == [] # and no new turn forced past the lock+ assert bot.messages and "обслуживание" in bot.messages[0][1].lower()diff --git a/tests/test_claude_session.py b/tests/test_claude_session.pyindex 3fd51c0..98c9c07 100644--- a/tests/test_claude_session.py+++ b/tests/test_claude_session.py@@ -434,3 +434,32 @@ def test_pane_log_precreated_owner_only_before_pipe(tmp_path, clock):log = tmp_path / ".dbrain" / "pane.log"assert log.exists()assert (log.stat().st_mode & 0o777) == 0o600+++# ── steering gate: maintenance turns must not swallow user input ────────+++def _hold_pane_lock(s):+ import fcntl++ fh = open(s._pane_lock, "w")+ fcntl.flock(fh, fcntl.LOCK_EX)+ return fh+++def test_is_steerable_turn_distinguishes_chat_from_maintenance(tmp_path, clock):+ s = make_session(tmp_path, FakeTmux([READY]), clock)+ inflight = tmp_path / ".dbrain" / "inflight"++ assert s.is_steerable_turn() is False # idle: nothing to steer++ fh = _hold_pane_lock(s)+ try:+ # lock held but no inflight → startup/recovery/control, not a turn+ assert s.is_steerable_turn() is False+ inflight.write_text("rid12345\n0.0\n")+ assert s.is_steerable_turn() is True # a chat turn+ inflight.write_text("maint-daily\n0.0\n")+ assert s.is_steerable_turn() is False # the nightly pipeline+ finally:+ fh.close()diff --git a/tests/test_doctor.py b/tests/test_doctor.pyindex 879d3ef..9bab73a 100644--- a/tests/test_doctor.py+++ b/tests/test_doctor.py@@ -68,3 +68,20 @@ def test_run_cli_exit_codes_follow_report():bad_sess = FakeSession(AskResult("logged_out"))assert run_cli(bad_sess, checks=[], alert=sent.append) == 1assert len(sent) == 2 # the telegram report goes out either way+++def test_canary_is_tagged_as_maintenance():+ # Chat steering keys off the maint- prefix in the inflight id — the+ # canary must never look like a steerable user turn.+ class RecordingSession(FakeSession):+ def __init__(self, result):+ super().__init__(result)+ self.request_ids = []++ def ask(self, prompt, *, timeout=120, request_id=None):+ self.request_ids.append(request_id)+ return self.result++ sess = RecordingSession(AskResult("ok", reply="DBRAIN_OK"))+ Doctor(sess, checks=[]).run()+ assert sess.request_ids and sess.request_ids[0].startswith("maint-")diff --git a/tests/test_processor.py b/tests/test_processor.pyindex 6a65ae4..3f66b3f 100644--- a/tests/test_processor.py+++ b/tests/test_processor.py@@ -104,3 +104,21 @@ def test_process_daily_prompt_instructs_cards_and_summary(tmp_path):prompt = sess.prompts[0].lower()assert "autograph" in promptassert "саммари" in prompt or "summary" in prompt+++def test_daily_processing_is_tagged_as_maintenance(tmp_path):+ # The nightly pipeline shares the brain session with chat; its turns+ # carry a maint- request_id so user input is never steered into them.+ sess = FakeSession(AskResult("ok", reply='{"status": "ok"}'))+ sess.request_ids = []+ original_ask = sess.ask++ def recording_ask(prompt, **kwargs):+ sess.request_ids.append(kwargs.get("request_id"))+ return original_ask(prompt, **kwargs)++ sess.ask = recording_ask+ day = _daily(tmp_path)+ ClaudeProcessor(tmp_path, session=sess).process_daily(day)+ assert sess.request_ids+ assert all(r and r.startswith("maint-") for r in sess.request_ids)