The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(health): narrow or log the swallowed exceptions the PR added in hermes_cli, tui_gateway, acp_adapter
Tekniumc5ebfe1108d3
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 4525716fd4f..80c8fa2f6f1 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asynciofrom contextlib import suppress+import loggingimport uuidimport acp@@ -16,6 +17,8 @@ from hermes_cli.gateway_client import GatewayClientError, connect_gatewayfrom hermes_constants import get_hermes_homefrom acp_adapter.session import _translate_acp_cwd, _normalize_cwd_for_compare+logger = logging.getLogger(__name__)+def _stage_user_content(content):"""Shared-converter output -> ``(text, attachments)`` for ``prompt.submit``.@@ -312,6 +315,9 @@ class GatewayACPAgent(acp.Agent):except asyncio.CancelledError:raiseexcept Exception as exc:+ # Boundary: ANY projection failure must reach every waiter (prompt/load re-raise+ # ``_failure``), or they block forever on ``_changed``.+ logger.debug("ACP gateway event projection stopped", exc_info=True)async with self._changed:self._failure = excself._changed.notify_all()@@ -378,7 +384,6 @@ class GatewayACPAgent(acp.Agent):self._permissions[key] = asyncio.create_task(self._answer_permission(session_id, prompt))async def _answer_permission(self, session_id, prompt):- import loggingfrom acp.schema import AllowedOutcomefrom acp_adapter.permissions import (_build_permission_options, _build_permission_tool_call, _OPTION_ID_TO_HERMES,@@ -405,7 +410,9 @@ class GatewayACPAgent(acp.Agent):prompt_id=prompt["prompt_id"], execution_generation=prompt["execution_generation"],choice=_OPTION_ID_TO_HERMES[response.outcome.option_id])except Exception:- logging.getLogger(__name__).info("ACP permission viewer detached or control expired")+ # Boundary: a detached viewer or expired control is not a denial; the canonical+ # waiter stays answerable by another viewer, so nothing propagates.+ logger.info("ACP permission viewer detached or control expired", exc_info=True)async def aclose(self):for task in self._permissions.values():diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 0ec40ade176..9b528a4fac1 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -1080,6 +1080,9 @@ def _revive_gateway_after_import(hermes_root: Path) -> None:print()ensure_gateway_service(context="import")except Exception:+ # Import boundary: the restore already succeeded; any service failure prints the+ # manual fallback instead of failing the import.+ logger.debug("gateway revive after import failed", exc_info=True)print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway run")diff --git a/hermes_cli/backup_restore.py b/hermes_cli/backup_restore.pyindex bf47224534a..1e5fff4a706 100644--- a/hermes_cli/backup_restore.py+++ b/hermes_cli/backup_restore.py@@ -274,8 +274,9 @@ def _restore_db_pages(src: Path, dst: Path) -> bool:# Force a WAL checkpoint so the backup starts from a clean# state rather than writing on top of a deep WAL.dst_conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")- except Exception:- pass+ except sqlite3.Error as exc:+ # Optional: backup() still publishes over a deep WAL, just less tidily.+ logger.debug("Pre-restore WAL checkpoint of %s skipped: %s", dst, exc)src_conn = sqlite3.connect(read_only_db_uri(src), uri=True)try:src_conn.backup(dst_conn)@@ -286,10 +287,11 @@ def _restore_db_pages(src: Path, dst: Path) -> bool:try:mode = src.stat().st_modedst.chmod(mode)- except Exception:- pass+ except OSError as exc:+ # The data is restored; only the snapshot's file mode could not be carried over.+ logger.warning("Restored %s but could not apply the snapshot's file mode: %s", dst, exc)return True- except Exception as exc:+ except (sqlite3.Error, OSError, ValueError) as exc: # ValueError: an unrepresentable pathlogger.warning("SQLite safe restore failed for %s -> %s: %s", src, dst, exc)# Release our own handle on *dst* before the fallback: on Windows an# open connection blocks unlink() with WinError 32, which would make@@ -297,8 +299,8 @@ def _restore_db_pages(src: Path, dst: Path) -> bool:if dst_conn is not None:try:dst_conn.close()- except Exception:- pass+ except sqlite3.Error as close_exc:+ logger.debug("Closing %s before the fallback restore failed: %s", dst, close_exc)# Fallback: unlink+move (the old approach). This still works for# the common case where no other process holds the DB open.from hermes_cli.sqlite_safe_read import (@@ -358,7 +360,7 @@ def _restore_db_pages(src: Path, dst: Path) -> bool:dst, exc2,)return False- except Exception as exc2:+ except (OSError, ValueError) as exc2: # ValueError: a path the OS cannot representlogger.error("Fallback restore also failed for %s -> %s: %s", src, dst, exc2)return Falsediff --git a/hermes_cli/cli_auto_maintenance.py b/hermes_cli/cli_auto_maintenance.pyindex d5803774c8a..5de986b4048 100644--- a/hermes_cli/cli_auto_maintenance.py+++ b/hermes_cli/cli_auto_maintenance.py@@ -7,6 +7,7 @@ cli-level names through ``from cli import ...`` at call time so facade monkeypatfrom __future__ import annotationsimport logging+import sqlite3import threading# Log-record parity with the origin module.@@ -39,7 +40,9 @@ def _run_state_db_auto_maintenance(session_db) -> None:continuetry:count = repair()- except Exception as _exc:+ # Every SessionDB refusal: sqlite/IO, RuntimeStoreError (ValueError), and the+ # hermes_state_errors busy/replaced family (RuntimeError).+ except (sqlite3.Error, OSError, ValueError, RuntimeError) as _exc:# Latched below regardless: a repair this store refuses (live ledger work,# locked file) must surface once, not retry silently on every start.logger.warning(skip_msg, _exc)diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 23f7049e465..33242552969 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -1,11 +1,14 @@"""Classic terminal presentation of authority events and fenced controls."""import asynciofrom contextlib import suppress+import loggingimport sysimport uuidfrom hermes_cli.gateway_client import GatewayClientError+logger = logging.getLogger(__name__)+_BLOCKING_CONTROL_EVENTS = frozenset({"approval.request", "approval.settled", "clarify.request", "clarify.settled",@@ -243,14 +246,18 @@ class GatewayChatView:async def _write_usage_file(self, admission, outcome):"""``-z --usage-file``: the same JSON ledger the in-process one-shot wrote, read from theresult the owner committed with this admission's settlement (best-effort, never raises)."""+ from websockets.exceptions import WebSocketExceptionfrom hermes_cli.oneshot import _write_usage_fileresult = {}try:receipt = await self.client.rpc("prompt.receipt", session_id=self.session_id,admission_id=admission, include_result=True)result = dict(receipt.get("result") or {})- except Exception:- pass+ # Transport loss / refusal, or a receipt whose ``result`` is not a mapping.+ except (GatewayClientError, OSError, TimeoutError, WebSocketException,+ AttributeError, TypeError, ValueError) as exc:+ # The ledger is still written from the outcome alone; a missing receipt is not fatal.+ logger.debug("usage-file receipt for %s unavailable: %s", admission, exc)result.setdefault("session_id", self.session_id)failure = None if outcome in ("completed", "cancelled") else (result.get("error") or outcome or "failed")_write_usage_file(self.usage_file, result, failure=failure)diff --git a/hermes_cli/gateway_setup_service.py b/hermes_cli/gateway_setup_service.pyindex a1f1b66fe79..b9c62ae5604 100644--- a/hermes_cli/gateway_setup_service.py+++ b/hermes_cli/gateway_setup_service.py@@ -1,7 +1,10 @@"""Gateway service setup orchestration; runtime startup is separate."""+import loggingimport sys+logger = logging.getLogger(__name__)+SERVICE_INSTALL_QUESTION = ("Install the gateway service so Hermes starts automatically at login ""and keeps scheduled jobs and messaging available?"@@ -98,6 +101,9 @@ def ensure_gateway_service(context: str = "setup", *, interactive: bool = False,except SystemExit:gw.print_warning("Gateway service install did not complete. Retry: hermes gateway install")except Exception as exc:+ # Setup/import boundary: a service-manager failure of any kind degrades to the printed+ # manual retry (False); it never aborts the setup wizard or a restore.+ logger.debug("gateway service setup failed", exc_info=True)gw.print_warning(f"Gateway service setup failed: {exc}")gw.print_info("You can retry manually: hermes gateway install")return Falsediff --git a/hermes_cli/web_server_app.py b/hermes_cli/web_server_app.pyindex 74f4e3445ae..dc54da051c3 100644--- a/hermes_cli/web_server_app.py+++ b/hermes_cli/web_server_app.py@@ -9,7 +9,7 @@ import threadingfrom fastapi import FastAPIfrom hermes_cli.pty_session import run_reaper-_log = logging.getLogger("hermes_cli.web_server")+logger = logging.getLogger("hermes_cli.web_server")def _unlink_pty_markers(app: FastAPI) -> None:@@ -79,7 +79,7 @@ async def standalone_lifespan(app: "FastAPI"):try:tui_gateway.server.install_tui_message_injector()except Exception:- _log.warning("TUI message injector did not install", exc_info=True)+ logger.warning("TUI message injector did not install", exc_info=True)hosted_room_start_cancel = threading.Event()@@ -87,7 +87,7 @@ async def standalone_lifespan(app: "FastAPI"):try:_hosted_groups.start_hosted_room_service()except Exception:- _log.exception("Hosted Group Chat recovery failed during backend startup")+ logger.exception("Hosted Group Chat recovery failed during backend startup")finally:if hosted_room_start_cancel.is_set():_hosted_groups.stop_hosted_room_service(timeout=1.0)@@ -119,7 +119,7 @@ async def standalone_lifespan(app: "FastAPI"):_reap_unsupervised_gateway_orphans(min_age_s=_REAP_MIN_AGE_SECONDS)except Exception:- _log.exception("Desktop startup: orphan gateway reap failed")+ logger.exception("Desktop startup: orphan gateway reap failed")cron_stop = threading.Event()cron_thread = threading.Thread(@@ -166,7 +166,7 @@ async def standalone_lifespan(app: "FastAPI"):try:tui_gateway.server.clear_tui_message_injector()except Exception:- _log.debug("TUI message injector clear skipped", exc_info=True)+ logger.debug("TUI message injector clear skipped", exc_info=True)hosted_room_start_cancel.set()_hosted_groups.stop_hosted_room_service(timeout=5.0)hosted_room_start_thread.join(timeout=1.0)@@ -188,8 +188,10 @@ async def standalone_lifespan(app: "FastAPI"):from hermes_cli.local_runtime.bootstrap import shutdown_local_runtimeshutdown_local_runtime()- except Exception: # noqa: BLE001- pass+ except Exception:+ # Shutdown boundary: a supervisor that fails to stop must not skip the+ # managed-gateway teardown below; log it so the orphan is diagnosable.+ logger.warning("managed local runtime shutdown failed", exc_info=True)if desktop_owned:_terminate_desktop_managed_gateway()diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.pyindex ce77b82df55..cc3a93e521c 100644--- a/hermes_cli/worktree_ops.py+++ b/hermes_cli/worktree_ops.py@@ -1006,7 +1006,7 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:logger.warning(".worktrees/ holds %d tree(s) (%s) — run `hermes worktree list` ""to audit and `hermes worktree prune` to reclaim safely.", count, size_txt)except Exception:- pass+ logger.debug("worktree summary failed", exc_info=True)def _prune_orphaned_branches(repo_root: str, protect: Optional[set] = None) -> None:diff --git a/tui_gateway/command_discovery.py b/tui_gateway/command_discovery.pyindex da8ccb318b4..60e0adfa7cf 100644--- a/tui_gateway/command_discovery.py+++ b/tui_gateway/command_discovery.py@@ -215,19 +215,24 @@ def command_catalog(load_cfg=None, module_loader=import_module, scope=None) -> d_catalog_registry(cat, module_loader)warning = ""skills: dict[str, dict] = {}+ # Each loader is a degrade boundary: user config, third-party plugin registration and skill+ # files can raise anything, and one failing source must never blank the whole palette.with scope if scope is not None else contextlib.nullcontext():try:_catalog_quick_commands(cat, load_cfg)except Exception as e:+ logger.debug("quick_commands discovery failed", exc_info=True)warning = f"quick_commands discovery unavailable: {e}"try:_catalog_plugin_commands(cat, module_loader)except Exception as e:+ logger.debug("plugin command discovery failed", exc_info=True)warning = warning or f"plugin command discovery unavailable: {e}"try:collision_note = _catalog_skills(cat, skills, module_loader) # always runs: skills must list even when a loader failedwarning = warning or collision_noteexcept Exception as e:+ logger.debug("skill discovery failed", exc_info=True)warning = f"skill discovery unavailable: {e}"return {"pairs": cat.pairs, "sub": {k: v[:] for k, v in module_loader("hermes_cli.commands").SUBCOMMANDS.items()},diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.pyindex d77f200e538..80501883f2c 100644--- a/tui_gateway/methods_bot_relay.py+++ b/tui_gateway/methods_bot_relay.py@@ -115,6 +115,9 @@ def _(rid, params: dict, _root=_relay_root) -> dict:try:return _ok(rid, authority_delivery(home, {**forwarded, 'profile': resolved}))except Exception as exc:+ # Boundary: every way the target authority can be unreachable (discovery, ticket, WS,+ # RPC refusal) is the same typed ``runtime_unavailable`` refusal the sender retries on.+ logging.getLogger(__name__).debug("bot_relay.deliver to %s refused", resolved, exc_info=True)return _err(rid, 5094, str(exc), data={'reason': 'runtime_unavailable'})