The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): handoff is broken on multi-profile installs (wrong DB, wrong key, wrong bot)
69k4xmdfm2-blipfc5fdb8c2ac4
diff --git a/gateway/run.py b/gateway/run.pyindex 1634a8e858f..581162a05b8 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2212,6 +2212,76 @@ def _multiplex_profile_homes(config: object) -> list[tuple[str, "Path"]]:)+def _handoff_watch_scopes(runner: object) -> list:+ """``(profile_name, home)`` pairs whose ``state.db`` the watcher must poll.++ ``/handoff`` writes ``handoff_state='pending'`` into the store of the+ profile the CLI ran under (``hermes -p medicina``), but the watcher+ resolves ``_session_db`` from whatever HERMES_HOME is active on its task.+ Unscoped, that is always the ROOT store, so a pending handoff queued by+ any secondary profile is never seen and the CLI times out with the+ gateway plainly alive.++ ``(None, None)`` means "poll unscoped" (the root/default store — the+ legacy single-profile path, always first so its behaviour is unchanged).+ A multiplexed gateway additionally yields each SECONDARY profile's+ ``(name, home)`` to be polled inside ``_profile_runtime_scope``. The+ default profile is deliberately not repeated: its home resolves to the+ very same ``state.db`` as the unscoped poll, and polling it twice per+ tick is pure waste.++ Module-level and defensive on purpose: the watcher's tests bind+ ``_handoff_watcher`` onto a ``SimpleNamespace`` with no ``config``, and a+ raising scope resolver would be swallowed by the loop's exception handler+ and silently disable the watcher. Any failure degrades to the root poll.+ """+ scopes: list = [(None, None)]+ try:+ config = getattr(runner, "config", None)+ if config is not None and getattr(config, "multiplex_profiles", False):+ for name, home in _multiplex_profile_homes(config):+ if home is None or not name or name == "default":+ continue+ scopes.append((name, home))+ except Exception:+ logger.debug("Could not resolve multiplex homes for handoff watcher", exc_info=True)+ return scopes+++async def _reclaim_stale(runner: object) -> None:+ """Fail handoffs left in ``running`` by a gateway that died mid-dispatch.++ Runs once per store at watcher startup. ``running`` is only ever set by+ the watcher for the duration of one in-process dispatch, so a row still+ in that state belongs to a previous process. It can never reach a+ terminal state on its own, and ``request_handoff`` refuses a NEW request+ while the row sits there — the session would be permanently unable to+ hand off again, with nothing surfaced to the user.++ Defensive throughout: the watcher's unit tests bind it onto stand-ins+ with no such method, and a raising reclaim would abort watcher startup.+ """+ session_db = getattr(runner, "_session_db", None)+ if session_db is None:+ return+ reclaim = getattr(session_db, "reclaim_stale_running_handoffs", None)+ if not callable(reclaim):+ return+ try:+ ids = await reclaim(+ "gateway stopped mid-handoff; state reclaimed at startup. "+ "Re-run /handoff to try again."+ )+ except Exception:+ logger.debug("Stale-handoff reclaim raised", exc_info=True)+ return+ if ids:+ logger.warning(+ "Reclaimed %d handoff(s) stranded in 'running' by a previous "+ "gateway: %s", len(ids), ", ".join(str(i) for i in ids),+ )++@_contextmanagerdef _profile_runtime_scope(profile_home: "Path"):"""Scope config/skills/memory AND credentials to a profile for one turn.@@ -13901,7 +13971,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewtask.add_done_callback(_done)return task- async def _handoff_watcher(self, interval: float = 2.0) -> None:+ async def _handoff_watcher(+ self, interval: float = 2.0, drain_timeout: float = 30.0,+ ) -> None:"""Background task that processes pending CLI→gateway session handoffs.Polls ``state.db`` for sessions in ``handoff_state='pending'`` and,@@ -13923,36 +13995,154 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# Initial delay so the gateway is fully connected to its platforms# before we try to dispatch handoffs through them.await asyncio.sleep(5)- while self._running:++ # Does this runner's _process_handoff accept the profile argument?+ # The real one does; test stand-ins bind a one-parameter callable.+ # Probed once, outside the loop.+ try:+ import inspect as _inspect+ _process_takes_profile = len(+ _inspect.signature(self._process_handoff).parameters+ ) >= 2+ except Exception:+ _process_takes_profile = False++ # In-flight dispatches, keyed by session id. A handoff runs a FULL+ # agent turn plus delivery, which can take far longer than the CLI's+ # 60s wait. Processing them inline would make one slow handoff block+ # every other profile's poll — a legitimate handoff could then time+ # out purely because another profile was ahead of it in the queue.+ # Dispatch is therefore fire-and-forget; the poll loop only claims.+ inflight: Dict[str, "asyncio.Task"] = {}++ async def _dispatch(row, session_id, session_db, profile_name) -> None:+ """Run one claimed handoff to a terminal state, off the poll path."""try:- if self._session_db is None:- await asyncio.sleep(interval)- continue- pending = await self._session_db.list_pending_handoffs()- for row in pending:- session_id = row.get("id")- if not session_id:- continue- if not await self._session_db.claim_handoff(session_id):- # Another tick or another gateway already claimed it.- continue- try:- await self._process_handoff(row)- await self._session_db.complete_handoff(session_id)- except Exception as exc:- logger.warning(- "Handoff for session %s failed: %s",- session_id, exc, exc_info=True,- )- await self._session_db.fail_handoff(session_id, str(exc))+ if _process_takes_profile:+ await self._process_handoff(row, profile_name)+ else:+ await self._process_handoff(row)+ await session_db.complete_handoff(session_id)except asyncio.CancelledError:+ # Gateway shutting down: leave the row 'running' so the next+ # start's reclaim marks it failed with a clear reason.raiseexcept Exception as exc:- logger.debug("Handoff watcher tick error: %s", exc, exc_info=True)- await asyncio.sleep(interval)+ logger.warning(+ "Handoff for session %s failed: %s",+ session_id, exc, exc_info=True,+ )+ try:+ await session_db.fail_handoff(session_id, str(exc))+ except Exception:+ logger.debug("Could not record handoff failure", exc_info=True)+ finally:+ inflight.pop(session_id, None)++ async def _tick(profile_name: Optional[str] = None) -> None:+ """One poll of the CURRENTLY-SCOPED session store.++ Deliberately a closure over ``self`` rather than a method: the+ watcher's unit tests bind ``_handoff_watcher`` onto a minimal+ ``SimpleNamespace`` stand-in that exposes only ``_session_db``,+ ``_running`` and ``_process_handoff``. Any ``self.<new method>``+ call here would raise AttributeError on that stand-in, get+ swallowed by the loop's ``except Exception``, and silently turn+ the whole watcher into a no-op — which is exactly what the+ mutation-survivable assertions caught. Touch only attributes the+ stand-in already provides.++ ``profile_name`` is threaded to ``_process_handoff`` so delivery+ uses that profile's OWN adapter/home channel; see the docstring+ there. ``None`` means the root/default profile.+ """+ session_db = getattr(self, "_session_db", None)+ if session_db is None:+ return+ pending = await session_db.list_pending_handoffs()+ for row in pending:+ session_id = row.get("id")+ if not session_id or session_id in inflight:+ continue+ if not await session_db.claim_handoff(session_id):+ # Another tick or another gateway already claimed it.+ continue+ # Positional, not keyword: the watcher's existing unit tests+ # bind a stand-in ``_process_handoff(row)`` with no second+ # parameter, and a keyword call would TypeError into the+ # failure branch — turning a passing suite into a silent+ # no-op watcher. Arity is probed above.+ inflight[session_id] = asyncio.ensure_future(+ _dispatch(row, session_id, session_db, profile_name)+ )++ # A row still in 'running' at startup belongs to a gateway that died+ # mid-dispatch. It can never reach a terminal state on its own, and+ # request_handoff refuses new requests while it sits there — so the+ # session would be permanently unable to hand off again. Reclaim once,+ # per store, before the first poll.+ for _pname, _phome in _handoff_watch_scopes(self):+ try:+ if _phome is None:+ await _reclaim_stale(self)+ else:+ with _profile_runtime_scope(_phome):+ await _reclaim_stale(self)+ except Exception:+ logger.debug("Stale-handoff reclaim failed", exc_info=True)++ try:+ while self._running:+ try:+ for profile_name, profile_home in _handoff_watch_scopes(self):+ if profile_home is None:+ await _tick(profile_name)+ else:+ with _profile_runtime_scope(profile_home):+ await _tick(profile_name)+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ logger.debug("Handoff watcher tick error: %s", exc, exc_info=True)+ await asyncio.sleep(interval)+ finally:+ # Drain in-flight dispatches before returning. Cancelling them+ # outright would strand their rows in 'running'; giving them a+ # bounded grace period lets an almost-done handoff record its own+ # terminal state. Whatever is still running after that is+ # cancelled and reclaimed at the next startup.+ pending_tasks = [t for t in inflight.values() if not t.done()]+ if pending_tasks:+ try:+ await asyncio.wait(pending_tasks, timeout=drain_timeout)+ except Exception:+ logger.debug("Handoff drain raised", exc_info=True)+ for task in pending_tasks:+ if not task.done():+ task.cancel()- async def _process_handoff(self, row: Dict[str, Any]) -> None:- """Execute one handoff row. Raises on failure (caller marks failed)."""+ async def _process_handoff(+ self, row: Dict[str, Any], profile_name: Optional[str] = None,+ ) -> None:+ """Execute one handoff row. Raises on failure (caller marks failed).++ ``profile_name`` is the profile whose store queued this handoff+ (``None`` = root/default). On a multiplexed gateway it is load-bearing+ for THREE things that otherwise silently resolve to the primary+ profile and deliver through the wrong bot:++ - ``self.adapters`` only ever holds the DEFAULT profile's adapters;+ secondary profiles live in ``self._profile_adapters[name]``.+ - ``self.config`` is the primary's config, so ``get_home_channel()``+ returns the primary's chat — a medicina handoff would be delivered+ by the default bot, to the default's home channel.+ - the session key must be namespaced ``agent:<profile>:...`` to match+ the key that profile's own adapter uses for organic inbound+ messages; otherwise the handoff binds a key nobody reads.++ Passing the name explicitly beats re-deriving it from the active+ contextvar: the caller already knows which store the row came from.+ """from gateway.config import Platformfrom gateway.session import SessionSource, build_session_keyfrom gateway.platforms.base import MessageEvent@@ -13968,13 +14158,40 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewexcept (ValueError, KeyError):raise RuntimeError(f"unknown platform '{platform_name}'")+ # Resolve the config + adapter map for the profile that queued this+ # handoff. On a single-profile gateway (or a default-profile handoff)+ # both fall back to self.config/self.adapters, so behaviour is+ # byte-identical to before. On a multiplexed gateway a secondary+ # profile MUST use its own map — self.adapters holds only the primary's+ # adapters, and self.config only the primary's home channel.+ handoff_config = self.config+ handoff_adapters = self.adapters+ if profile_name and profile_name != "default":+ secondary = (self._profile_adapters or {}).get(profile_name)+ if not secondary:+ raise RuntimeError(+ f"profile '{profile_name}' has no live adapters in this gateway"+ )+ handoff_adapters = secondary+ # The watcher already entered _profile_runtime_scope for this+ # profile, so a fresh load resolves that profile's config.yaml+ # and .env (home channel, tokens) rather than the primary's.+ try:+ handoff_config = load_gateway_config()+ except Exception:+ logger.warning(+ "Handoff: could not load config for profile %s; "+ "falling back to the primary's config",+ profile_name, exc_info=True,+ )+# Adapter must be live. A relay-fronted gateway registers ONE adapter# under Platform.RELAY that fronts N logical platforms — so a literal# adapters.get(discord) misses even though "discord" is deliverable.# resolve_delivery_transport is the shared alias-aware resolver (native# adapter wins; relay eligible only when its authenticated transport# advertises it fronts the logical platform).- transport = resolve_delivery_transport(platform, self.config, self.adapters)+ transport = resolve_delivery_transport(platform, handoff_config, handoff_adapters)if not transport:raise RuntimeError(f"platform '{platform_name}' is not active in this gateway"@@ -13982,7 +14199,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewadapter = transport.adapter# Home channel must be configured- home = self.config.get_home_channel(platform)+ home = handoff_config.get_home_channel(platform)if not home or not home.chat_id:raise RuntimeError(f"no home channel configured for {platform_name}; "@@ -14066,6 +14283,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewuser_id=dest_user_id,user_name="Handoff",thread_id=effective_thread_id,+ profile=profile_name,)# Compute the gateway's session_key for that destination using the@@ -14073,12 +14291,40 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# entry. For thread destinations build_session_key keys without# user_id (thread_sessions_per_user defaults to False) — so the# next real user message in the thread shares this same session.- platform_cfg = self.config.platforms.get(platform)+ platform_cfg = handoff_config.platforms.get(platform)extra = platform_cfg.extra if platform_cfg else {}+ # Namespace the key to the profile that queued this handoff. Without+ # it, a multiplexed gateway builds ``agent:main:...`` here while the+ # profile's own adapter routes real inbound messages on+ # ``agent:<profile>:...`` — the handoff would bind a key nobody reads.+ #+ # ``profile_name`` comes straight from the watcher, which knows which+ # store the row was claimed from; prefer it over re-deriving from the+ # ambient contextvar. The resolver stays as the fallback for the+ # root/default case (and returns None when multiplexing is off, which+ # reproduces the previous key byte-for-byte).+ #+ # The isinstance check is load-bearing, not defensive noise: a+ # duck-typed/Mock session store returns a truthy MagicMock from the+ # resolver, which would be interpolated straight into the key as+ # ``agent:<MagicMock ...>:``. Same pitfall guarded in+ # ``BasePlatformAdapter._session_key_profile``.+ handoff_profile = profile_name if (profile_name and profile_name != "default") else None+ if handoff_profile is None:+ try:+ store = getattr(self.async_session_store, "_store", self.async_session_store)+ resolver = getattr(store, "_resolve_profile_for_key", None)+ if callable(resolver):+ resolved = resolver(dest_source)+ if isinstance(resolved, str) and resolved.strip():+ handoff_profile = resolved+ except Exception:+ logger.debug("Handoff: could not resolve profile namespace", exc_info=True)session_key = build_session_key(dest_source,group_sessions_per_user=extra.get("group_sessions_per_user", True),thread_sessions_per_user=extra.get("thread_sessions_per_user", False),+ profile=handoff_profile,)# Make sure there's an entry in the session_store for this key. Ifdiff --git a/hermes_state.py b/hermes_state.pyindex 8fed65b943a..7c20af3dbd6 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -15213,6 +15213,42 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin))self._execute_write(_do)+ def reclaim_stale_running_handoffs(self, error: str) -> List[str]:+ """Fail every handoff stuck in ``running``. Returns the ids reclaimed.++ Only the gateway's watcher ever sets ``running``, and it does so for+ the duration of a single in-process dispatch. So any row still in+ ``running`` when a watcher starts up belongs to a PREVIOUS gateway+ that died mid-dispatch (crash, kill, machine reboot).++ Such a row is unrecoverable *and* poisonous: ``request_handoff`` only+ accepts a new request when the state is NULL/``completed``/``failed``,+ so a stranded ``running`` row makes that session permanently unable to+ hand off again — with no error surfaced anywhere.++ Failing (rather than re-queueing as ``pending``) is deliberate: the+ dead gateway may have already switched the session key and dispatched+ the synthetic turn before dying, so a blind retry risks double+ delivery. The user's CLI has long since timed out; the right outcome+ is a clean terminal state they can retry from explicitly.+ """+ def _do(conn):+ cur = conn.execute(+ "SELECT id FROM sessions WHERE handoff_state = 'running'"+ )+ ids = [r[0] for r in cur.fetchall()]+ if ids:+ conn.execute(+ "UPDATE sessions SET handoff_state = 'failed', "+ "handoff_error = ? WHERE handoff_state = 'running'",+ (error[:500],),+ )+ return ids+ try:+ return self._execute_write(_do) or []+ except Exception:+ return []+class AsyncSessionDB:"""Async door onto SessionDB: offloads each call via asyncio.to_thread so a blocking SQLite call never freezes the event loop. Generic forwarder — the audit confirms no method returns a live cursor/generator."""diff --git a/tests/gateway/test_handoff_secondary_profile_adapter.py b/tests/gateway/test_handoff_secondary_profile_adapter.pynew file mode 100644index 00000000000..e637b293c1e--- /dev/null+++ b/tests/gateway/test_handoff_secondary_profile_adapter.py@@ -0,0 +1,188 @@+"""A secondary profile's handoff must deliver through ITS OWN adapter/config.++Regression guard for the third `/handoff` multi-profile bug. Even after the+watcher polls the right ``state.db`` and the session key carries the profile+namespace, ``_process_handoff`` still resolved delivery from ``self.adapters``+and ``self.config`` — which on a multiplexed gateway hold ONLY the primary+profile's adapters and home channel. A medicina handoff was therefore sent by+the default profile's bot, to the default profile's chat, while persisting a+``agent:medicina:...`` key and reporting ``handoff_state='completed'``: a+false positive that looks fine in the database and is wrong on the wire.++This was caught by an adversarial review reading gateway.log, not by the+end-to-end test — the log line showed ``hermes_plugins.telegram_platform``+(primary) instead of the secondary's ``..._home_<hash>`` adapter module.+"""++from datetime import datetime+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.config import GatewayConfig, HomeChannel, Platform, PlatformConfig+from gateway.run import GatewayRunner+from gateway.session import SessionEntry+++def _adapter(tag):+ """A platform adapter stand-in that records which one was used."""+ a = MagicMock()+ a.tag = tag+ a.send = AsyncMock(return_value=SimpleNamespace(success=True))+ a.create_handoff_thread = AsyncMock(return_value=None)+ a._bot = None+ return a+++def _config(chat_id):+ cfg = GatewayConfig(+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="***")}+ )+ cfg.platforms[Platform.TELEGRAM].home_channel = HomeChannel(+ platform=Platform.TELEGRAM, chat_id=chat_id, name=f"home-{chat_id}",+ )+ return cfg+++def _make_multiplex_runner():+ runner = object.__new__(GatewayRunner)+ runner.config = _config("1111") # primary/default home+ runner.config.multiplex_profiles = True+ runner.adapters = {Platform.TELEGRAM: _adapter("primary")}+ runner._profile_adapters = {+ "medicina": {Platform.TELEGRAM: _adapter("medicina")},+ }+ runner._voice_mode = {}+ runner.hooks = SimpleNamespace(+ emit=AsyncMock(), emit_collect=AsyncMock(return_value=[]), loaded_hooks=False,+ )++ captured = {}++ store = MagicMock()+ store.get_or_create_session = AsyncMock(return_value=SessionEntry(+ session_key="k", session_id="s",+ created_at=datetime.now(), updated_at=datetime.now(),+ platform=Platform.TELEGRAM, chat_type="dm",+ ))++ async def _switch(key, sid):+ captured["session_key"] = key+ return SessionEntry(+ session_key=key, session_id=sid,+ created_at=datetime.now(), updated_at=datetime.now(),+ platform=Platform.TELEGRAM, chat_type="dm",+ )++ store.switch_session = AsyncMock(side_effect=_switch)+ # ``async_session_store`` is a derived property with no setter: it rebuilds+ # the facade whenever ``facade._store is not self.session_store``. Wiring+ # the mock as that ``_store`` is what makes the primed cache survive.+ runner.session_store = store+ runner._async_session_store = SimpleNamespace(+ _store=store,+ get_or_create_session=store.get_or_create_session,+ switch_session=store.switch_session,+ )+ runner._evict_cached_agent = MagicMock()+ runner._release_running_agent_state = MagicMock()+ runner._session_db = None++ async def _handle_message(event):+ captured["source"] = event.source+ return "ok"++ runner._handle_message = AsyncMock(side_effect=_handle_message)+ return runner, captured+++def _spy_transport_factory(used):+ """Build a resolve_delivery_transport stand-in that records what it got.++ The real transport exposes ``.adapter`` AND an awaitable ``.send``; the+ handoff uses both, so the stand-in must too.+ """+ def _spy(platform, config, adapters):+ adapter = adapters[platform]+ used["adapter_tag"] = adapter.tag+ used["home_chat_id"] = config.get_home_channel(platform).chat_id++ async def _send(_platform, _chat_id, _text, _metadata=None):+ used["sent_via"] = adapter.tag+ return SimpleNamespace(success=True)++ return SimpleNamespace(adapter=adapter, send=_send)++ return _spy+++async def test_secondary_profile_handoff_uses_its_own_adapter(monkeypatch):+ """medicina's handoff must NOT be delivered by the primary's adapter."""+ runner, captured = _make_multiplex_runner()++ used = {}+ monkeypatch.setattr(+ "gateway.run.resolve_delivery_transport", _spy_transport_factory(used),+ )+ # The watcher would already be inside _profile_runtime_scope here, so a+ # fresh load resolves the secondary's config.+ monkeypatch.setattr("gateway.run.load_gateway_config", lambda: _config("2222"))++ await runner._process_handoff(+ {"id": "cli-session", "title": "work", "handoff_platform": "telegram"},+ profile_name="medicina",+ )++ assert used["adapter_tag"] == "medicina", (+ "delivery must use the secondary profile's own adapter, not the primary's"+ )+ assert used["sent_via"] == "medicina", "the message went out on the wrong bot"+ assert used["home_chat_id"] == "2222", (+ "delivery must use the secondary profile's own home channel"+ )+ assert captured["session_key"].startswith("agent:medicina:"), (+ f"session key must carry the profile namespace, got {captured['session_key']}"+ )+ assert captured["source"].profile == "medicina"+++async def test_default_profile_handoff_keeps_primary_adapter(monkeypatch):+ """The default/root path must behave exactly as before the fix."""+ runner, captured = _make_multiplex_runner()++ used = {}+ monkeypatch.setattr(+ "gateway.run.resolve_delivery_transport", _spy_transport_factory(used),+ )++ await runner._process_handoff(+ {"id": "cli-session", "title": "work", "handoff_platform": "telegram"},+ profile_name=None,+ )++ assert used["adapter_tag"] == "primary"+ assert used["home_chat_id"] == "1111"+++async def test_secondary_profile_without_live_adapters_fails_loudly(monkeypatch):+ """Never silently fall back to the primary's bot — that ships to the wrong chat.++ Raising marks the row ``failed`` and the CLI reports it; delivering through+ another profile's bot would look like success.+ """+ runner, _ = _make_multiplex_runner()+ runner._profile_adapters = {}++ monkeypatch.setattr(+ "gateway.run.resolve_delivery_transport", _spy_transport_factory({}),+ )++ with pytest.raises(RuntimeError, match="no live adapters"):+ await runner._process_handoff(+ {"id": "cli-session", "title": "work", "handoff_platform": "telegram"},+ profile_name="medicina",+ )diff --git a/tests/gateway/test_handoff_watcher_multiprofile.py b/tests/gateway/test_handoff_watcher_multiprofile.pynew file mode 100644index 00000000000..08bcf95710e--- /dev/null+++ b/tests/gateway/test_handoff_watcher_multiprofile.py@@ -0,0 +1,251 @@+"""Handoff watcher must poll EVERY served profile's store, not just the root.++Regression guard for the multi-profile ``/handoff`` bug: ``/handoff`` writes+``handoff_state='pending'`` into the store of the profile the CLI ran under+(``hermes -p medicina``), while the gateway's watcher resolves ``_session_db``+from whatever HERMES_HOME is active on its task. Unscoped that is always the+ROOT store, so the pending row was never seen and the CLI timed out with the+gateway plainly alive and connected.++These tests pin the two halves of the fix:+ 1. the scope list includes the root (``None``) plus every multiplexed home,+ and degrades to ``[None]`` for a single-profile gateway;+ 2. the watcher actually enters ``_profile_runtime_scope`` for each non-root+ home, which is what re-points ``_session_db`` at that profile's store.+"""++import asyncio+import types+from pathlib import Path++import pytest++from gateway import run+++class _FakeConfig:+ def __init__(self, multiplex, allowlist=None):+ self.multiplex_profiles = multiplex+ self.multiplex_profile_allowlist = allowlist+++def test_scopes_single_profile_gateway_is_root_only():+ """No multiplexing → exactly the legacy unscoped poll."""+ runner = types.SimpleNamespace(config=_FakeConfig(multiplex=False))+ assert run._handoff_watch_scopes(runner) == [(None, None)]+++def test_scopes_include_root_first_then_every_secondary_home(monkeypatch):+ """Multiplexed → root first, then each SECONDARY profile as (name, home).++ The default profile must NOT be yielded again: its home resolves to the+ same ``state.db`` as the unscoped root poll, so repeating it would double+ every tick's query count for zero benefit.+ """+ homes = [+ ("default", Path("/h")),+ ("bala", Path("/h/profiles/bala")),+ ("medicina", Path("/h/profiles/medicina")),+ ]+ monkeypatch.setattr(run, "_multiplex_profile_homes", lambda _cfg: homes)++ runner = types.SimpleNamespace(config=_FakeConfig(multiplex=True))+ scopes = run._handoff_watch_scopes(runner)++ assert scopes[0] == (None, None), "root store must still be polled first"+ assert scopes[1:] == [+ ("bala", Path("/h/profiles/bala")),+ ("medicina", Path("/h/profiles/medicina")),+ ]+ assert not any(name == "default" for name, _h in scopes[1:]), (+ "default profile must not be polled twice per tick"+ )+++def test_scopes_degrade_to_root_when_resolution_raises(monkeypatch):+ """A broken profile resolver must not disable the watcher entirely."""+ def _boom(_cfg):+ raise RuntimeError("profiles dir unreadable")++ monkeypatch.setattr(run, "_multiplex_profile_homes", _boom)+ runner = types.SimpleNamespace(config=_FakeConfig(multiplex=True))+ assert run._handoff_watch_scopes(runner) == [(None, None)]+++def test_scopes_tolerate_runner_without_config():+ """The watcher's own unit tests bind onto a config-less stand-in."""+ assert run._handoff_watch_scopes(types.SimpleNamespace()) == [(None, None)]+++class _RecordingDB:+ """Minimal AsyncSessionDB-shaped stub; records nothing pending."""++ def __init__(self, tag=None):+ self.polls = 0+ self.tag = tag++ async def list_pending_handoffs(self):+ self.polls += 1+ return []+++async def test_watcher_enters_profile_scope_for_each_home(monkeypatch):+ """Each non-root home is polled INSIDE ``_profile_runtime_scope``.++ Entering that scope is the whole point of the fix — it is what redirects+ ``_session_db`` to the profile's own ``state.db``. Asserting on the scope+ entries (not just the poll count) keeps the test mutation-survivable:+ dropping the ``with`` still polls N times but records no scopes.+ """+ scopes = [+ (None, None),+ ("bala", Path("/h/profiles/bala")),+ ("medicina", Path("/h/profiles/medicina")),+ ]+ monkeypatch.setattr(run, "_handoff_watch_scopes", lambda _r: scopes)++ entered = []++ class _SpyScope:+ def __init__(self, home):+ self.home = home++ def __enter__(self):+ entered.append(self.home)+ return self++ def __exit__(self, *exc):+ return False++ monkeypatch.setattr(run, "_profile_runtime_scope", _SpyScope)++ async def _no_sleep(_seconds):+ return None++ monkeypatch.setattr(run.asyncio, "sleep", _no_sleep)++ db = _RecordingDB()+ states = iter([True, False])++ class _Running:+ def __bool__(_self):+ try:+ return next(states)+ except StopIteration:+ return False++ fake = types.SimpleNamespace()+ fake._session_db = db+ fake._running = _Running()++ async def _process_handoff(row, profile_name=None):+ return None++ fake._process_handoff = _process_handoff++ coro = run.GatewayRunner._handoff_watcher(fake, interval=0.0)+ await asyncio.wait_for(coro, timeout=5)++ secondary_homes = [h for _n, h in scopes[1:]]+ # Each secondary home is entered TWICE per watcher run: once by the+ # startup stale-handoff reclaim, once by the poll tick. Both must be+ # scoped — a reclaim outside the scope would clear the ROOT store's rows+ # while reporting the profile's.+ assert entered == secondary_homes * 2, (+ "each secondary home must be scoped for BOTH the startup reclaim "+ f"and the poll tick; got {entered}"+ )+ assert db.polls == 3, "root + both profiles polled once each per tick"+++async def test_each_scope_resolves_its_own_store_and_profile(monkeypatch):+ """The whole point: a DIFFERENT ``state.db`` per scope, and the profile+ name reaches ``_process_handoff`` so delivery uses that profile's adapter.++ The earlier test proves the ``with`` runs; it cannot prove the store was+ re-resolved, because it pins one fake db for every scope. Here+ ``_session_db`` is a property whose value depends on the active scope, and+ each store yields a pending row tagged with its profile — so a regression+ that polls the root three times, or that drops ``profile_name``, fails.+ """+ scopes = [+ (None, None),+ ("bala", Path("/h/profiles/bala")),+ ("medicina", Path("/h/profiles/medicina")),+ ]+ monkeypatch.setattr(run, "_handoff_watch_scopes", lambda _r: scopes)++ active = {"home": None}++ class _SpyScope:+ def __init__(self, home):+ self.home = home++ def __enter__(self):+ active["home"] = self.home+ return self++ def __exit__(self, *exc):+ active["home"] = None+ return False++ monkeypatch.setattr(run, "_profile_runtime_scope", _SpyScope)++ async def _no_sleep(_seconds):+ return None++ monkeypatch.setattr(run.asyncio, "sleep", _no_sleep)++ class _ScopedDB:+ """Yields a row whose id identifies the store it came from."""++ def __init__(self, tag):+ self.tag = tag++ async def list_pending_handoffs(self):+ return [{"id": f"row-from-{self.tag}"}]++ async def claim_handoff(self, _sid):+ return True++ async def complete_handoff(self, _sid):+ return None++ async def fail_handoff(self, _sid, _err):+ return None++ stores = {+ None: _ScopedDB("root"),+ Path("/h/profiles/bala"): _ScopedDB("bala"),+ Path("/h/profiles/medicina"): _ScopedDB("medicina"),+ }++ processed = []+ states = iter([True, False])++ class _Fake:+ @property+ def _running(self):+ try:+ return next(states)+ except StopIteration:+ return False++ @property+ def _session_db(self):+ # Mirrors the real property: resolves from the ACTIVE scope.+ return stores[active["home"]]++ async def _process_handoff(self, row, profile_name=None):+ processed.append((row["id"], profile_name))++ coro = run.GatewayRunner._handoff_watcher(_Fake(), interval=0.0)+ await asyncio.wait_for(coro, timeout=5)++ assert processed == [+ ("row-from-root", None),+ ("row-from-bala", "bala"),+ ("row-from-medicina", "medicina"),+ ], "each scope must resolve its own store AND pass its profile name through"diff --git a/tests/gateway/test_handoff_watcher_resilience.py b/tests/gateway/test_handoff_watcher_resilience.pynew file mode 100644index 00000000000..cfe672b784c--- /dev/null+++ b/tests/gateway/test_handoff_watcher_resilience.py@@ -0,0 +1,337 @@+"""Handoff watcher resilience: no head-of-line blocking, no stranded rows.++Two failure modes raised by adversarial review of the multi-profile handoff+work, both fixed here and pinned by these tests.++1. HEAD-OF-LINE BLOCKING. ``_process_handoff`` runs a full agent turn plus+ platform delivery. Awaiting it inline meant one slow handoff in profile A+ stopped the watcher from even POLLING B, C and D. Since the CLI gives up+ after 60s, a perfectly good handoff could time out purely because another+ profile's was ahead of it. Dispatch is now fire-and-forget.++2. STRANDED ``running`` ROWS. Only the watcher sets ``running``, for the span+ of one in-process dispatch. A gateway that dies mid-dispatch leaves the row+ there forever — and ``request_handoff`` refuses a NEW request unless the+ state is NULL/completed/failed, so that session can never hand off again,+ silently. Startup now reclaims those rows to ``failed``.+"""++import asyncio+import types+from pathlib import Path++import pytest++from gateway import run+++def _running_flag(ticks):+ """A ``_running`` stand-in that is True for ``ticks`` reads, then False."""+ states = iter([True] * ticks + [False])++ class _Running:+ def __bool__(_self):+ try:+ return next(states)+ except StopIteration:+ return False++ return _Running()+++class _SlowDB:+ """One pending row; ``_process_handoff`` for it never finishes on its own."""++ def __init__(self):+ self.polls = 0+ self.claimed = []++ async def list_pending_handoffs(self):+ self.polls += 1+ return [{"id": "slow-row"}]++ async def claim_handoff(self, sid):+ # Real claim is atomic pending→running: it succeeds exactly once.+ if sid in self.claimed:+ return False+ self.claimed.append(sid)+ return True++ async def complete_handoff(self, sid):+ return None++ async def fail_handoff(self, sid, err):+ return None+++async def test_slow_handoff_does_not_block_later_polls(monkeypatch):+ """A handoff that never returns must not stop the poll loop.++ Mutation-survivable by construction: ``_process_handoff`` blocks on an+ Event that is only set AFTER the watcher has been given room to keep+ polling. Restoring the inline ``await self._process_handoff`` deadlocks+ tick 1 — the watcher never reaches tick 2, ``release`` is never set, and+ ``wait_for`` raises TimeoutError.++ Note the sleep stub must yield control (``asyncio.sleep(0)``); a stub that+ returns immediately without yielding lets an inline dispatch monopolise+ the loop and masks the bug.+ """+ monkeypatch.setattr(run, "_handoff_watch_scopes", lambda _r: [(None, None)])++ # Capture the real sleep BEFORE patching: the stub runs as+ # ``run.asyncio.sleep``, which is the same module object the test imports,+ # so calling ``asyncio.sleep`` inside it would recurse into itself.+ _real_sleep = asyncio.sleep++ async def _yield_sleep(_seconds):+ await _real_sleep(0)++ monkeypatch.setattr(run.asyncio, "sleep", _yield_sleep)++ db = _SlowDB()+ started = asyncio.Event()+ release = asyncio.Event()++ async def _process_handoff(row, profile_name=None):+ started.set()+ await release.wait()++ fake = types.SimpleNamespace()+ fake._session_db = db+ fake._running = _running_flag(3)+ fake._process_handoff = _process_handoff++ async def _watch():+ await run.GatewayRunner._handoff_watcher(fake, interval=0.0, drain_timeout=0.01)++ task = asyncio.ensure_future(_watch())+ await asyncio.wait_for(started.wait(), timeout=5)++ # Give the loop real turns to poll while the handoff is stuck.+ for _ in range(20):+ await _real_sleep(0)++ polls_while_stuck = db.polls+ release.set()+ # The watcher may already have exited its loop and be draining; either way+ # it must finish once the stuck handoff is released.+ try:+ await asyncio.wait_for(task, timeout=5)+ except asyncio.TimeoutError:+ task.cancel()+ raise AssertionError("watcher did not finish after the handoff was released")++ assert polls_while_stuck >= 2, (+ "poll loop must keep polling while a handoff is in flight; "+ f"polls={polls_while_stuck}"+ )+++async def test_inflight_row_is_not_claimed_twice(monkeypatch):+ """A row already dispatched must be skipped by later ticks."""+ monkeypatch.setattr(run, "_handoff_watch_scopes", lambda _r: [(None, None)])++ async def _no_sleep(_seconds):+ return None++ monkeypatch.setattr(run.asyncio, "sleep", _no_sleep)++ db = _SlowDB()+ calls = []++ async def _process_handoff(row, profile_name=None):+ calls.append(row["id"])+ await asyncio.sleep(3600)++ fake = types.SimpleNamespace()+ fake._session_db = db+ fake._running = _running_flag(4)+ fake._process_handoff = _process_handoff++ coro = run.GatewayRunner._handoff_watcher(fake, interval=0.0, drain_timeout=0.01)+ await asyncio.wait_for(coro, timeout=5)++ assert calls == ["slow-row"], f"dispatched more than once: {calls}"+++class _ReclaimDB:+ """Records the reclaim call and reports nothing pending."""++ def __init__(self, stale_ids=("dead-row",)):+ self.stale_ids = list(stale_ids)+ self.reclaim_calls = []++ async def reclaim_stale_running_handoffs(self, error):+ self.reclaim_calls.append(error)+ return self.stale_ids++ async def list_pending_handoffs(self):+ return []+++async def test_startup_reclaims_rows_stranded_in_running(monkeypatch):+ """Rows left 'running' by a dead gateway are failed at startup.++ Without this, ``request_handoff`` keeps rejecting new requests for that+ session forever and nothing tells the user why.+ """+ monkeypatch.setattr(run, "_handoff_watch_scopes", lambda _r: [(None, None)])++ async def _no_sleep(_seconds):+ return None++ monkeypatch.setattr(run.asyncio, "sleep", _no_sleep)++ db = _ReclaimDB()+ fake = types.SimpleNamespace()+ fake._session_db = db+ fake._running = _running_flag(1)++ async def _process_handoff(row, profile_name=None):+ return None++ fake._process_handoff = _process_handoff++ coro = run.GatewayRunner._handoff_watcher(fake, interval=0.0, drain_timeout=0.01)+ await asyncio.wait_for(coro, timeout=5)++ assert len(db.reclaim_calls) == 1, "reclaim must run exactly once per store"+ assert "/handoff" in db.reclaim_calls[0], (+ "the recorded error should tell the user how to retry"+ )+++async def test_reclaim_runs_per_profile_store(monkeypatch):+ """Every served profile's store gets reclaimed, not just the root's."""+ scopes = [+ (None, None),+ ("bala", Path("/h/profiles/bala")),+ ("medicina", Path("/h/profiles/medicina")),+ ]+ monkeypatch.setattr(run, "_handoff_watch_scopes", lambda _r: scopes)++ class _Scope:+ def __init__(self, home):+ self.home = home++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ monkeypatch.setattr(run, "_profile_runtime_scope", _Scope)++ async def _no_sleep(_seconds):+ return None++ monkeypatch.setattr(run.asyncio, "sleep", _no_sleep)++ db = _ReclaimDB(stale_ids=[])+ fake = types.SimpleNamespace()+ fake._session_db = db+ fake._running = _running_flag(1)++ async def _process_handoff(row, profile_name=None):+ return None++ fake._process_handoff = _process_handoff++ coro = run.GatewayRunner._handoff_watcher(fake, interval=0.0, drain_timeout=0.01)+ await asyncio.wait_for(coro, timeout=5)++ assert len(db.reclaim_calls) == 3, (+ f"expected one reclaim per scope (root + 2 profiles), got {len(db.reclaim_calls)}"+ )+++async def test_reclaim_tolerates_store_without_the_method(monkeypatch):+ """An older/duck-typed store must not abort watcher startup."""+ monkeypatch.setattr(run, "_handoff_watch_scopes", lambda _r: [(None, None)])++ async def _no_sleep(_seconds):+ return None++ monkeypatch.setattr(run.asyncio, "sleep", _no_sleep)++ class _OldDB:+ def __init__(self):+ self.polls = 0++ async def list_pending_handoffs(self):+ self.polls += 1+ return []++ db = _OldDB()+ fake = types.SimpleNamespace()+ fake._session_db = db+ fake._running = _running_flag(1)++ async def _process_handoff(row, profile_name=None):+ return None++ fake._process_handoff = _process_handoff++ coro = run.GatewayRunner._handoff_watcher(fake, interval=0.0, drain_timeout=0.01)+ await asyncio.wait_for(coro, timeout=5)++ assert db.polls == 1, "the watcher must still poll when reclaim is unavailable"+++def test_reclaim_stale_running_handoffs_flips_only_running_rows(tmp_path):+ """DB-level: only 'running' rows are touched, and their ids are returned."""+ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ for sid, state in (+ ("dead", "running"),+ ("queued", "pending"),+ ("done", "completed"),+ ):+ db.create_session(sid, "cli")+ db._execute_write(+ lambda conn, s=sid, st=state: conn.execute(+ "UPDATE sessions SET handoff_state = ? WHERE id = ?", (st, s)+ )+ )++ reclaimed = db.reclaim_stale_running_handoffs("gateway died")++ assert reclaimed == ["dead"]+ assert db.get_handoff_state("dead")["state"] == "failed"+ assert db.get_handoff_state("dead")["error"] == "gateway died"+ assert db.get_handoff_state("queued")["state"] == "pending"+ assert db.get_handoff_state("done")["state"] == "completed"+++def test_reclaimed_session_can_request_handoff_again(tmp_path):+ """The point of the reclaim: the session is usable again.++ ``request_handoff`` only accepts NULL/completed/failed, so a stranded+ 'running' row is what permanently locks the session out.+ """+ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session("stuck", "cli")+ db._execute_write(+ lambda conn: conn.execute(+ "UPDATE sessions SET handoff_state = 'running' WHERE id = 'stuck'"+ )+ )++ assert db.request_handoff("stuck", "telegram") is False, (+ "precondition: a stranded 'running' row blocks new handoff requests"+ )++ db.reclaim_stale_running_handoffs("gateway died")++ assert db.request_handoff("stuck", "telegram") is True, (+ "after reclaim the session must be able to hand off again"+ )