Skip to content

The agent that grows with you

fix(health): clear F811/F841/ASYNC240 and the handle_ws/backup CC growth

Teknium1f7cb4f87157
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index 9b528a4fac1..8adb01a6e62 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -934,6 +934,33 @@ def _import_members(
return _import_members_exclusive(zf, members, prefix, hermes_root, file_count)
+def _import_external_member(
+ zf: zipfile.ZipFile, member: str, home_dir: Path, new_file_mode: int, errors: List[str]
+) -> bool:
+ """Publish one ``_external/`` member under the user's home; False (with ``errors`` appended)
+ when it is a traversal or cannot be written."""
+ target = home_dir / member[len(_EXTERNAL_PREFIX):]
+ # Security: the resolved target must stay under the home dir.
+ try:
+ target.resolve().relative_to(home_dir)
+ except ValueError:
+ errors.append(f" {member}: path traversal blocked")
+ return False
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ _extract_member_atomically(zf, member, target, new_file_mode)
+ # External provider configs commonly hold credentials.
+ if target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES:
+ try:
+ os.chmod(target, 0o600)
+ except OSError:
+ pass
+ return True
+ except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:
+ errors.append(f" {member}: {exc}")
+ return False
+
+
def _import_members_exclusive(
zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int
) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:
@@ -957,29 +984,11 @@ def _import_members_exclusive(
# ``_external/`` arc prefix restores to its original home-relative
# location (e.g. ~/.honcho/config.json), NOT under HERMES_HOME.
if member.startswith(_EXTERNAL_PREFIX):
- ext_rel = member[len(_EXTERNAL_PREFIX):]
- if not ext_rel:
- continue
- target = home_dir / ext_rel
- # Security: the resolved target must stay under the home dir.
- try:
- target.resolve().relative_to(home_dir)
- except ValueError:
- errors.append(f" {member}: path traversal blocked")
+ if not member[len(_EXTERNAL_PREFIX):]:
continue
- try:
- target.parent.mkdir(parents=True, exist_ok=True)
- _extract_member_atomically(zf, member, target, new_file_mode)
- # External provider configs commonly hold credentials.
- if target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES:
- try:
- os.chmod(target, 0o600)
- except OSError:
- pass
+ if _import_external_member(zf, member, home_dir, new_file_mode, errors):
restored += 1
restored_external += 1
- except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:
- errors.append(f" {member}: {exc}")
if restored % 500 == 0:
print(f" {restored}/{file_count} files ...")
continue
@@ -1549,6 +1558,48 @@ def restore_quick_snapshot(
return False
+def _snapshot_epochs_restorable(files, entry_paths) -> bool:
+ """False (logged) when any listed ``state.db`` destination cannot prove its runtime epoch."""
+ for rel in files:
+ entry = entry_paths(rel)
+ if entry and entry[0].exists() and "state.db" in (entry[1].name, entry[1].resolve().name):
+ try:
+ _restore_destination_epoch(entry[1])
+ except OSError as exc:
+ logger.error("%s", exc)
+ return False
+ return True
+
+
+def _restore_snapshot_entry(rel: str, src: Path, dst: Path) -> bool:
+ """Publish one quick-snapshot file over ``dst``; False (logged) when refused or failed."""
+ try:
+ if dst.suffix == ".db":
+ # Restore through SQLite backup API so live connections
+ # (gateway, dashboard, another CLI session) see the
+ # restored data instead of continuing to serve stale
+ # cached pages from a replaced inode (issue #65942).
+ if not _safe_restore_db(src, dst):
+ # Refused, failed, or source failed its integrity check:
+ # dst left as it was. Count as a failure, not a restore.
+ logger.error("Failed to restore %s: refused or source integrity check failed (see previous log)", rel)
+ return False
+ elif rel == "auth.json":
+ # Refresh tokens for these OAuth providers rotate on use. A historical
+ # snapshot can therefore contain a spent pair even though the current
+ # auth.json has the live successor. Restore the historical auth state
+ # while retaining that live single-use grant under the auth-store lock.
+ if not _restore_auth_json(src, dst):
+ logger.error("Failed to restore %s safely", rel)
+ return False
+ else:
+ shutil.copy2(src, dst)
+ return True
+ except (OSError, PermissionError) as exc:
+ logger.error("Failed to restore %s: %s", rel, exc)
+ return False
+
+
def _restore_quick_snapshot_exclusive(snapshot_id: str, home: Path) -> bool:
"""Restore state from a quick snapshot while ``home`` is reserved."""
from gateway.runtime_ownership import exclusive_maintenance
@@ -1602,14 +1653,8 @@ def _restore_quick_snapshot_exclusive(snapshot_id: str, home: Path) -> bool:
with exclusive_maintenance(homes):
# Epoch safety is a whole-profile preflight: copying config first would
# both partially roll back the profile and report a refused DB as success.
- for rel in meta.get("files", {}):
- entry = _entry_paths(rel)
- if entry and entry[0].exists() and "state.db" in (entry[1].name, entry[1].resolve().name):
- try:
- _restore_destination_epoch(entry[1])
- except OSError as exc:
- logger.error("%s", exc)
- return False
+ if not _snapshot_epochs_restorable(meta.get("files", {}), _entry_paths):
+ return False
restored = 0
auth_restore_failed = False
@@ -1628,34 +1673,10 @@ def _restore_quick_snapshot_exclusive(snapshot_id: str, home: Path) -> bool:
continue
dst.parent.mkdir(parents=True, exist_ok=True)
-
- try:
- if dst.suffix == ".db":
- # Restore through SQLite backup API so live connections
- # (gateway, dashboard, another CLI session) see the
- # restored data instead of continuing to serve stale
- # cached pages from a replaced inode (issue #65942).
- if not _safe_restore_db(src, dst):
- # Refused, failed, or source failed its integrity check:
- # dst left as it was. Count as a failure, not a restore.
- logger.error("Failed to restore %s: refused or source integrity check failed (see previous log)", rel)
- continue
- elif rel == "auth.json":
- # Refresh tokens for these OAuth providers rotate on use. A historical
- # snapshot can therefore contain a spent pair even though the current
- # auth.json has the live successor. Restore the historical auth state
- # while retaining that live single-use grant under the auth-store lock.
- if not _restore_auth_json(src, dst):
- logger.error("Failed to restore %s safely", rel)
- auth_restore_failed = True
- continue
- else:
- shutil.copy2(src, dst)
+ if _restore_snapshot_entry(rel, src, dst):
restored += 1
- except (OSError, PermissionError) as exc:
- logger.error("Failed to restore %s: %s", rel, exc)
- if rel == "auth.json":
- auth_restore_failed = True
+ elif rel == "auth.json":
+ auth_restore_failed = True
logger.info("Restored %d files from snapshot %s", restored, snapshot_id)
return restored > 0 and not auth_restore_failed
diff --git a/hermes_cli/cli_single_query.py b/hermes_cli/cli_single_query.py
index b3d686b593a..b3fa8450a12 100644
--- a/hermes_cli/cli_single_query.py
+++ b/hermes_cli/cli_single_query.py
@@ -166,15 +166,17 @@ def _single_query_exit_code(result, *, credentials_rate_limited: bool = False,
``agent.kanban_turn_recovery``) so a whitespace-only value is not a worker here
either — the exit mapping and the recovery gate must agree on what a worker is.
"""
- from cli import _TERMINAL_PROVIDER_REASONS, _TRANSIENT_PROVIDER_REASONS
+ # Late-bound through the ``cli`` facade so a patched ``cli._*_PROVIDER_REASONS`` holds.
+ from cli import _TERMINAL_PROVIDER_REASONS as terminal_reasons
+ from cli import _TRANSIENT_PROVIDER_REASONS as transient_reasons
from agent.kanban_turn_recovery import kanban_task_id
from hermes_cli.turn_exit import turn_exit_code
return turn_exit_code(
result, kanban_worker=kanban_task_id() is not None,
credentials_rate_limited=credentials_rate_limited,
credentials_terminal=credentials_terminal,
- transient_reasons=_TRANSIENT_PROVIDER_REASONS,
- terminal_reasons=_TERMINAL_PROVIDER_REASONS,
+ transient_reasons=transient_reasons,
+ terminal_reasons=terminal_reasons,
)
diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.py
index b4de2b5c688..1cbdc869743 100644
--- a/hermes_cli/gateway_chat.py
+++ b/hermes_cli/gateway_chat.py
@@ -76,6 +76,11 @@ def validate_options(args):
f"\n Example: {_SAFE_MODE_EXAMPLE}")
+def _caller_cwd(args) -> str:
+ """The caller's working directory (``--in`` wins), resolved; filesystem work, so off the loop."""
+ return str(Path(getattr(args, "in_dir", None) or os.getcwd()).expanduser().resolve())
+
+
async def run_gateway_chat(args, emitter=None):
from hermes_cli.gateway_chat_view import GatewayChatView
async with connect_gateway() as client:
@@ -110,7 +115,7 @@ async def run_gateway_chat(args, emitter=None):
policy["title"] = title
if isinstance(policy.get("toolsets"), str):
policy["toolsets"] = [name.strip() for name in policy["toolsets"].split(",") if name.strip()]
- cwd = str(Path(getattr(args, "in_dir", None) or os.getcwd()).expanduser().resolve())
+ cwd = await asyncio.to_thread(_caller_cwd, args)
if "cwd" in parameters:
policy["cwd"] = cwd
elif getattr(args, "in_dir", None):
diff --git a/hermes_cli/kanban_worker_client.py b/hermes_cli/kanban_worker_client.py
index 5d1a1633d1f..871168c83f1 100644
--- a/hermes_cli/kanban_worker_client.py
+++ b/hermes_cli/kanban_worker_client.py
@@ -18,7 +18,8 @@ async def run(params, board_db):
if os.environ.get('HERMES_TUI_GATEWAY_URL'):
raise GatewayClientError('Kanban requires the assigned local profile owner')
async with connect_gateway() as client:
- accepted = await client.rpc('kanban.run', **dict(params, db=str(Path(board_db).resolve())))
+ db = str(await asyncio.to_thread(Path(board_db).resolve))
+ accepted = await client.rpc('kanban.run', **dict(params, db=db))
sid, receipt = accepted['session_id'], accepted['receipt']
print(f'Session: {sid}', file=sys.stderr)
while receipt['status'] not in {'terminal', 'unknown'}:
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index 649e41bc46d..9e207b2bdb0 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -478,7 +478,7 @@ async def upload_chat_image(payload: ChatImageUpload, profile: Optional[str] = N
"""
def _run():
data, mime_type, ext = _decode_chat_image_upload(payload)
- with _profile_scope(profile) as scoped_home:
+ with _profile_scope(profile):
from gateway.platforms.base import get_image_cache_dir
img_dir = get_image_cache_dir()
with _io_errors("Image directory is not writable", "Could not create image directory"):
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index e1da25e6a3c..356ef9cf1f5 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -294,6 +294,46 @@ def _disable_nagle(ws: Any) -> None:
_log.debug("ws TCP_NODELAY skip: %s", exc)
+def _authority_connection(ws: Any, transport: "WSTransport", auth_identity: dict | None, operator: bool):
+ """The session-authority connection for this socket (route scope, else app state), or None
+ when this backend has no authority and requests go to the legacy ``server.dispatch``."""
+ authority = (getattr(ws, 'scope', None) or {}).get('hermes.session_authority') or getattr(
+ getattr(getattr(ws, 'app', None), 'state', None), 'session_authority', None)
+ if authority is None:
+ return None
+ from gateway.session_controls import AuthorityConnection
+ return AuthorityConnection(authority, transport, auth_identity or {}, operator=operator)
+
+
+async def _dispatch_request(authority_connection: Any, req: Any, req_method: Any, transport: "WSTransport") -> Any:
+ """One request through the authority when attached, else the legacy dispatcher."""
+ if authority_connection is None:
+ return await asyncio.to_thread(server.dispatch, req, transport)
+ resp = await authority_connection.dispatch(req)
+ actor = authority_connection.actor
+ if _is_unknown_method(resp) and req_method in server._methods and legacy_fallback_allowed(actor):
+ # Session verbs live on the authority; everything else the sidecar still
+ # registers (pet, wake word, active-session list, connectors) keeps its
+ # legacy handler. A real -32601 reaches the client only for methods
+ # neither side knows, which is what its version-skew notice keys on.
+ resp = await asyncio.to_thread(dispatch_legacy, server, req, transport, actor)
+ return resp
+
+
+def _start_backend_liveness() -> None:
+ """Backend heartbeat refresher + startup orphan sweep (idempotent, once per process); a
+ failure of either is logged and never blocks the connection."""
+ for start, what in (
+ (server._start_backend_heartbeat_refresher, "backend heartbeat refresher start"),
+ (server._schedule_startup_orphan_sweep, "startup orphan sweep scheduling"),
+ ):
+ try:
+ start()
+ # health: allow BLE001 -- liveness boundary; logs the traceback (exc_info) via _log, a name ruff does not treat as a logger
+ except Exception:
+ _log.warning("%s failed", what, exc_info=True)
+
+
class _SendFailed(Exception):
"""Raised by handle_ws._reply when a reply could not be written: ends the read loop."""
@@ -334,18 +374,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
# writes the response itself via transport.write (a separate thread, so that is the safe
# path). Inline handlers return the response dict, written here from the loop.
try:
- if authority_connection is not None:
- resp = await authority_connection.dispatch(req)
- actor = authority_connection.actor
- if (_is_unknown_method(resp) and req_method in server._methods
- and legacy_fallback_allowed(actor)):
- # Session verbs live on the authority; everything else the sidecar still
- # registers (pet, wake word, active-session list, connectors) keeps its
- # legacy handler. A real -32601 reaches the client only for methods
- # neither side knows, which is what its version-skew notice keys on.
- resp = await asyncio.to_thread(dispatch_legacy, server, req, transport, actor)
- else:
- resp = await asyncio.to_thread(server.dispatch, req, transport)
+ resp = await _dispatch_request(authority_connection, req, req_method, transport)
except Exception:
dispatch_crashes += 1
_log.exception("ws dispatch crash peer=%s id=%s method=%s", peer, req_id, req_method)
@@ -376,11 +405,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
_disable_nagle(ws)
_log.info("ws accepted peer=%s", peer)
transport = WSTransport(ws, asyncio.get_running_loop(), peer=peer, auth_identity=auth_identity)
- authority = (getattr(ws, 'scope', None) or {}).get('hermes.session_authority') or getattr(
- getattr(getattr(ws, 'app', None), 'state', None), 'session_authority', None)
- if authority is not None:
- from gateway.session_controls import AuthorityConnection
- authority_connection = AuthorityConnection(authority, transport, auth_identity or {}, operator=operator)
+ authority_connection = _authority_connection(ws, transport, auth_identity, operator)
# resolve_skin() is sync I/O + CPU; pooled so the read loop can drain the frontend's initial RPC burst.
skin_payload = await asyncio.to_thread(server.resolve_skin)
# change_events: this backend broadcasts pet/cron/sessions.changed, so clients can demote legacy
@@ -401,14 +426,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
# Cross-backend liveness: a heartbeat row lets the startup orphan sweep tell "live but idle
# backend" from "truly orphaned". Idempotent and once-per-process, like the orphan sweep (the
# desktop app and web dashboard reach the agent via this sidecar, not entry.main()).
- for start, what in (
- (server._start_backend_heartbeat_refresher, "backend heartbeat refresher start"),
- (server._schedule_startup_orphan_sweep, "startup orphan sweep scheduling"),
- ):
- try:
- start()
- except Exception:
- _log.warning("%s failed", what, exc_info=True)
+ _start_backend_liveness()
if not ready_ok:
disconnect_reason = "ready_send_failed"
send_failures += 1