The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
chore(health): offset growth, bound the ACL subprocesses, scope the update ACL repair
Teknium52652b56d476
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 6bdd59be4ce..8fb0c9aaed4 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -18,8 +18,8 @@ import timeimport uuidimport weakreffrom abc import ABC, abstractmethod-from urllib.parse import urlsplitfrom hermes_dir_acl import make_user_dir, unusable_dir_remedy+from gateway.platforms.base_log_safety import safe_url_for_log # re-exported: adapters import it from herefrom utils import normalize_proxy_urlfrom agent.i18n import t@@ -463,27 +463,6 @@ def unauthorized_action_notice(platform: Any) -> str:return t("gateway.unauthorized.action_notice", platform=str(name or "<platform>"))-def safe_url_for_log(url: str, max_len: int = 80) -> str:- """Return a URL string safe for logs (no query/fragment/userinfo)."""- raw = str(url) if max_len > 0 and url is not None else ""- if not raw:- return ""- try:- parsed = urlsplit(raw)- except Exception:- return raw[:max_len]- safe = raw- if parsed.scheme and parsed.netloc:- # Strip potential embedded credentials (user:pass@host).- path = parsed.path or ""- basename = path.rsplit("/", 1)[-1]- tail = "" if path in ("", "/") else f"/.../{basename}" if basename else "/..."- safe = f"{parsed.scheme}://{parsed.netloc.rsplit('@', 1)[-1]}{tail}"- if len(safe) <= max_len:- return safe- return "." * max_len if max_len <= 3 else f"{safe[:max_len - 3]}..."--async def _ssrf_redirect_guard(response):"""Re-validate each redirect target (a public URL 302-ing to http://169.254.169.254/ wouldbypass the pre-flight is_safe_url()). Async because httpx awaits response event hooks."""diff --git a/gateway/platforms/base_log_safety.py b/gateway/platforms/base_log_safety.pynew file mode 100644index 00000000000..db1e69bfa43--- /dev/null+++ b/gateway/platforms/base_log_safety.py@@ -0,0 +1,23 @@+"""Log-safe rendering split from :mod:`gateway.platforms.base` (re-exported there)."""+from urllib.parse import urlsplit+++def safe_url_for_log(url: str, max_len: int = 80) -> str:+ """Return a URL string safe for logs (no query/fragment/userinfo)."""+ raw = str(url) if max_len > 0 and url is not None else ""+ if not raw:+ return ""+ try:+ parsed = urlsplit(raw)+ except Exception:+ return raw[:max_len]+ safe = raw+ if parsed.scheme and parsed.netloc:+ # Strip potential embedded credentials (user:pass@host).+ path = parsed.path or ""+ basename = path.rsplit("/", 1)[-1]+ tail = "" if path in ("", "/") else f"/.../{basename}" if basename else "/..."+ safe = f"{parsed.scheme}://{parsed.netloc.rsplit('@', 1)[-1]}{tail}"+ if len(safe) <= max_len:+ return safe+ return "." * max_len if max_len <= 3 else f"{safe[:max_len - 3]}..."diff --git a/gateway/status.py b/gateway/status.pyindex 64a2058f3e6..084b34cae7d 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -20,7 +20,7 @@ from dataclasses import dataclassfrom datetime import datetime, timezone, UTCfrom pathlib import Pathfrom typing import Any, Callable, NamedTuple, Optional-from hermes_dir_acl import make_user_dir, unusable_dir_remedy+from hermes_dir_acl import make_user_dirfrom gateway.status_inline_source import (command_line_runs_inline_source,@@ -29,6 +29,9 @@ from gateway.status_inline_source import ()from hermes_constants import _get_platform_default_hermes_home, get_hermes_home, get_process_hermes_homefrom hermes_cli._subprocess_compat import pid_exists_stdlib+from gateway.status_scoped_locks import ( # re-exported: the public scoped-lock API lives on gateway.status+ ScopedLockDirUnusable, _unusable_lock_dir, _warned_unusable_lock_dirs, release_all_scoped_locks,+ release_scoped_lock)from utils import atomic_json_writeif sys.platform == "win32":@@ -1542,31 +1545,6 @@ def _process_is_stopped(pid: int) -> bool:return False-class ScopedLockDirUnusable(PermissionError):- """This token cannot create, read or replace locks in the scoped-lock dir (#134889 W2).-- On Windows an elevated install/update creates ``gateway-locks`` owned by Administrators with- no entry for the user; the same user's non-elevated gateway then gets ``Permission denied`` on- every token lock. Retrying cannot fix an ACL, so the adapter reports it once, names the repair- and stays down instead of crash-looping. A ``PermissionError`` subclass so existing callers- keep their handling.- """---# Lock dirs already reported unusable by this process: WARNING once per dir, DEBUG after, since the-# reconnect watcher and every adapter sharing the dir re-enter the acquire path.-_warned_unusable_lock_dirs: set[Path] = set()---def _unusable_lock_dir(lock_dir: Path, exc: PermissionError) -> ScopedLockDirUnusable:- level = logging.DEBUG if lock_dir in _warned_unusable_lock_dirs else logging.WARNING- _warned_unusable_lock_dirs.add(lock_dir)- logger.log(level, "Gateway lock directory %s is not usable by this process (%s); it was likely created "- "by an elevated (administrator) Hermes. Platforms that need a token lock stay down until it "- "is repaired. To repair, %s", lock_dir, exc, unusable_dir_remedy(lock_dir))- return ScopedLockDirUnusable(exc.errno, f"gateway lock directory is not usable: {exc}", str(lock_dir))--def acquire_scoped_lock(scope: str, identity: str, metadata: Optional[dict[str, Any]] = None) -> tuple[bool, Optional[dict[str, Any]]]:@@ -1586,7 +1564,6 @@ def acquire_scoped_lock(def _acquire_scoped_lock_at(lock_path: Path, scope: str, identity: str, metadata: Optional[dict[str, Any]]) -> tuple[bool, Optional[dict[str, Any]]]:- from hermes_dir_acl import make_user_dirmake_user_dir(lock_path.parent, parents=True, exist_ok=True)# An existing lock this token may not read (left by an elevated gateway) must raise here:# ``_read_json_file`` would call it empty and O_EXCL "in use", a conflict with no holder.@@ -1634,36 +1611,6 @@ def _acquire_scoped_lock_at(return True, None-def release_scoped_lock(scope: str, identity: str) -> None:- """Release a scope lock owned by this PID. No start_time equality check: on-disk null vs a live- fingerprint would wedge reconnects."""- lock_path = _get_scope_lock_path(scope, identity)- if (_read_json_file(lock_path) or {}).get("pid") == os.getpid():- _unlink_quietly(lock_path)---def release_all_scoped_locks(- *, owner_pid: Optional[int] = None, owner_start_time: Optional[int] = None-) -> int:- """Remove scoped lock files (--replace cleanup); returns the count removed. With ``owner_pid``- only that gateway's records go (``owner_start_time`` narrows against PID reuse)."""- lock_dir = _get_lock_dir()- if not lock_dir.exists():- return 0- removed = 0- for lock_file in lock_dir.glob("*.lock"):- if owner_pid is not None:- record = _read_json_file(lock_file) or {}- if _pid_from_record(record) != owner_pid or (- owner_start_time is not None and record.get("start_time") != owner_start_time- ):- continue- with contextlib.suppress(OSError):- lock_file.unlink(missing_ok=True)- removed += 1- return removed--# ── --replace takeover marker ─────────────────────────────────────────# SIGTERM exits the gateway with code 1 so Restart=on-failure revives it after unexpected# kills -- which would also revive a --replace target (flap loop against the replacer). Thediff --git a/gateway/status_scoped_locks.py b/gateway/status_scoped_locks.pynew file mode 100644index 00000000000..094a9a6845f--- /dev/null+++ b/gateway/status_scoped_locks.py@@ -0,0 +1,71 @@+"""Scoped-lock helpers split from :mod:`gateway.status` (re-exported there): the unusable lock-dir+report (#134889 W2) and lock release. Status-module helpers are read through the module at call time+so tests that patch ``gateway.status`` keep steering them."""+from __future__ import annotations++import contextlib+import logging+import os+from pathlib import Path+from typing import Optional++from hermes_dir_acl import unusable_dir_remedy++log = logging.getLogger("gateway.status")+++class ScopedLockDirUnusable(PermissionError):+ """This token cannot create, read or replace locks in the scoped-lock dir (#134889 W2).++ On Windows an elevated install/update creates ``gateway-locks`` owned by Administrators with+ no entry for the user; the same user's non-elevated gateway then gets ``Permission denied`` on+ every token lock. Retrying cannot fix an ACL, so the adapter reports it once, names the repair+ and stays down instead of crash-looping. A ``PermissionError`` subclass so existing callers+ keep their handling.+ """+++# Lock dirs already reported unusable by this process: WARNING once per dir, DEBUG after, since the+# reconnect watcher and every adapter sharing the dir re-enter the acquire path.+_warned_unusable_lock_dirs: set[Path] = set()+++def _unusable_lock_dir(lock_dir: Path, exc: PermissionError) -> ScopedLockDirUnusable:+ level = logging.DEBUG if lock_dir in _warned_unusable_lock_dirs else logging.WARNING+ _warned_unusable_lock_dirs.add(lock_dir)+ log.log(level, "Gateway lock directory %s is not usable by this process (%s); it was likely created "+ "by an elevated (administrator) Hermes. Platforms that need a token lock stay down until it "+ "is repaired. To repair, %s", lock_dir, exc, unusable_dir_remedy(lock_dir))+ return ScopedLockDirUnusable(exc.errno, f"gateway lock directory is not usable: {exc}", str(lock_dir))+++def release_scoped_lock(scope: str, identity: str) -> None:+ """Release a scope lock owned by this PID. No start_time equality check: on-disk null vs a live+ fingerprint would wedge reconnects."""+ from gateway import status as _status+ lock_path = _status._get_scope_lock_path(scope, identity)+ if (_status._read_json_file(lock_path) or {}).get("pid") == os.getpid():+ _status._unlink_quietly(lock_path)+++def release_all_scoped_locks(+ *, owner_pid: Optional[int] = None, owner_start_time: Optional[int] = None+) -> int:+ """Remove scoped lock files (--replace cleanup); returns the count removed. With ``owner_pid``+ only that gateway's records go (``owner_start_time`` narrows against PID reuse)."""+ from gateway import status as _status+ lock_dir = _status._get_lock_dir()+ if not lock_dir.exists():+ return 0+ removed = 0+ for lock_file in lock_dir.glob("*.lock"):+ if owner_pid is not None:+ record = _status._read_json_file(lock_file) or {}+ if _status._pid_from_record(record) != owner_pid or (+ owner_start_time is not None and record.get("start_time") != owner_start_time+ ):+ continue+ with contextlib.suppress(OSError):+ lock_file.unlink(missing_ok=True)+ removed += 1+ return removeddiff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 002e15d2b71..12a8864f681 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -16,7 +16,6 @@ from contextlib import contextmanager, suppressfrom datetime import datetime, timezone, UTCfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Tuple-from hermes_dir_acl import make_user_dirfrom hermes_constants import (LOCAL_RUNTIME_ROOT_DIRS, _get_platform_default_hermes_home, get_default_hermes_root, get_hermes_home,@@ -1306,10 +1305,10 @@ def _create_quick_snapshot_locked(snap_dir = root / snap_idstaging_dir = root / f".{snap_id}.{os.getpid()}.partial"shutil.rmtree(staging_dir, ignore_errors=True)- make_user_dir(root, parents=True, exist_ok=True, mode=0o700)+ root.mkdir(parents=True, exist_ok=True, mode=0o700)if os.name != "nt":os.chmod(root, 0o700)- make_user_dir(staging_dir, mode=0o700, exist_ok=False)+ staging_dir.mkdir(mode=0o700, exist_ok=False)logger.info("quick snapshot phase=copy status=started id=%s", snap_id)manifest: dict[str, int] = {} # rel_path -> file sizediff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex a3f7e0e1f57..80419ba6dd1 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -34,7 +34,7 @@ def _current_windows_user_sid() -> str:"""Return the process user's SID without depending on localized account names."""result = subprocess.run(["whoami", "/user", "/fo", "csv", "/nh"],- capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=False, timeout=30,)if result.returncode:detail = result.stderr.strip() or f"whoami exited {result.returncode}"@@ -56,12 +56,17 @@ def _repair_windows_home_acl() -> None:"""if sys.platform != "win32":return+ from hermes_dir_acl import process_is_elevated+ if not process_is_elevated():+ # Only an elevated update leaves Administrators-only entries, and only an elevated token+ # can rewrite them; a recursive icacls over the whole home on every update costs minutes.+ returnfrom hermes_constants import get_hermes_homehome = get_hermes_home()result = subprocess.run(_windows_home_acl_grant_command(home, _current_windows_user_sid()),- capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=False, timeout=900,)if result.returncode:detail = result.stderr.strip() or result.stdout.strip() or f"icacls exited {result.returncode}"diff --git a/hermes_dir_acl.py b/hermes_dir_acl.pyindex b8bd125afad..bfcd0bf9ce0 100644--- a/hermes_dir_acl.py+++ b/hermes_dir_acl.py@@ -86,12 +86,12 @@ def _grant_with_pywin32(path: Path) -> None:def _grant_with_icacls(path: Path) -> None:whoami = subprocess.run(["whoami", "/user", "/fo", "csv", "/nh"], capture_output=True, text=True,- check=True, encoding="utf-8", errors="replace")+ check=True, encoding="utf-8", errors="replace", timeout=30)sid = whoami.stdout.strip().rsplit(",", 1)[-1].strip().strip('"')if not sid.upper().startswith("S-1-"):raise OSError(f"could not resolve the current user SID from whoami: {whoami.stdout!r}")subprocess.run(["icacls", str(path), "/grant", f"*{sid}:(OI)(CI)F", "/Q"], capture_output=True,- check=True)+ check=True, timeout=60)def grant_user_access(path: str | Path) -> bool:diff --git a/tests/hermes_cli/test_update_windows_home_acl.py b/tests/hermes_cli/test_update_windows_home_acl.pyindex 4d304f189af..43b6f085fdf 100644--- a/tests/hermes_cli/test_update_windows_home_acl.py+++ b/tests/hermes_cli/test_update_windows_home_acl.py@@ -15,3 +15,26 @@ def test_windows_home_acl_grant_targets_the_current_user_sid_recursively(tmp_pat"/C","/Q",]+++def test_repair_runs_only_from_an_elevated_update(monkeypatch, tmp_path):+ """A non-elevated update created nothing Administrators-only and could not rewrite it anyway;+ the recursive icacls over the whole home is skipped there."""+ import subprocess+ import sys++ import hermes_dir_acl+ from hermes_cli import update_cmd_maint as maint++ calls = []+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(maint, "_current_windows_user_sid", lambda: "S-1-5-21-1-2-3-1001")+ monkeypatch.setattr(subprocess, "run", lambda argv, **kw: calls.append((argv, kw)) or+ subprocess.CompletedProcess(argv, 0, "", ""))+ monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: False)+ maint._repair_windows_home_acl()+ assert calls == []+ monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: True)+ maint._repair_windows_home_acl()+ assert calls and calls[0][0][0] == "icacls" and calls[0][1]["timeout"]