The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): classify terminal adapter connect failures + escalate long-lived retry loops (OOF-156)
Shannon Sands91bc82233006
diff --git a/gateway/run.py b/gateway/run.pyindex 4957b56f632..24497a34e27 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -43,7 +43,7 @@ import timefrom collections import OrderedDictfrom contextvars import copy_contextfrom pathlib import Path-from datetime import datetime+from datetime import datetime, timedelta, timezonefrom typing import Awaitable, Callable, Dict, Optional, Any, List, Tuple, Union, castfrom agent.async_utils import consume_detached_task_result, safe_schedule_threadsafe@@ -3788,12 +3788,41 @@ async def _dispose_unused_adapter(adapter: "BasePlatformAdapter | None") -> None# secondary-profile reconnects share this policy — tune in one place)._RECONNECT_BACKOFF_CAP = 300+# Seconds a platform may sit continuously in the reconnect queue before the+# watcher flags it NEEDS_ATTENTION in runtime status. Retrying never stops+# (auto-pause was deliberately removed — a transient outage must self-heal+# without operator action); this only makes a *long-lived* retry loop loud so+# owners and fleet monitoring can distinguish hour one from week three.+# A dead bot token, a revoked Discord intent, or a deterministically crashing+# sidecar all present as "retrying" forever without this signal.+_RECONNECT_ATTENTION_AFTER_SECONDS = int(+ os.getenv("HERMES_RECONNECT_ATTENTION_AFTER_SECONDS", "7200")+)+def _reconnect_backoff(attempt: int) -> int:"""Exponential reconnect backoff: 30s, 60s, 120s, ... capped at 5 min."""return min(30 * (2 ** (attempt - 1)), _RECONNECT_BACKOFF_CAP)+def _reconnect_needs_attention(info: dict, now: float) -> bool:+ """Return True when a reconnect-queue entry has been continuously queued+ long enough to warrant a NEEDS_ATTENTION signal.++ ``queued_at`` is (re)stamped whenever the platform (re)enters the queue,+ so a platform that reconnects successfully and later fails again starts a+ fresh clock — only *continuous* failure escalates. Entries queued before+ this field existed (in-flight upgrade) are treated as newly queued.+ """+ if _RECONNECT_ATTENTION_AFTER_SECONDS <= 0:+ return False # escalation disabled+ queued_at = info.get("queued_at")+ if queued_at is None:+ info["queued_at"] = now+ return False+ return (now - queued_at) >= _RECONNECT_ATTENTION_AFTER_SECONDS++class TurnRunner:"""Per-turn collaborator carrying the tool-progress callbacks that used tobe nested closures inside ``GatewayRunner._run_agent_inner``.@@ -7385,6 +7414,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew"config": platform_config,"attempts": 0,"next_retry": time.monotonic(),+ "queued_at": time.monotonic(),"credential_claim": self._adapter_credential_claim(adapter.platform, adapter),@@ -8216,14 +8246,22 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewplatform_state: Optional[str] = None,error_code: Optional[str] = None,error_message: Optional[str] = None,+ needs_attention: Optional[bool] = None,+ retrying_since: Any = _UNSET,) -> None:try:from gateway.status import write_runtime_status+ extra: Dict[str, Any] = {}+ if needs_attention is not None:+ extra["needs_attention"] = needs_attention+ if retrying_since is not _UNSET:+ extra["retrying_since"] = retrying_sincewrite_runtime_status(platform=platform,platform_state=platform_state,error_code=error_code,error_message=error_message,+ **extra,)except Exception:pass@@ -11576,6 +11614,8 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewplatform_state="connected",error_code=None,error_message=None,+ needs_attention=False,+ retrying_since=None,)logger.info("✓ %s connected", platform.value)else:@@ -11610,6 +11650,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew"config": platform_config,"attempts": 1,"next_retry": time.monotonic() + 30,+ "queued_at": time.monotonic(),"credential_claim": self._adapter_credential_claim(platform, adapter),@@ -11632,6 +11673,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew"config": platform_config,"attempts": 1,"next_retry": time.monotonic() + 30,+ "queued_at": time.monotonic(),"credential_claim": self._adapter_credential_claim(platform, adapter),@@ -11657,6 +11699,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew"config": platform_config,"attempts": 1,"next_retry": time.monotonic() + 30,+ "queued_at": time.monotonic(),"credential_claim": self._adapter_credential_claim(platform, adapter),@@ -12900,6 +12943,36 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# /platform resume to come back.if info.get("paused"):continue+ # Long-lived retry-loop escalation (OOF-156): once a platform+ # has been continuously queued past the attention threshold,+ # flag it NEEDS_ATTENTION in runtime status so owners and+ # fleet monitoring see "this is not a blip" — a dead token,+ # revoked intent, or crash-looping sidecar otherwise presents+ # as ordinary "retrying" forever. Retries continue unchanged:+ # this is a signal, NOT a circuit breaker (auto-pause was+ # deliberately removed — see this docstring's history).+ if not info.get("attention_flagged") and _reconnect_needs_attention(info, now):+ info["attention_flagged"] = True+ queued_for = now - info.get("queued_at", now)+ retrying_since_iso = (+ datetime.now(timezone.utc) - timedelta(seconds=queued_for)+ ).isoformat()+ logger.warning(+ "%s has been failing/reconnecting continuously for "+ "%.1f hours (%d attempts) — flagging NEEDS_ATTENTION. "+ "Retries continue, but this usually means a permanent "+ "problem (revoked credentials, missing intents, broken "+ "sidecar). Check `hermes status` / `/platform list`.",+ platform.value,+ queued_for / 3600.0,+ info.get("attempts", 0),+ )+ self._update_platform_runtime_status(+ platform.value,+ platform_state="retrying",+ needs_attention=True,+ retrying_since=retrying_since_iso,+ )if now < info["next_retry"]:continue # not time yet@@ -12963,6 +13036,8 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewplatform_state="connected",error_code=None,error_message=None,+ needs_attention=False,+ retrying_since=None,)logger.info("✓ %s reconnected successfully", platform.value)diff --git a/gateway/status.py b/gateway/status.pyindex 4e6b8c86945..1616d109342 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -987,6 +987,8 @@ def write_runtime_status(platform_state: Any = _UNSET,error_code: Any = _UNSET,error_message: Any = _UNSET,+ needs_attention: Any = _UNSET,+ retrying_since: Any = _UNSET,served_profiles: Any = _UNSET,) -> None:"""Persist gateway runtime health information for diagnostics/status."""@@ -1023,6 +1025,17 @@ def write_runtime_status(platform_payload["error_code"] = error_codeif error_message is not _UNSET:platform_payload["error_message"] = error_message+ if needs_attention is not _UNSET:+ # Long-lived reconnect-loop escalation (OOF-156): True once a+ # platform has been continuously failing/retrying past the+ # attention threshold. Retry never stops — this is a signal for+ # owners and fleet monitoring, not a circuit breaker. Cleared+ # (False) on successful reconnect.+ platform_payload["needs_attention"] = bool(needs_attention)+ if retrying_since is not _UNSET:+ # ISO timestamp of when the platform entered its current+ # continuous retry episode; None clears it on reconnect.+ platform_payload["retrying_since"] = retrying_sinceplatform_payload["updated_at"] = _utc_now_iso()payload["platforms"][platform] = platform_payloaddiff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 45d2e8858ac..239a93a7117 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -1435,6 +1435,13 @@ class DiscordAdapter(BasePlatformAdapter):# each process every message, producing duplicate threads/responses.await self._cancel_bot_task()self._release_platform_lock()+ # Always set an explicit fatal code (OOF-152): a code-less failure+ # forces the gateway into its "no info = probably transient" guess.+ self._set_fatal_error(+ "discord_connect_timeout",+ "Timed out waiting for the Discord gateway to become ready",+ retryable=True,+ )return Falseexcept Exception as e: # pragma: no cover - defensive logginglogger.error("[%s] Failed to connect to Discord: %s", self.name, e, exc_info=True)@@ -1443,8 +1450,72 @@ class DiscordAdapter(BasePlatformAdapter):# step raises. Cancel it so the discarded adapter cannot connect.await self._cancel_bot_task()self._release_platform_lock()+ # Classify by exception TYPE (OOF-152). Previously this branch set+ # no fatal error at all, so the gateway treated every startup+ # failure — including a revoked token or a privileged intent that+ # was never enabled in the Developer Portal — as transient and+ # retried it forever with zero owner signal. Auth/permission+ # failures can never self-heal: mark them retryable=False so they+ # drop out of the reconnect queue and surface as fatal.+ code, message, retryable = self._classify_connect_exception(e)+ self._set_fatal_error(code, message, retryable=retryable)return False+ @staticmethod+ def _classify_connect_exception(error: Exception) -> tuple:+ """Map a Discord startup exception to ``(code, message, retryable)``.++ Type-based only — never match on message text. Unknown exception+ types stay ``retryable=True``: a false terminal on a transient error+ would leave a recovered platform silently dead, which is the exact+ failure mode the auto-pause removal fixed. The reconnect watcher's+ NEEDS_ATTENTION escalation covers misclassified permanent failures.+ """+ name = error.__class__.__name__+ # String-typename fallback keeps this classifiable when discord.py is+ # mocked (tests) or the import fails; real isinstance checks follow.+ if name == "LoginFailure":+ return (+ "discord_auth_error",+ f"Discord bot token rejected: {error}. The token is invalid or "+ "was revoked — regenerate it in the Discord Developer Portal "+ "and update DISCORD_BOT_TOKEN.",+ False,+ )+ if name == "PrivilegedIntentsRequired":+ return (+ "discord_intents_required",+ "Discord privileged intents are not enabled for this bot: "+ f"{error}. Enable 'Message Content Intent' (and any other "+ "required privileged intents) for this application in the "+ "Discord Developer Portal → Bot → Privileged Gateway Intents.",+ False,+ )+ try:+ import discord as _discord+ login_failure = getattr(_discord, "LoginFailure", None)+ intents_required = getattr(_discord, "PrivilegedIntentsRequired", None)+ if isinstance(login_failure, type) and isinstance(error, login_failure):+ return (+ "discord_auth_error",+ f"Discord bot token rejected: {error}. The token is invalid "+ "or was revoked — regenerate it in the Discord Developer "+ "Portal and update DISCORD_BOT_TOKEN.",+ False,+ )+ if isinstance(intents_required, type) and isinstance(error, intents_required):+ return (+ "discord_intents_required",+ "Discord privileged intents are not enabled for this bot: "+ f"{error}. Enable 'Message Content Intent' for this "+ "application in the Discord Developer Portal → Bot → "+ "Privileged Gateway Intents.",+ False,+ )+ except Exception:+ pass+ return ("discord_connect_error", f"Discord startup failed: {error}", True)+def _discord_message_admission(self,message: Any,diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.pyindex 8698dc93803..c26ee51d9bf 100644--- a/plugins/platforms/email/adapter.py+++ b/plugins/platforms/email/adapter.py@@ -682,6 +682,21 @@ class EmailAdapter(BasePlatformAdapter):logger.info("[Email] IMAP connection test passed. %d existing messages skipped.", len(self._seen_uids))except Exception as e:logger.error("[Email] IMAP connection failed: %s", e)+ # Always set an explicit fatal code (OOF-156): returning False+ # with no error info made the gateway treat every IMAP failure —+ # including permanently bad credentials — as transient, retrying+ # forever with zero owner signal ("stuck retrying 22h").+ # Kept retryable=True deliberately: imaplib raises the same+ # generic IMAP4.error for bad credentials AND transient server+ # NOs (e.g. Gmail's "too many simultaneous connections"), so a+ # type-based terminal classification isn't safe here. Long-lived+ # loops surface via the reconnect watcher's NEEDS_ATTENTION+ # escalation instead.+ self._set_fatal_error(+ "email_imap_connect_error",+ f"IMAP connection to {self._imap_host}:{self._imap_port} failed: {e}",+ retryable=True,+ )return Falsetry:@@ -692,8 +707,27 @@ class EmailAdapter(BasePlatformAdapter):finally:smtp.quit()logger.info("[Email] SMTP connection test passed.")+ except smtplib.SMTPAuthenticationError as e:+ logger.error("[Email] SMTP authentication failed: %s", e)+ # Typed auth failure (535 & friends): bad or revoked credentials+ # can never self-heal, so drop out of the reconnect queue instead+ # of retrying a dead password forever (OOF-156). Type-based only —+ # SMTPAuthenticationError is unambiguous, unlike IMAP4.error above.+ self._set_fatal_error(+ "email_auth_error",+ f"SMTP authentication failed for {self._address}: {e}. "+ "Check EMAIL_PASSWORD (for Gmail/Outlook this must be an "+ "app password, not the account password).",+ retryable=False,+ )+ return Falseexcept Exception as e:logger.error("[Email] SMTP connection failed: %s", e)+ self._set_fatal_error(+ "email_smtp_connect_error",+ f"SMTP connection to {self._smtp_host} failed: {e}",+ retryable=True,+ )return Falseself._running = Truediff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.pyindex d7f89c4a692..b0bc3e388c3 100644--- a/plugins/platforms/photon/adapter.py+++ b/plugins/platforms/photon/adapter.py@@ -283,6 +283,23 @@ _DEFAULT_MENTION_PATTERNS = [# ---------------------------------------------------------------------------# Module-level helpers — also used by check_fn / standalone send+class PhotonSidecarStartupError(RuntimeError):+ """Typed startup failure raised by ``_start_sidecar`` (OOF-156).++ Carries the fatal-error classification instead of relying on+ ``connect()``'s catch-all, which used to collapse every startup failure+ into ``SIDECAR_FAILED, retryable=True`` — including deterministic ones+ (deps that can't install on an immutable image, missing node binary)+ that then retried forever with zero owner signal. ``retryable`` defaults+ to True: only failures known to be deterministic mark themselves False.+ """++ def __init__(self, message: str, *, code: str = "SIDECAR_FAILED", retryable: bool = True) -> None:+ self.code = code+ self.retryable = retryable+ super().__init__(message)++class PhotonSidecarError(RuntimeError):"""Structured failure returned by the supervised Photon sidecar."""@@ -900,11 +917,22 @@ class PhotonAdapter(BasePlatformAdapter):try:await self._start_sidecar()except Exception as e:- self._set_fatal_error(- "SIDECAR_FAILED",- f"failed to start Photon sidecar: {e}",- retryable=True,- )+ # Honor typed classification from _start_sidecar (OOF-153):+ # deterministic failures (deps can't install on an immutable+ # image, node binary missing) are retryable=False so they+ # surface as fatal instead of silently spinning in the+ # reconnect queue. Everything else — sidecar crashed before+ # ready, /healthz timeout — stays retryable=True; ambiguity+ # resolves toward retry, with the gateway's NEEDS_ATTENTION+ # escalation as the backstop for long-lived loops.+ if isinstance(e, PhotonSidecarStartupError):+ self._set_fatal_error(e.code, str(e), retryable=e.retryable)+ else:+ self._set_fatal_error(+ "SIDECAR_FAILED",+ f"failed to start Photon sidecar: {e}",+ retryable=True,+ )# No live sidecar — make sure no stale runtime record# survives to mislead standalone senders._delete_runtime_record()@@ -1575,10 +1603,16 @@ class PhotonAdapter(BasePlatformAdapter):)await asyncio.to_thread(_reinstall_sidecar_deps)if not sidecar_deps_installed():- raise RuntimeError(+ # Deterministic on managed/immutable images: npm ci failed and+ # will fail identically on every retry (OOF-153) — surface as+ # non-retryable so it doesn't spin silently in the reconnect+ # queue for weeks.+ raise PhotonSidecarStartupError(f"Photon sidecar deps could not be installed into "f"{_sidecar_dir()} (see log for the npm error). "- f"Run: cd {_sidecar_dir()} && npm ci (or `hermes photon setup`)"+ f"Run: cd {_sidecar_dir()} && npm ci (or `hermes photon setup`)",+ code="SIDECAR_DEPS_MISSING",+ retryable=False,)# A `hermes update` that bumps the spectrum-ts pin rewrites# package-lock.json but never reinstalls node_modules, so the sidecar@@ -1642,19 +1676,28 @@ class PhotonAdapter(BasePlatformAdapter):exc,)- self._sidecar_proc = subprocess.Popen( # noqa: S603- [self._node_bin, str(_sidecar_dir() / "index.mjs")],- stdin=subprocess.PIPE,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- env=env,- start_new_session=(sys.platform != "win32"),- # Windows: run the persistent sidecar headless so it does not open- # (or leave) a visible console window. CREATE_NO_WINDOW only (no- # DETACHED_PROCESS) so the stdin/stdout pipes above stay usable.- creationflags=windows_hide_flags(),- )-+ try:+ self._sidecar_proc = subprocess.Popen( # noqa: S603+ [self._node_bin, str(_sidecar_dir() / "index.mjs")],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ env=env,+ start_new_session=(sys.platform != "win32"),+ # Windows: run the persistent sidecar headless so it does not open+ # (or leave) a visible console window. CREATE_NO_WINDOW only (no+ # DETACHED_PROCESS) so the stdin/stdout pipes above stay usable.+ creationflags=windows_hide_flags(),+ )+ except FileNotFoundError as exc:+ # Deterministic: node isn't on PATH / PHOTON_NODE_BIN points at+ # nothing. Retrying can never fix a missing binary (OOF-153).+ raise PhotonSidecarStartupError(+ f"node binary not found ({self._node_bin!r}) — install Node.js "+ f"or set PHOTON_NODE_BIN: {exc}",+ code="SIDECAR_NODE_MISSING",+ retryable=False,+ ) from exc# Pump sidecar stderr/stdout into our logger so users see crashes.loop = asyncio.get_event_loop()self._sidecar_supervisor_task = loop.create_task(diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex b714ab7a121..093f5b23600 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -1516,6 +1516,26 @@ class TelegramAdapter(BasePlatformAdapter):or "another bot instance is running" in text)+ @staticmethod+ def _looks_like_auth_error(error: Exception) -> bool:+ """Return True for credential failures that can never self-heal.++ InvalidToken (malformed/unknown token) and Forbidden (revoked token /+ bot deleted) are terminal: no amount of reconnecting fixes them, so+ connect() must classify them retryable=False (OOF-151). Deliberately+ narrower than "not _looks_like_network_error" — BadRequest and+ RetryAfter are non-network but transient at connect time and must+ keep retrying. Type-based only; never match on message text.+ """+ name = error.__class__.__name__.lower()+ if name in {"invalidtoken", "forbidden"}:+ return True+ try:+ from telegram.error import Forbidden, InvalidToken+ return isinstance(error, (InvalidToken, Forbidden))+ except ImportError:+ return False+@staticmethoddef _looks_like_network_error(error: Exception) -> bool:"""Return True for transient transport failures that warrant reconnect."""@@ -4463,8 +4483,23 @@ class TelegramAdapter(BasePlatformAdapter):except Exception as e:self._release_platform_lock()safe_error = _redact_telegram_error_text(e)- message = f"Telegram startup failed: {safe_error}"- self._set_fatal_error("telegram_connect_error", message, retryable=True)+ # Classify by exception TYPE (never message text): auth failures+ # (InvalidToken / Forbidden — dead or revoked bot token) can never+ # self-heal, so marking them retryable put agents into a silent,+ # eternal reconnect loop (OOF-151: weeks of retries at the backoff+ # cap with zero owner signal). _looks_like_network_error already+ # discriminates these types for the runtime polling path — reuse+ # it here so connect() and runtime agree on what is transient.+ if self._looks_like_auth_error(e):+ message = (+ f"Telegram bot token rejected: {safe_error}. "+ "The token is invalid or was revoked — generate a new one "+ "with @BotFather and update TELEGRAM_BOT_TOKEN."+ )+ self._set_fatal_error("telegram_auth_error", message, retryable=False)+ else:+ message = f"Telegram startup failed: {safe_error}"+ self._set_fatal_error("telegram_connect_error", message, retryable=True)logger.error("[%s] Failed to connect to Telegram: %s", self.name, safe_error)return Falsediff --git a/tests/gateway/test_adapter_connect_classification.py b/tests/gateway/test_adapter_connect_classification.pynew file mode 100644index 00000000000..724c8391b86--- /dev/null+++ b/tests/gateway/test_adapter_connect_classification.py@@ -0,0 +1,445 @@+"""Connect-failure classification + reconnect-queue escalation (OOF-156).++Four platforms (telegram, discord, photon, email) used to funnel every+startup failure into an indefinitely-retried state — including permanent+failures like revoked tokens, missing privileged intents, and sidecar deps+that can never install on an immutable image. Fleet triage found agents that+had been silently "retrying" for weeks (OOF-151/152/153).++Two-part fix, both covered here:++1. Per-adapter classification: auth/permission/deterministic failures are+ classified by exception TYPE (never message text) as ``retryable=False``+ so they exit via the existing non-retryable fatal path.+2. Gateway escalation: platforms continuously in the reconnect queue past a+ threshold get ``needs_attention`` flagged in runtime status. Retries never+ stop — the deliberate removal of auto-pause stands (a transient outage+ must self-heal without operator action).+"""++import asyncio+import time+from unittest.mock import MagicMock, patch++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.run import (+ GatewayRunner,+ _reconnect_needs_attention,+)+++# ── Telegram: type-based auth classification ───────────────────────────+++class InvalidToken(Exception): # noqa: N818 — name-matched stand-in+ pass+++class Forbidden(Exception): # noqa: N818+ pass+++class NetworkError(Exception): # noqa: N818+ pass+++class TimedOut(Exception): # noqa: N818+ pass+++def _telegram_classifier():+ from plugins.platforms.telegram.adapter import TelegramAdapter++ return TelegramAdapter._looks_like_auth_error+++class TestTelegramAuthClassification:+ """InvalidToken/Forbidden are terminal; transient transports are not."""++ def test_invalid_token_is_auth_error(self):+ # Classifier matches on class name so tests do not need real+ # telegram.error types — mirrors _looks_like_network_error's design.+ assert _telegram_classifier()(InvalidToken("401 Unauthorized")) is True++ def test_forbidden_is_auth_error(self):+ assert _telegram_classifier()(Forbidden("bot was deleted")) is True++ def test_network_error_is_not_auth_error(self):+ assert _telegram_classifier()(NetworkError("dns failure")) is False++ def test_timeout_is_not_auth_error(self):+ assert _telegram_classifier()(TimedOut("read timeout")) is False++ def test_generic_exception_is_not_auth_error(self):+ # Unknown types must stay retryable — a false terminal recreates the+ # "silently dead bot" problem the auto-pause removal fixed.+ assert _telegram_classifier()(RuntimeError("weird")) is False++ def test_auth_message_text_does_not_classify(self):+ # Guard against text matching creeping back in: an exception whose+ # MESSAGE mentions auth but whose type is generic must stay retryable.+ assert _telegram_classifier()(RuntimeError("InvalidToken Forbidden")) is False+++# ── Discord: connect exception classification ──────────────────────────+++class LoginFailure(Exception):+ """Name-matched stand-in for discord.LoginFailure."""+++class PrivilegedIntentsRequired(Exception):+ """Name-matched stand-in for discord.PrivilegedIntentsRequired."""+++def _discord_classifier():+ from plugins.platforms.discord.adapter import DiscordAdapter++ return DiscordAdapter._classify_connect_exception+++class TestDiscordConnectClassification:+ def test_login_failure_is_terminal(self):+ code, message, retryable = _discord_classifier()(LoginFailure("Improper token"))+ assert code == "discord_auth_error"+ assert retryable is False+ assert "Developer Portal" in message++ def test_privileged_intents_is_terminal(self):+ code, message, retryable = _discord_classifier()(+ PrivilegedIntentsRequired("shard 0 requested privileged intents")+ )+ assert code == "discord_intents_required"+ assert retryable is False+ assert "Message Content Intent" in message++ def test_unknown_exception_is_retryable_with_explicit_code(self):+ # The old behavior set NO fatal code at all, which the gateway read+ # as "probably transient". Every failure must now carry a code.+ code, message, retryable = _discord_classifier()(OSError("connection reset"))+ assert code == "discord_connect_error"+ assert retryable is True++ def test_auth_message_text_does_not_classify(self):+ code, _message, retryable = _discord_classifier()(+ RuntimeError("LoginFailure: PrivilegedIntentsRequired")+ )+ assert code == "discord_connect_error"+ assert retryable is True+++# ── Photon: typed sidecar startup errors ───────────────────────────────+++class TestPhotonSidecarStartupClassification:+ def _make_adapter(self, monkeypatch):+ monkeypatch.setenv("PHOTON_PROJECT_ID", "pid")+ monkeypatch.setenv("PHOTON_PROJECT_SECRET", "psecret")+ from plugins.platforms.photon.adapter import PhotonAdapter++ return PhotonAdapter(PlatformConfig(enabled=True, token="", extra={}))++ @pytest.mark.asyncio+ async def test_typed_startup_error_sets_nonretryable_fatal(self, monkeypatch):+ from plugins.platforms.photon import adapter as photon_adapter++ adapter = self._make_adapter(monkeypatch)++ async def _boom():+ raise photon_adapter.PhotonSidecarStartupError(+ "deps could not be installed",+ code="SIDECAR_DEPS_MISSING",+ retryable=False,+ )++ monkeypatch.setattr(adapter, "_start_sidecar", _boom)+ ok = await adapter.connect()++ assert ok is False+ assert adapter.fatal_error_code == "SIDECAR_DEPS_MISSING"+ assert adapter.fatal_error_retryable is False++ @pytest.mark.asyncio+ async def test_untyped_startup_error_stays_retryable(self, monkeypatch):+ # Ambiguous failures (crash before ready, health timeout) must keep+ # retrying; the gateway's needs_attention escalation is the backstop.+ adapter = self._make_adapter(monkeypatch)++ async def _boom():+ raise RuntimeError("sidecar exited with code 1 before becoming ready")++ monkeypatch.setattr(adapter, "_start_sidecar", _boom)+ ok = await adapter.connect()++ assert ok is False+ assert adapter.fatal_error_code == "SIDECAR_FAILED"+ assert adapter.fatal_error_retryable is True++ def test_deps_install_failure_raises_typed_nonretryable(self, monkeypatch):+ from plugins.platforms.photon import adapter as photon_adapter++ adapter = self._make_adapter(monkeypatch)+ monkeypatch.setattr(photon_adapter, "sidecar_deps_installed", lambda: False)+ monkeypatch.setattr(photon_adapter, "_reinstall_sidecar_deps", lambda: None)++ with pytest.raises(photon_adapter.PhotonSidecarStartupError) as exc_info:+ asyncio.get_event_loop().run_until_complete(adapter._start_sidecar())++ assert exc_info.value.code == "SIDECAR_DEPS_MISSING"+ assert exc_info.value.retryable is False+++# ── Email: explicit fatal codes on IMAP/SMTP failure ───────────────────+++class TestEmailConnectClassification:+ def _make_adapter(self, monkeypatch):+ for key, value in {+ "EMAIL_ADDRESS": "[email protected]",+ "EMAIL_PASSWORD": "app-password",+ "EMAIL_IMAP_HOST": "imap.example.com",+ "EMAIL_SMTP_HOST": "smtp.example.com",+ }.items():+ monkeypatch.setenv(key, value)+ from plugins.platforms.email.adapter import EmailAdapter++ return EmailAdapter(PlatformConfig(enabled=True, token=""))++ @pytest.mark.asyncio+ async def test_imap_failure_sets_explicit_retryable_fatal(self, monkeypatch):+ # The old code returned False with NO fatal info — the gateway's+ # "no info = transient" branch then retried forever with zero owner+ # signal ("stuck retrying 22h").+ adapter = self._make_adapter(monkeypatch)+ from plugins.platforms.email import adapter as email_adapter++ def _raise(*a, **k):+ raise email_adapter.imaplib.IMAP4.error(b"[AUTHENTICATIONFAILED]")++ monkeypatch.setattr(email_adapter.imaplib, "IMAP4_SSL", _raise)+ ok = await adapter.connect()++ assert ok is False+ assert adapter.fatal_error_code == "email_imap_connect_error"+ # IMAP4.error is the same type for bad creds and transient server+ # NOs, so a type-based terminal classification is not safe here.+ assert adapter.fatal_error_retryable is True++ @pytest.mark.asyncio+ async def test_smtp_auth_failure_is_terminal(self, monkeypatch):+ import smtplib++ adapter = self._make_adapter(monkeypatch)+ from plugins.platforms.email import adapter as email_adapter++ imap = MagicMock()+ imap.uid.return_value = ("OK", [b""])+ monkeypatch.setattr(email_adapter.imaplib, "IMAP4_SSL", lambda *a, **k: imap)++ def _smtp_fail():+ raise smtplib.SMTPAuthenticationError(535, b"authentication failed")++ monkeypatch.setattr(adapter, "_connect_smtp", _smtp_fail)+ ok = await adapter.connect()++ assert ok is False+ assert adapter.fatal_error_code == "email_auth_error"+ assert adapter.fatal_error_retryable is False++ @pytest.mark.asyncio+ async def test_smtp_transient_failure_stays_retryable(self, monkeypatch):+ adapter = self._make_adapter(monkeypatch)+ from plugins.platforms.email import adapter as email_adapter++ imap = MagicMock()+ imap.uid.return_value = ("OK", [b""])+ monkeypatch.setattr(email_adapter.imaplib, "IMAP4_SSL", lambda *a, **k: imap)++ def _smtp_fail():+ raise OSError("connection refused")++ monkeypatch.setattr(adapter, "_connect_smtp", _smtp_fail)+ ok = await adapter.connect()++ assert ok is False+ assert adapter.fatal_error_code == "email_smtp_connect_error"+ assert adapter.fatal_error_retryable is True+++# ── Gateway: needs_attention escalation ────────────────────────────────+++class TestReconnectNeedsAttention:+ def test_fresh_entry_is_not_flagged_and_gets_stamped(self):+ # In-flight upgrade path: entries queued before queued_at existed are+ # treated as newly queued, not instantly escalated.+ info = {"attempts": 3}+ now = time.monotonic()+ assert _reconnect_needs_attention(info, now) is False+ assert info["queued_at"] == now++ def test_below_threshold_is_not_flagged(self):+ now = time.monotonic()+ info = {"queued_at": now - 60}+ assert _reconnect_needs_attention(info, now) is False++ def test_past_threshold_is_flagged(self):+ import gateway.run as run_module++ now = time.monotonic()+ info = {"queued_at": now - (run_module._RECONNECT_ATTENTION_AFTER_SECONDS + 1)}+ assert _reconnect_needs_attention(info, now) is True++ def test_zero_threshold_disables_escalation(self, monkeypatch):+ import gateway.run as run_module++ monkeypatch.setattr(run_module, "_RECONNECT_ATTENTION_AFTER_SECONDS", 0)+ info = {"queued_at": time.monotonic() - 999999}+ assert _reconnect_needs_attention(info, time.monotonic()) is False+++def _make_runner():+ """Minimal GatewayRunner via object.__new__ (same pattern as+ test_platform_reconnect.py)."""+ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="test")}+ )+ runner._running = True+ runner._shutdown_event = asyncio.Event()+ runner._exit_reason = None+ runner._exit_with_failure = False+ runner._exit_cleanly = False+ runner._failed_platforms = {}+ runner.adapters = {}+ runner.delivery_router = MagicMock()+ runner._running_agents = {}+ runner._pending_messages = {}+ runner._pending_approvals = {}+ runner._honcho_managers = {}+ runner._honcho_configs = {}+ runner._shutdown_all_gateway_honcho = lambda: None+ runner.session_store = MagicMock()+ return runner+++class TestWatcherAttentionEscalation:+ @pytest.mark.asyncio+ async def test_watcher_flags_long_queued_platform_and_keeps_retrying(self, monkeypatch):+ import gateway.run as run_module++ runner = _make_runner()+ status_writes = []+ monkeypatch.setattr(+ runner,+ "_update_platform_runtime_status",+ lambda platform, **kw: status_writes.append((platform, kw)),+ )++ threshold = run_module._RECONNECT_ATTENTION_AFTER_SECONDS+ runner._failed_platforms[Platform.TELEGRAM] = {+ "config": PlatformConfig(enabled=True, token="test"),+ "attempts": 40,+ # Not yet due for a retry — escalation must not depend on the+ # backoff schedule lining up.+ "next_retry": time.monotonic() + 300,+ "queued_at": time.monotonic() - threshold - 10,+ }++ real_sleep = asyncio.sleep+ call_count = 0++ async def fake_sleep(n):+ nonlocal call_count+ call_count += 1+ if call_count > 1:+ runner._running = False+ await real_sleep(0)++ with patch("asyncio.sleep", side_effect=fake_sleep):+ await runner._platform_reconnect_watcher()++ attention = [kw for _p, kw in status_writes if kw.get("needs_attention")]+ assert attention, f"expected a needs_attention status write, got {status_writes!r}"+ assert attention[0]["platform_state"] == "retrying"+ assert attention[0].get("retrying_since")+ # Platform must STILL be queued — escalation is a signal, never a+ # circuit breaker.+ assert Platform.TELEGRAM in runner._failed_platforms+ assert runner._failed_platforms[Platform.TELEGRAM].get("attention_flagged") is True++ @pytest.mark.asyncio+ async def test_watcher_flags_only_once(self, monkeypatch):+ import gateway.run as run_module++ runner = _make_runner()+ status_writes = []+ monkeypatch.setattr(+ runner,+ "_update_platform_runtime_status",+ lambda platform, **kw: status_writes.append((platform, kw)),+ )++ threshold = run_module._RECONNECT_ATTENTION_AFTER_SECONDS+ runner._failed_platforms[Platform.TELEGRAM] = {+ "config": PlatformConfig(enabled=True, token="test"),+ "attempts": 40,+ "next_retry": time.monotonic() + 300,+ "queued_at": time.monotonic() - threshold - 10,+ }++ real_sleep = asyncio.sleep+ call_count = 0++ async def fake_sleep(n):+ nonlocal call_count+ call_count += 1+ if call_count > 3:+ runner._running = False+ await real_sleep(0)++ with patch("asyncio.sleep", side_effect=fake_sleep):+ await runner._platform_reconnect_watcher()++ attention = [kw for _p, kw in status_writes if kw.get("needs_attention")]+ assert len(attention) == 1, (+ f"needs_attention must be written once per episode, got {len(attention)}"+ )+++# ── Status file: new platform fields round-trip ────────────────────────+++class TestRuntimeStatusAttentionFields:+ def test_needs_attention_and_retrying_since_persisted(self, tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ from gateway import status as status_module++ status_module.write_runtime_status(+ platform="telegram",+ platform_state="retrying",+ error_code="telegram_connect_error",+ error_message="boom",+ needs_attention=True,+ retrying_since="2026-08-11T00:00:00+00:00",+ )+ payload = status_module.read_runtime_status()+ platform = payload["platforms"]["telegram"]+ assert platform["needs_attention"] is True+ assert platform["retrying_since"] == "2026-08-11T00:00:00+00:00"++ # Reconnect clears both.+ status_module.write_runtime_status(+ platform="telegram",+ platform_state="connected",+ error_code=None,+ error_message=None,+ needs_attention=False,+ retrying_since=None,+ )+ payload = status_module.read_runtime_status()+ platform = payload["platforms"]["telegram"]+ assert platform["needs_attention"] is False+ assert platform["retrying_since"] is None