The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(child-env): one scandir manifest stamp per scrub, file-signature keyed
kshitijk4poorb1206115a2c2
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 8f8cd082d95..ac5a1990f74 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -29,7 +29,7 @@ from contextlib import suppressfrom dataclasses import dataclassfrom decimal import Decimal, InvalidOperationfrom pathlib import Path-from typing import Dict, Any, Optional, List, Tuple, Set+from typing import Dict, Any, Literal, Optional, List, Tuple, Setimport hermes_yaml as yaml@@ -3990,11 +3990,22 @@ def _inject_profile_env_vars() -> None:_inject_profile_env_vars()-def _platform_manifest_paths(home: Optional[Path] = None, source: str = "all"):- """Yield ``(dir_name, manifest_path, require_kind)`` for every platform plugin manifest file.+PlatformManifestSource = Literal["all", "bundled", "user"]+++def _is_plugin_dir_name(name: str) -> bool:+ # Same rule as plugins_discovery.scan_directory: dot dirs and __pycache__-style dunders aren't plugins.+ return not name.startswith(".") and not (name.startswith("__") and name.endswith("__"))+++def _platform_manifest_paths(home: Optional[Path] = None, source: PlatformManifestSource = "all"):+ """Yield ``(dir_name, manifest_path, require_kind, stat)`` for every platform plugin manifest.``source`` is ``"bundled"`` (shipped ``plugins/platforms/*``), ``"user"`` (``<home>/plugins/platforms/*`` plus flat ``<home>/plugins/*`` installs, which must declare ``kind: platform``,- #46600) or ``"all"``. ``home`` defaults to the bound Hermes home."""+ #46600) or ``"all"``. ``home`` defaults to the bound Hermes home. A directory that cannot be+ listed or searched yields ``(name, None, require_kind, error)``: a plugin there can't load+ either, so callers skip it. One ``scandir`` per root and one ``stat`` per candidate, because+ the child-env scrub stamps these on every spawn."""roots = []if source in ("all", "bundled"):roots.append((get_project_root() / "plugins" / "platforms", False))@@ -4002,42 +4013,54 @@ def _platform_manifest_paths(home: Optional[Path] = None, source: str = "all"):user_plugins = (home if home is not None else get_hermes_home()) / "plugins"roots += [(user_plugins / "platforms", False), (user_plugins, True)]for root, require_kind in roots:- if not root.is_dir():+ try:+ with os.scandir(root) as it:+ entries = [e for e in it if _is_plugin_dir_name(e.name)]+ except (FileNotFoundError, NotADirectoryError):+ continue+ except OSError as exc:+ yield str(root), None, require_kind, exccontinue- for child in root.iterdir():- if child.name.startswith((".", "__")):- continue # __pycache__, .git, editor state: never a plugin+ for entry in entries:try:- manifest_path = next(- (p for p in (child / "plugin.yaml", child / "plugin.yml") if child.is_dir() and p.exists()), None)- except OSError as exc: # an unsearchable dir cannot be loaded as a plugin either- logger.warning("Skipping unreadable plugin directory %s: %s", child, exc)+ if not entry.is_dir():+ continue+ except OSError:continue- if manifest_path is not None:- yield child.name, manifest_path, require_kind+ for file_name in ("plugin.yaml", "plugin.yml"):+ path = Path(entry.path) / file_name+ try:+ st = os.stat(path)+ except FileNotFoundError:+ continue+ except OSError as exc: # the dir itself is not searchable+ yield entry.name, None, require_kind, exc+ break+ yield entry.name, path, require_kind, st+ break-def platform_manifest_stamp(home: Optional[Path] = None, source: str = "user") -> tuple:- """``(path, mtime_ns)`` of every platform plugin manifest file: changes whenever one is added,- removed or edited in place, so a cache keyed on it never serves a stale declaration."""- stamp = []- for _dir, path, _kind in _platform_manifest_paths(home, source):- try:- stamp.append((str(path), path.stat().st_mtime_ns))- except OSError:- stamp.append((str(path), None)) # the strict read reports it- return tuple(stamp)+def platform_manifest_stamp(home: Optional[Path] = None) -> tuple:+ """Change-detection key over every user platform plugin manifest of ``home`` (path plus+ :func:`utils.file_signature`): it changes when one is added, removed, replaced or edited in+ place, so a cache keyed on it never serves a stale declaration."""+ return tuple((name, str(path), file_signature(st) if path is not None else type(st).__name__)+ for name, path, _kind, st in _platform_manifest_paths(home, "user"))-def _platform_plugin_manifests(home: Optional[Path] = None, source: str = "all", *, strict: bool = False):+def _platform_plugin_manifests(home: Optional[Path] = None, source: PlatformManifestSource = "all", *,+ strict: bool = False):"""Yield ``(dir_name, manifest_dict)`` for every platform plugin manifest (see:func:`_platform_manifest_paths`). ``strict`` raises when a manifest cannot be read instead ofskipping it: the child-env scrub must not lose a declared secret to an I/O error. Only amanifest known to be a platform's counts (the bundled and ``plugins/platforms/`` dirs); aflat ``plugins/*`` manifest proves it is one only by its content, so an unreadable one is- skipped with a warning. A manifest that does not parse declares nothing (its adapter cannot- load either) and is skipped."""- for dir_name, manifest_path, require_kind in _platform_manifest_paths(home, source):+ skipped with a warning, as is an unsearchable plugin directory. A manifest that does not+ parse declares nothing (its adapter cannot load either) and is skipped."""+ for dir_name, manifest_path, require_kind, st in _platform_manifest_paths(home, source):+ if manifest_path is None:+ logger.warning("Skipping unreadable plugin directory %s: %s", dir_name, st)+ continuetry:with open(manifest_path, "r", encoding="utf-8-sig") as f:manifest = fast_safe_load(f) or {}@@ -4082,7 +4105,7 @@ def _manifest_secret_envs(manifests) -> frozenset[str]:return frozenset(names - {n.upper() for n in CORE_DECLARED_ENV_NAMES})-def platform_manifest_secret_envs(home: Optional[Path] = None, source: str = "user", *,+def platform_manifest_secret_envs(home: Optional[Path] = None, source: PlatformManifestSource = "user", *,strict: bool = False) -> frozenset[str]:"""Secret env names declared by one source's platform plugin manifests: ``"user"`` reads only``home``'s user-installed plugins, which belong to that profile alone; ``"bundled"`` returns@@ -4128,5 +4151,4 @@ def _inject_platform_plugin_env_vars() -> "frozenset[str] | None":# one: the config form keeps the core entry, and the child-env scrub keeps a plugin that lists# OPENAI_API_KEY from turning a provider key into an adapter secret.CORE_DECLARED_ENV_NAMES: frozenset[str] = frozenset(OPTIONAL_ENV_VARS)-BUNDLED_PLATFORM_SECRET_ENVS: "frozenset[str] | None" = None-BUNDLED_PLATFORM_SECRET_ENVS = _inject_platform_plugin_env_vars()+BUNDLED_PLATFORM_SECRET_ENVS: "frozenset[str] | None" = _inject_platform_plugin_env_vars()diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.pyindex 234329abb89..a4d743f2399 100644--- a/tests/tools/test_local_env_blocklist.py+++ b/tests/tools/test_local_env_blocklist.py@@ -169,10 +169,33 @@ def test_user_platform_plugin_secrets_belong_to_their_own_profile(child_env, montoken = set_hermes_home_override(a)try:assert "CHATX_WEBHOOK_KEY" not in local.hermes_subprocess_env(inherit_credentials=True)+ # Removing the plugin releases its names, and a symlinked alias of the home shares one entry.+ manifest.unlink()+ assert "CHATX_WEBHOOK_KEY" in local.hermes_subprocess_env(inherit_credentials=True)finally:reset_hermes_home_override(token)[email protected]("posix") # symlinks+def test_a_symlinked_home_alias_shares_its_profiles_plugin_declarations(child_env, monkeypatch):+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ from tools.environments import local_env_policy as policy+ home = child_env / "profiles" / "a"+ _user_platform_plugin(home, "chatx", "CHATX_SIGNING_SECRET")+ alias = child_env / "a-alias"+ alias.symlink_to(home, target_is_directory=True)+ monkeypatch.setenv("CHATX_SIGNING_SECRET", "fake-value")+ sizes = []+ for bound in (home, alias):+ token = set_hermes_home_override(bound)+ try:+ assert "CHATX_SIGNING_SECRET" not in local.hermes_subprocess_env(inherit_credentials=True)+ finally:+ reset_hermes_home_override(token)+ sizes.append(len(policy._HOME_ADAPTER_SECRET_CACHE))+ assert sizes[0] == sizes[1]++@pytest.mark.skipif(os.name == "nt" or os.geteuid() == 0, # windows-footgun: ok — short-circuits on ntreason="needs POSIX permissions as non-root")def test_unreadable_platform_manifest_fails_closed(tmp_path):@@ -192,8 +215,8 @@ def test_unreadable_platform_manifest_fails_closed(tmp_path):finally:manifest.chmod(0o644)# Not provably a platform's, so no reason to fail: an unsearchable plugin dir (a root-owned- # __pycache__ or plugin in a volume) or an unreadable flat plugins/* manifest.- locked = [tmp_path / "plugins" / "__pycache__", tmp_path / "plugins" / "memx"]+ # plugin in a volume) or an unreadable flat plugins/* manifest.+ locked = [tmp_path / "plugins" / "lockedx", tmp_path / "plugins" / "memx"]for d in locked:d.mkdir()(locked[1] / "plugin.yaml").write_text("kind: memory\n", encoding="utf-8")@@ -206,6 +229,27 @@ def test_unreadable_platform_manifest_fails_closed(tmp_path):(locked[1] / "plugin.yaml").chmod(0o644)+def test_unreadable_bundled_manifest_fails_the_policy_instead_of_dropping_it(monkeypatch):+ """The import-time read keeps the bundled secret set only when every bundled manifest was+ read; otherwise the policy's strict re-read raises rather than building without them."""+ import builtins+ import hermes_cli.config as cfg+ target = next(path for _name, path, _kind, _st in cfg._platform_manifest_paths(source="bundled") if path)+ real_open = builtins.open++ def denying_open(file, *args, **kwargs):+ if str(file) == str(target):+ raise PermissionError(13, "Permission denied", str(file))+ return real_open(file, *args, **kwargs)++ monkeypatch.setattr(cfg, "OPTIONAL_ENV_VARS", dict(cfg.OPTIONAL_ENV_VARS))+ monkeypatch.setattr(builtins, "open", denying_open)+ assert cfg._inject_platform_plugin_env_vars() is None+ monkeypatch.setattr(cfg, "BUNDLED_PLATFORM_SECRET_ENVS", None)+ with pytest.raises(PermissionError):+ cfg.platform_manifest_secret_envs(source="bundled", strict=True)++def test_inheriting_child_gets_provider_keys_but_never_adapter_secrets(child_env, monkeypatch):# inherit_credentials is the narrow grant for model-driving CLIs: provider keys only.granted = ["OPENAI_API_KEY", "NOUS_API_KEY", *OPERATOR_SECRETS]diff --git a/tools/environments/local.py b/tools/environments/local.pyindex bdf81b32af0..efc60952238 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -24,7 +24,7 @@ from tools.environments.local_env_policy import ( # noqa: F401 — _HERMES_PROV_ALWAYS_STRIP_FOLDED, _ALWAYS_STRIP_KEYS, _HERMES_PROVIDER_ENV_BLOCKLIST, _HERMES_PROVIDER_ENV_FORCE_PREFIX,_is_hermes_internal_secret, _is_provider_env_blocklisted, _is_terminal_first_party_env,_home_adapter_secret_env, _matches_terminal_first_party_prefix, _plugin_terminal_env_strip_keys,- _registered_adapter_secret_env,+ _registered_adapter_secret_env, _registry_adapter_secret_env,strip_profile_gate_env)from tools.environments.local_pythonpath import (_build_hermes_repo_root_aliases, _strip_hermes_owned_pythonpath_and_runtime_markers)@@ -335,8 +335,9 @@ def _scrub_credentials(env: dict, *, inherit_credentials: bool) -> dict:"""Tier 1 (always) and, unless ``inherit_credentials``, Tier 2 provider/tool credentials, in place."""# Credential names fold to uppercase for membership: on Windows the env block# itself is case-insensitive, so a lowercase-stored ``gh_token`` IS GH_TOKEN.- strip_folded = _ALWAYS_STRIP_FOLDED | {k.upper() for k in _plugin_terminal_env_strip_keys()} | _home_adapter_secret_env()- registered = _registered_adapter_secret_env()+ home_secrets = _home_adapter_secret_env() # one manifest stamp per scrub+ strip_folded = _ALWAYS_STRIP_FOLDED | {k.upper() for k in _plugin_terminal_env_strip_keys()} | home_secrets+ registered = _registry_adapter_secret_env() | home_secretsfor key in list(env):if (key.upper() in strip_foldedor (not inherit_credentials and _is_provider_env_blocklisted(key, registered))diff --git a/tools/environments/local_env_policy.py b/tools/environments/local_env_policy.pyindex 22efb8205a6..74d2f7927f8 100644--- a/tools/environments/local_env_policy.py+++ b/tools/environments/local_env_policy.py@@ -138,17 +138,22 @@ def _home_adapter_secret_env() -> frozenset:return cached[1]-def _registered_adapter_secret_env() -> frozenset:- """Per-call adapter secrets: the bound profile's user-plugin declarations (Tier 1, see- :func:`_home_adapter_secret_env`) plus the secret-named ``required_env`` of the adapters- registered in the current profile scope. Registered names are Tier 2 only: ``required_env`` is- an unchecked setup list, so a plugin naming OPENAI_API_KEY must not strip it from credentialed- children. No blanket fallback: a registry error surfaces instead of an empty (fail-open) set."""+def _registry_adapter_secret_env() -> frozenset:+ """Secret-named ``required_env`` of the adapters registered in the current profile scope.+ Tier 2 only: ``required_env`` is an unchecked setup list, so a plugin naming OPENAI_API_KEY+ must not strip it from credentialed children. No blanket fallback: a registry error surfaces+ instead of an empty (fail-open) set."""from gateway.platform_registry import platform_registryfrom hermes_cli.config import PLATFORM_SECRET_ENV_SUFFIXES- registered = {n.upper() for n in platform_registry.required_env_names()- if n.upper().endswith(PLATFORM_SECRET_ENV_SUFFIXES)}- return frozenset(registered) | _home_adapter_secret_env()+ return frozenset(n.upper() for n in platform_registry.required_env_names()+ if n.upper().endswith(PLATFORM_SECRET_ENV_SUFFIXES))+++def _registered_adapter_secret_env() -> frozenset:+ """Per-call adapter secrets: the bound profile's user-plugin declarations (Tier 1, see+ :func:`_home_adapter_secret_env`) plus the registered adapters' (Tier 2,+ :func:`_registry_adapter_secret_env`)."""+ return _registry_adapter_secret_env() | _home_adapter_secret_env()def _is_provider_env_blocklisted(name: str, _registered: "frozenset | None" = None) -> bool: