The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): compact mem_trim/migrate/managed_scope/main_agent_cmds
Teknium1ee583aa612b
diff --git a/hermes_cli/managed_scope.py b/hermes_cli/managed_scope.pyindex 89c89a276ce..80182df2795 100644--- a/hermes_cli/managed_scope.py+++ b/hermes_cli/managed_scope.py@@ -1,12 +1,10 @@"""Managed scope — IT-pushed, user-immutable config & env layer.-This is DISTINCT from ``hermes_cli.config.is_managed()`` / ``HERMES_MANAGED``, which is a coarse-package-manager write-lock (declarative-distro / formula installs). That lock blocks all mutation;-this layer injects specific immutable values. The two are independent and may coexist.--v1 enforcement is filesystem permissions only — see ``docs/design/managed-scope.md`` §7. v1 is-Linux/POSIX-first; ``get_managed_dir()`` is the single seam for adding macOS / Windows native-locations later.+DISTINCT from ``hermes_cli.config.is_managed()`` / ``HERMES_MANAGED`` (a coarse package-manager+write-lock that blocks all mutation); this layer injects specific immutable values. The two are+independent and may coexist. v1 enforcement is filesystem permissions only (see+``docs/design/managed-scope.md`` §7); ``get_managed_dir()`` is the single seam for adding+macOS / Windows native locations later."""from __future__ import annotations@@ -21,8 +19,7 @@ import yamllogger = logging.getLogger(__name__)-# POSIX default. Other-platform locations are a deliberate v2 item; when added,-# they belong ONLY inside get_managed_dir().+# POSIX default. Other-platform locations belong ONLY inside get_managed_dir()._DEFAULT_MANAGED_DIR = Path("/etc/hermes")_CACHE_LOCK = threading.Lock()@@ -32,24 +29,17 @@ _ENV_CACHE: Dict[str, tuple] = {}def _under_pytest() -> bool:- """True when running inside the test suite.-- Used to ignore the system default ``/etc/hermes`` under tests so a real managed scope on a- dev/CI box can't leak policy into the suite. An explicit ``HERMES_MANAGED_DIR`` is still- honored because that override runs before this guard.- """+ """True inside the test suite: ignore the system ``/etc/hermes`` so a real managed scope on a+ dev/CI box can't leak policy into the suite. An explicit ``HERMES_MANAGED_DIR`` still wins."""return "PYTEST_CURRENT_TEST" in os.environdef get_managed_dir() -> Optional[Path]:"""Resolve the managed-scope directory, or None when no scope is present.- Resolution (highest priority first): 1. ``$HERMES_MANAGED_DIR`` — deployment/bootstrap path- override (IT-only; never persisted to any .env). Honored only when set to a non-empty value AND- the directory exists. 2. ``/etc/hermes`` — POSIX default, when it exists.-- A non-existent directory at either tier resolves to None (no managed scope), which is the common- case and must be cheap + side-effect-free.+ Priority: ``$HERMES_MANAGED_DIR`` (IT-only bootstrap override; never persisted to any .env;+ honored only when non-empty AND the directory exists), then ``/etc/hermes`` when it exists.+ A missing directory resolves to None — the common case, so it must be cheap + side-effect-free."""override = os.environ.get("HERMES_MANAGED_DIR", "").strip()if override:@@ -69,11 +59,11 @@ def invalidate_managed_cache() -> None:def _cached_read(path: Path, cache: Dict[str, tuple], parse):- """Shared (mtime_ns, size)-keyed read. Returns a deepcopy of the parsed value.+ """Shared (mtime_ns, size)-keyed read; returns a deepcopy of the parsed value.- Returns ``None`` when the file is absent or fails to parse (fail-open). A parse failure is- logged LOUDLY — the admin needs to know their policy isn't being applied — but never raises, so- a malformed managed file can't brick startup.+ ``None`` when the file is absent or fails to parse (fail-open). A parse failure is logged+ LOUDLY — the admin needs to know their policy isn't applied — but never raises, so a malformed+ managed file can't brick startup."""try:st = path.stat()@@ -121,15 +111,11 @@ def load_managed_env() -> Dict[str, str]:def apply_managed_overlay(config: dict) -> dict:"""Overlay administrator-pinned config values on top of an already-built dict.- * expand the managed config's ``${VAR}`` refs against the PROCESS env only (never user-config-- defined refs), so a user cannot shadow a managed literal via a ${VAR} they control; * normalize- the managed config's root ``model`` key (a bare ``model: x/y`` string is promoted to- ``model.default``) so it can't clobber the dict shape callers expect; * leaf-level deep-merge- managed ON TOP, so managed wins per-leaf while sibling keys stay user-controlled.-- Fail-open: returns ``config`` unchanged if no managed scope is present or on any error — managed- scope must never break a caller's startup. Mutates and returns ``config`` (callers pass a dict- they own).+ ``${VAR}`` refs in the managed config expand against the PROCESS env only, so a user cannot+ shadow a managed literal via a ref they control; a bare root ``model: x/y`` string is promoted+ to ``model.default`` so it can't clobber the dict shape callers expect; managed values+ deep-merge ON TOP per leaf while sibling keys stay user-controlled. Fail-open: returns+ ``config`` unchanged when no scope is present or on any error. Mutates and returns ``config``."""try:managed = load_managed_config()@@ -139,12 +125,9 @@ def apply_managed_overlay(config: dict) -> dict:from hermes_cli.config import _deep_merge, _expand_env_vars, _normalize_root_model_keysmanaged_expanded = _normalize_root_model_keys(_expand_env_vars(managed))- # A bare ``model: x/y`` string in the managed file must merge as- # ``model.default`` — otherwise _deep_merge would replace the caller's- # ``model`` dict with a string and break every ``cfg["model"]["..."]``- # read. _normalize_root_model_keys only promotes the string when there- # are root provider/base_url keys to migrate, so handle the bare case- # here (matches cli.py's own string-model handling).+ # _normalize_root_model_keys only promotes the string when root provider/base_url+ # keys exist to migrate; handle the bare case here (matches cli.py) so _deep_merge+ # never replaces the caller's ``model`` dict with a string.if isinstance(managed_expanded.get("model"), str):managed_expanded = dict(managed_expanded)managed_expanded["model"] = {"default": managed_expanded["model"]}diff --git a/hermes_cli/mem_trim.py b/hermes_cli/mem_trim.pyindex 761e5e9b970..cf414fd7c7c 100644--- a/hermes_cli/mem_trim.py+++ b/hermes_cli/mem_trim.py@@ -23,6 +23,11 @@ logger = logging.getLogger(__name__)_DEFAULT_COOLDOWN_SECONDS = 60.0_DEFAULT_LOG_EVERY_N = 1_DEFAULT_INFO_LOG_MIN_DELTA_MB = 0.0+# Even forced trims honor a short floor: AIAgent.close() forces a trim, and delegate+# batches close N child subagents back-to-back in the SAME process — without a floor+# that stacks N+1 uncooled full gc.collect() passes (50-500ms each in a large gateway+# process). 5s coalesces the burst while keeping the parent's final close-trim effective.+_FORCE_FLOOR_SECONDS = 5.0_trim_lock = threading.Lock()_last_trim_monotonic = 0.0_probe_done = False@@ -31,15 +36,12 @@ _trim_call_count = 0def _config_settings() -> tuple[bool, float, int, float]:- """Return fail-open settings from the normal Hermes config path."""- enabled = True+ """Return fail-open ``(enabled, cooldown, log_every_n, info_log_min_delta_mb)`` from config."""settings: Any = Nonetry:- # Read-only access: settings are only .get()ed and coerced, never- # mutated — use the no-deepcopy variant. This runs on EVERY trim- # attempt (before the cooldown check), and generating a full-config- # deepcopy per attempt is exactly the allocator garbage this module- # exists to release.+ # Read-only, no-deepcopy variant: this runs on EVERY trim attempt (before the+ # cooldown check), and a full-config deepcopy per attempt is exactly the+ # allocator garbage this module exists to release.from hermes_cli.config import load_config_readonlyconfig = load_config_readonly() or {}@@ -49,8 +51,7 @@ def _config_settings() -> tuple[bool, float, int, float]:passif not isinstance(settings, dict):settings = {}- if isinstance(settings.get("enabled"), bool):- enabled = settings["enabled"]+ enabled = settings["enabled"] if isinstance(settings.get("enabled"), bool) else Truereturn (enabled,_cooldown_seconds(settings.get("cooldown_seconds")),@@ -84,10 +85,9 @@ def _read_proc_status() -> str | None:def collect_memory_snapshot(history_bytes: int | None = None) -> dict[str, int | None]:- """Return lightweight process-memory telemetry for trim logs and canaries.+ """Lightweight process-memory telemetry for trim logs and canaries.- ``VmRSS`` and ``RssAnon`` are Linux-only best effort fields. The helper is intentionally- dependency-free so allocation recovery never requires psutil.+ ``VmRSS`` / ``RssAnon`` are Linux-only best effort; deliberately psutil-free."""snapshot: dict[str, int | None] = {"rss_kib": None,@@ -112,8 +112,8 @@ def _should_log_trim(*, force: bool, log_every_n: int, call_count: int, before: dict[str, int | None],after: dict[str, int | None], info_log_min_delta_mb: float,) -> bool:- # trim_memory calls this only after malloc_trim reported success. A forced- # successful trim is an explicit observability event, regardless of RSS.+ # Called only after malloc_trim reported success; a forced successful trim is an+ # explicit observability event regardless of RSS.if force:return Trueif call_count % log_every_n:@@ -136,8 +136,7 @@ def _probe_glibc_malloc_trim() -> Callable[[int], int] | None:try:if platform.libc_ver()[0].lower() != "glibc":return None- libc = ctypes.CDLL(None)- trim = libc.malloc_trim+ trim = ctypes.CDLL(None).malloc_trimtrim.argtypes = [ctypes.c_size_t]trim.restype = ctypes.c_int_malloc_trim = trim@@ -169,15 +168,8 @@ def trim_memory(return Falsenow = time.monotonic()cooldown = configured_cooldown if cooldown_seconds is None else _cooldown_seconds(cooldown_seconds)- if not force and _last_trim_monotonic and now - _last_trim_monotonic < cooldown:- return False- # Even forced trims honor a short floor: AIAgent.close() forces a trim,- # and delegate batches close N child subagents back-to-back in the SAME- # process — without a floor that stacks N+1 uncooled full gc.collect()- # passes (50-500ms each in a large gateway process). 5s coalesces the- # burst while keeping the parent's final close-trim effective.- _FORCE_FLOOR_SECONDS = 5.0- if force and _last_trim_monotonic and now - _last_trim_monotonic < _FORCE_FLOOR_SECONDS:+ since_last = now - _last_trim_monotonic+ if _last_trim_monotonic and since_last < (_FORCE_FLOOR_SECONDS if force else cooldown):return False# Record the attempt before calling into libc so repeated failures do not# turn every turn boundary into an expensive full collection.diff --git a/hermes_cli/migrate.py b/hermes_cli/migrate.pyindex 81afa057c5e..be152681133 100644--- a/hermes_cli/migrate.py+++ b/hermes_cli/migrate.py@@ -15,14 +15,18 @@ from hermes_cli.config import load_configdef cmd_migrate(args: Any) -> int:"""Dispatcher for ``hermes migrate <subtype>``."""- sub = getattr(args, "migrate_type", None)- if sub == "xai":+ if getattr(args, "migrate_type", None) == "xai":return cmd_migrate_xai(args)print("usage: hermes migrate xai [--apply] [--no-backup]", file=sys.stderr)return 2+def _fail(message: str) -> int:+ print(f" {color('✗', Colors.RED)} {message}", file=sys.stderr)+ return 1++def cmd_migrate_xai(args: Any) -> int:"""Run xAI May-15 model migration in dry-run or apply mode."""from hermes_cli.xai_retirement import (@@ -35,15 +39,10 @@ def cmd_migrate_xai(args: Any) -> int:apply = bool(getattr(args, "apply", False))no_backup = bool(getattr(args, "no_backup", False))-- config = load_config()- issues = find_retired_xai_refs(config)+ issues = find_retired_xai_refs(load_config())print()- print(color(- f"◆ xAI Model Retirement Migration ({RETIREMENT_DATE})",- Colors.CYAN, Colors.BOLD,- ))+ print(color(f"◆ xAI Model Retirement Migration ({RETIREMENT_DATE})", Colors.CYAN, Colors.BOLD))print()if not issues:@@ -70,25 +69,12 @@ def cmd_migrate_xai(args: Any) -> int:return 0if not config_path or not config_path.exists():- print(- f" {color('✗', Colors.RED)} Could not locate config.yaml "- f"(looked at: {config_path})",- file=sys.stderr,- )- return 1+ return _fail(f"Could not locate config.yaml (looked at: {config_path})")try:- result = apply_migration(- config_path=config_path,- issues=issues,- backup=not no_backup,- )+ result = apply_migration(config_path=config_path, issues=issues, backup=not no_backup)except Exception as exc:- print(- f" {color('✗', Colors.RED)} Migration failed: {exc}",- file=sys.stderr,- )- return 1+ return _fail(f"Migration failed: {exc}")if not result.config_changed:print(f" {color('⚠', Colors.YELLOW)} No changes written.")@@ -101,10 +87,7 @@ def cmd_migrate_xai(args: Any) -> int:f"slot(s) in {result.file_path}")print()- print(color(- "Run `hermes doctor` to confirm no retired xAI models remain.",- Colors.DIM,- ))+ print(color("Run `hermes doctor` to confirm no retired xAI models remain.", Colors.DIM))return 0