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
feat(watchdog): liveness watchdog with state-based hang detection
smixs25c3127275ce
diff --git a/src/d_brain/services/claude_session.py b/src/d_brain/services/claude_session.pyindex dc81172..22b5896 100644--- a/src/d_brain/services/claude_session.py+++ b/src/d_brain/services/claude_session.py@@ -244,6 +244,10 @@ class ClaudeSession:def is_healthy(self) -> bool:return self._session_exists()+ def current_state(self) -> PaneState:+ """Classify the live pane (for the watchdog / doctor)."""+ return classify_state(self._capture())+def force_recover(self) -> bool:"""Watchdog entry point: take the lock non-blocking; if free, kill andrecreate. Returns False if a live ask() currently holds the lock."""diff --git a/src/d_brain/services/watchdog.py b/src/d_brain/services/watchdog.pynew file mode 100644index 0000000..498ce86--- /dev/null+++ b/src/d_brain/services/watchdog.py@@ -0,0 +1,206 @@+"""Liveness watchdog for the persistent Claude session.++Runs as its own systemd --user service in a SEPARATE slice from the session+(so an OOM kill of the brain doesn't take the watchdog with it). Each tick it+decides one of:++- disk_full → alert + STOP (a restart can't fix a full disk)+- recovered_dead → session gone → force_recover + alert+- rate_limited → subscription limit hit → do NOT kill; wait it out+- logged_out → auth lost → alert (needs re-login); do NOT kill+- recovered_hung → wedged → force_recover + alert+- recover_deferred → wedged but a live request holds the lock → retry next tick+- healthy → nothing to do++Hang model: hung == pane state is NOT serviceable (not READY/RATE/LOGGED_OUT)+AND no new bytes have flowed to pane.log for stall_threshold. This catches a+wedged request AND a stuck startup, never kills a long-but-live task (pane.log+keeps growing), and never kills a healthy idle READY session that merely left+an orphan inflight marker (which is cleared on READY). ask() also self-detects+stalls; the watchdog is the second line when the bot process itself died.++Alerts are debounced: a level-triggered fault (disk/logged-out) alerts once+per cooldown, and re-fires after the session returns to a good state.+"""++import logging+import shutil+import time+from collections.abc import Callable+from pathlib import Path+from typing import Any++from d_brain.services.systemd_notify import notify, watchdog_interval+from d_brain.services.tmux_parse import PaneState++logger = logging.getLogger(__name__)++DEFAULT_TICK = 15.0+DEFAULT_STALL_THRESHOLD = 300.0 # 5 min of no pane output ⇒ wedged+DEFAULT_MIN_DISK = 500_000_000 # 500 MB+DEFAULT_ALERT_COOLDOWN = 3600.0 # re-alert a persistent fault at most hourly++_SERVICEABLE = {+ PaneState.READY,+ PaneState.RATE_LIMITED,+ PaneState.LOGGED_OUT,+}+++class Watchdog:+ def __init__(+ self,+ session: Any,+ *,+ runtime_dir: Path,+ disk_free_fn: Callable[[], int] | None = None,+ clock_fn: Callable[[], float] = time.time,+ alert_fn: Callable[[str], None] = lambda _m: None,+ sleep_fn: Callable[[float], None] = time.sleep,+ tick: float = DEFAULT_TICK,+ stall_threshold: float = DEFAULT_STALL_THRESHOLD,+ min_disk_bytes: int = DEFAULT_MIN_DISK,+ alert_cooldown: float = DEFAULT_ALERT_COOLDOWN,+ ) -> None:+ self.session = session+ self.runtime_dir = Path(runtime_dir)+ self._disk_free_fn = disk_free_fn or (+ lambda: shutil.disk_usage(self.runtime_dir).free+ )+ self._clock = clock_fn+ self._alert_fn = alert_fn+ self._sleep = sleep_fn+ self._tick = tick+ self._stall_threshold = stall_threshold+ self._min_disk = min_disk_bytes+ self._alert_cooldown = alert_cooldown+ self._inflight = self.runtime_dir / "inflight"+ self._pane_log = self.runtime_dir / "pane.log"+ self._status = self.runtime_dir / "STATUS.md"+ self._last_alert_key: str | None = None+ self._last_alert_ts = 0.0++ def _mtime_age(self, path: Path) -> float:+ try:+ return max(0.0, self._clock() - path.stat().st_mtime)+ except OSError:+ return float("inf")++ def _is_hung(self, state: PaneState) -> bool:+ # Serviceable states are never hung. Otherwise hung only if no bytes+ # are flowing (a long-but-live task keeps pane.log growing).+ if state in _SERVICEABLE:+ return False+ return self._mtime_age(self._pane_log) >= self._stall_threshold++ def _maybe_alert(self, key: str, msg: str) -> None:+ now = self._clock()+ if (+ self._last_alert_key == key+ and now - self._last_alert_ts < self._alert_cooldown+ ):+ return+ self._alert_fn(msg)+ self._last_alert_key = key+ self._last_alert_ts = now++ def _note_good(self) -> None:+ # Returning to a good state re-arms alerts for the next incident.+ self._last_alert_key = None++ def _write_status(self, state: str) -> None:+ try:+ self._status.write_text(f"state: {state}\nchecked_at: {self._clock()}\n")+ except OSError as exc:+ logger.warning("could not write STATUS.md: %s", exc)++ def _recover(self, reason: str, alert_msg: str) -> str:+ if self.session.force_recover():+ self._maybe_alert(f"recovered_{reason}", alert_msg)+ self._write_status(f"recovered_{reason}")+ return f"recovered_{reason}"+ # A live request holds the lock — don't claim a restart happened.+ self._write_status("recover_deferred")+ return "recover_deferred"++ def check_once(self) -> str:+ """One liveness tick. Returns the decision string."""+ if self._disk_free_fn() < self._min_disk:+ self._maybe_alert(+ "disk_full", "🔴 Диск переполнен — dbrain не работает (dbrain repair)."+ )+ self._write_status("disk_full")+ return "disk_full"++ if not self.session.is_healthy():+ return self._recover("dead", "♻️ Мозг был мёртв — перезапустил.")++ state = self.session.current_state()+ if state == PaneState.RATE_LIMITED:+ self._note_good()+ self._write_status("rate_limited")+ return "rate_limited"+ if state == PaneState.LOGGED_OUT:+ self._maybe_alert(+ "logged_out",+ "🔑 Claude разлогинился — нужен повторный вход (dbrain login).",+ )+ self._write_status("logged_out")+ return "logged_out"++ if self._is_hung(state):+ return self._recover("hung", "♻️ Мозг завис — перезапустил.")++ if state == PaneState.READY:+ self._inflight.unlink(missing_ok=True) # clear any orphan marker+ self._note_good()+ self._write_status("healthy")+ return "healthy"++ def run(self) -> None: # pragma: no cover - long-running loop+ """Main loop: tick, ping systemd watchdog, sleep."""+ notify("READY=1")+ interval = min(self._tick, watchdog_interval(self._tick))+ while True:+ try:+ self.check_once()+ except Exception:+ logger.exception("watchdog tick failed")+ notify("WATCHDOG=1")+ self._sleep(interval)+++def _telegram_alerter(settings) -> Callable[[str], None]: # pragma: no cover+ import httpx++ def send(msg: str) -> None:+ if not settings.admin_chat_id:+ return+ try:+ httpx.post(+ f"https://api.telegram.org/bot{settings.telegram_bot_token}/sendMessage",+ data={"chat_id": settings.admin_chat_id, "text": msg},+ timeout=10,+ )+ except Exception:+ logger.warning("watchdog alert send failed")++ return send+++def main() -> None: # pragma: no cover+ logging.basicConfig(level=logging.INFO)+ from d_brain.config import get_settings+ from d_brain.services.runtime import get_session++ settings = get_settings()+ session = get_session(settings)+ Watchdog(+ session,+ runtime_dir=settings.runtime_dir,+ alert_fn=_telegram_alerter(settings),+ ).run()+++if __name__ == "__main__":+ main()diff --git a/tests/test_watchdog.py b/tests/test_watchdog.pynew file mode 100644index 0000000..73ea6bf--- /dev/null+++ b/tests/test_watchdog.py@@ -0,0 +1,185 @@+"""Tests for the liveness watchdog.++Hang model (after review): a session is hung when its pane state is NOT+serviceable (not READY/RATE_LIMITED/LOGGED_OUT) AND no new bytes have flowed+to pane.log for stall_threshold. This catches a wedged request AND a stuck+startup, never kills a long-but-live task (pane.log keeps growing), and never+kills a healthy idle READY session that merely has an orphan inflight marker.+"""++import os++from d_brain.services.tmux_parse import PaneState+from d_brain.services.watchdog import Watchdog+++class FakeSession:+ def __init__(self, *, healthy=True, state=PaneState.READY, recover_ok=True):+ self._healthy = healthy+ self.state = state+ self._recover_ok = recover_ok+ self.recovered = 0++ def is_healthy(self) -> bool:+ return self._healthy++ def current_state(self) -> PaneState:+ return self.state++ def force_recover(self) -> bool:+ self.recovered += 1+ if self._recover_ok:+ self._healthy = True+ return self._recover_ok+++def make_wd(tmp_path, session, *, disk_free=10_000_000_000, now=1000.0, alerts=None):+ return Watchdog(+ session,+ runtime_dir=tmp_path,+ disk_free_fn=lambda: disk_free,+ clock_fn=lambda: now,+ alert_fn=(alerts.append if alerts is not None else (lambda m: None)),+ min_disk_bytes=500_000_000,+ stall_threshold=300.0,+ alert_cooldown=3600.0,+ )+++def _stale_log(tmp_path, age_from=1000.0, age=400.0):+ p = tmp_path / "pane.log"+ p.write_text("...")+ os.utime(p, (age_from - age, age_from - age))+++def _fresh_log(tmp_path, now=1000.0):+ p = tmp_path / "pane.log"+ p.write_text("...")+ os.utime(p, (now - 1, now - 1))+++# ── basic states ─────────────────────────────────────────────────────────+++def test_healthy_does_nothing(tmp_path):+ sess = FakeSession()+ wd = make_wd(tmp_path, sess)+ assert wd.check_once() == "healthy"+ assert sess.recovered == 0+++def test_dead_session_is_recovered(tmp_path):+ sess = FakeSession(healthy=False)+ alerts = []+ wd = make_wd(tmp_path, sess, alerts=alerts)+ assert wd.check_once() == "recovered_dead"+ assert sess.recovered == 1+ assert alerts+++def test_rate_limited_is_not_killed(tmp_path):+ sess = FakeSession(state=PaneState.RATE_LIMITED)+ wd = make_wd(tmp_path, sess)+ assert wd.check_once() == "rate_limited"+ assert sess.recovered == 0+++def test_logged_out_alerts_without_restart(tmp_path):+ sess = FakeSession(state=PaneState.LOGGED_OUT)+ alerts = []+ wd = make_wd(tmp_path, sess, alerts=alerts)+ assert wd.check_once() == "logged_out"+ assert sess.recovered == 0+ assert alerts+++# ── hang detection (state-based) ──────────────────────────────────────────+++def test_hung_when_nonserviceable_and_log_stale(tmp_path):+ sess = FakeSession(state=PaneState.UNKNOWN)+ _stale_log(tmp_path)+ wd = make_wd(tmp_path, sess)+ assert wd.check_once() == "recovered_hung"+ assert sess.recovered == 1+++def test_stuck_startup_is_recovered(tmp_path):+ sess = FakeSession(state=PaneState.STARTING)+ _stale_log(tmp_path)+ wd = make_wd(tmp_path, sess)+ assert wd.check_once() == "recovered_hung"+++def test_long_live_task_not_killed(tmp_path):+ """Non-serviceable (working) but bytes still flowing → alive, not hung."""+ sess = FakeSession(state=PaneState.UNKNOWN)+ _fresh_log(tmp_path)+ wd = make_wd(tmp_path, sess)+ assert wd.check_once() == "healthy"+ assert sess.recovered == 0+++def test_idle_ready_with_orphan_inflight_not_killed(tmp_path):+ """CRITICAL regression: a healthy idle READY session with a leftover+ orphan inflight + frozen pane.log must NOT be recovered."""+ sess = FakeSession(state=PaneState.READY)+ (tmp_path / "inflight").write_text("orphan\n")+ _stale_log(tmp_path)+ wd = make_wd(tmp_path, sess)+ assert wd.check_once() == "healthy"+ assert sess.recovered == 0+ assert not (tmp_path / "inflight").exists() # orphan cleared+++def test_recover_deferred_when_lock_busy(tmp_path):+ """force_recover returns False (a live request holds the lock) → report+ deferred, do not claim a restart happened."""+ sess = FakeSession(state=PaneState.UNKNOWN, recover_ok=False)+ _stale_log(tmp_path)+ wd = make_wd(tmp_path, sess)+ assert wd.check_once() == "recover_deferred"+++# ── alert debounce ────────────────────────────────────────────────────────+++def test_logged_out_alert_debounced_across_ticks(tmp_path):+ sess = FakeSession(state=PaneState.LOGGED_OUT)+ alerts = []+ wd = make_wd(tmp_path, sess, alerts=alerts)+ wd.check_once()+ wd.check_once()+ wd.check_once()+ assert len(alerts) == 1 # not 3+++def test_alert_refires_after_recovery(tmp_path):+ sess = FakeSession(state=PaneState.LOGGED_OUT)+ alerts = []+ wd = make_wd(tmp_path, sess, alerts=alerts)+ wd.check_once() # alert #1+ sess.state = PaneState.READY+ wd.check_once() # healthy → resets debounce+ sess.state = PaneState.LOGGED_OUT+ wd.check_once() # alert #2+ assert len(alerts) == 2+++# ── disk + status ─────────────────────────────────────────────────────────+++def test_disk_full_alerts_and_does_not_restart(tmp_path):+ sess = FakeSession()+ alerts = []+ wd = make_wd(tmp_path, sess, disk_free=1_000_000, alerts=alerts)+ assert wd.check_once() == "disk_full"+ assert sess.recovered == 0+ assert alerts+++def test_status_file_written(tmp_path):+ sess = FakeSession()+ wd = make_wd(tmp_path, sess)+ wd.check_once()+ assert (tmp_path / "STATUS.md").exists()