The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): one scoped boot-probe hop; one lost-scope warning per resolve
kshitijk4poorc71dbf7078b4
diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex b087cdb207d..ea2e321239a 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -108,32 +108,35 @@ class GatewayStartupMixin:returnself._startup_warmup_task = asyncio.ensure_future(self._warm_turn_prerequisites())+ async def _run_boot_probe_in_launch_scope(self, fn):+ """Run a boot-time probe on the default executor under the LAUNCH profile's scope when+ multiplexing (the ``_discover_gateway_mcp_tools`` shape). Boot probes (``check_fn``s) read profile-scoped secrets; an unscoped read under multiplex fails+ closed, so routing overrides resolve as absent and default routing applies. ``copy_context``+ carries the contextvars across the executor hop; single-profile keeps environ semantics."""+ loop = asyncio.get_running_loop()+ if getattr(self.config, "multiplex_profiles", False):+ from gateway.run import _async_profile_runtime_scope+ from hermes_constants import get_hermes_home+ try:+ async with _async_profile_runtime_scope(get_hermes_home()):+ return await loop.run_in_executor(None, copy_context().run, fn)+ except Exception:+ # Same fallback as load_gateway_config_for_runner: a scope that cannot be built must not+ # abort startup; the probe runs unscoped as it did before.+ logger.debug("multiplex launch-scope entry failed for boot probe %s; running unscoped",+ getattr(fn, "__name__", fn), exc_info=True)+ return await loop.run_in_executor(None, copy_context().run, fn)+async def _warm_turn_prerequisites(self) -> None:"""Initialize turn machinery on an executor thread before the gate opens. Never raises: a- failed warm-up degrades to lazy init and must not block startup.-- Under multiplex the warm-up runs inside the launch profile's ``_profile_runtime_scope`` and- carries that context into the executor thread (the ``_discover_gateway_mcp_tools`` shape).- ``get_tool_definitions`` runs every ``check_fn``, and the vision probe resolves live Nous- runtime credentials; with no scope installed ``get_secret`` fails closed, the Portal / inference- env overrides read as absent, and the refresh token of a non-production Portal is POSTed to the- production Portal — ``invalid_grant`` and a quarantined login ~10 s after every boot, before any- inbound turn (live on hosted staging, 2026-09-16)."""+ failed warm-up degrades to lazy init and must not block startup."""from gateway.run import _warm_turn_machinery_syncwith _log_suppressed(logging.WARNING, "Turn-machinery warm-up failed; first inbound turn will initialize lazily",exc_info=True,):- loop = asyncio.get_running_loop()t0 = time.monotonic()- if getattr(self.config, "multiplex_profiles", False):- from gateway.run import _async_profile_runtime_scope- from hermes_constants import get_hermes_home- async with _async_profile_runtime_scope(get_hermes_home()):- tool_count = await loop.run_in_executor(- None, copy_context().run, _warm_turn_machinery_sync)- else:- tool_count = await loop.run_in_executor(None, _warm_turn_machinery_sync)+ tool_count = await self._run_boot_probe_in_launch_scope(_warm_turn_machinery_sync)logger.info("Turn machinery warmed in %.1fs (%d tool schema(s) materialized)",time.monotonic() - t0, tool_count,diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.pyindex 11f11325f86..d2adc365578 100644--- a/hermes_cli/auth_nous.py+++ b/hermes_cli/auth_nous.py@@ -153,26 +153,31 @@ def _validate_nous_inference_url_from_network(url: Optional[str]) -> Optional[streturn cleaned.rstrip("/")-def _scoped_operator_override(name: str) -> Optional[str]:- """An operator routing override (``NOUS_INFERENCE_BASE_URL``, ``HERMES_PORTAL_BASE_URL``)- resolved through the profile secret scope, or None.+def _scoped_operator_override(*names: str) -> Optional[str]:+ """The first set operator routing override among ``names`` (``NOUS_INFERENCE_BASE_URL``,+ ``HERMES_PORTAL_BASE_URL`` / its ``NOUS_PORTAL_BASE_URL`` alias), resolved through the profile+ secret scope, or None.``get_secret`` already reads ``os.environ`` for a single-profile process, so the only time itraises is a multi-profile call that has lost its profile scope. That call has no authority toroute on the launch profile's value — returning the ambient env there would send a secondary'stokens to the launch profile's Portal or inference host — so the override is simply absent.- Absent is not free: the stored/default routing then applies, so a non-production deployment's- token is spent against the production hosts. Log it by name — the downstream- "ignoring invalid portal_base_url" warning hides which caller lost its scope.+ Absent is not free: default routing then applies, so a non-production deployment's token is+ spent against the production hosts. One WARNING per lost-scope event names the override; the+ downstream "ignoring invalid portal_base_url" line never says which caller lost its scope."""from agent.secret_scope import UnscopedSecretError, get_secrettry:- return get_secret(name)+ for name in names:+ value = get_secret(name)+ if value:+ return value+ return Noneexcept UnscopedSecretError:logger.warning("nous: %s unreadable — no profile secret scope on a multiplexed call; treating the ""override as absent (default routing applies). The caller needs a profile scope binding.",- name)+ "/".join(names))return None@@ -199,8 +204,7 @@ def _nous_portal_env_override() -> Optional[str]:secondary's refresh token to the DEFAULT profile's Portal."""from hermes_cli.auth import _optional_base_url- return _optional_base_url(- _scoped_operator_override("HERMES_PORTAL_BASE_URL") or _scoped_operator_override("NOUS_PORTAL_BASE_URL"))+ return _optional_base_url(_scoped_operator_override("HERMES_PORTAL_BASE_URL", "NOUS_PORTAL_BASE_URL"))def _scope_values(raw_scope: Any) -> set[str]:diff --git a/tests/gateway/test_startup_warmup_profile_scope.py b/tests/gateway/test_startup_warmup_profile_scope.pyindex 76bf62a5e1e..a336ce2784c 100644--- a/tests/gateway/test_startup_warmup_profile_scope.py+++ b/tests/gateway/test_startup_warmup_profile_scope.py@@ -1,18 +1,15 @@-"""The boot turn-machinery warm-up runs inside the launch profile's scope under multiplex.--``get_tool_definitions`` runs every ``check_fn``; the vision probe resolves live Nous runtime-credentials through ``hermes_cli.auth_nous``, whose Portal / inference routing overrides read through-``agent.secret_scope.get_secret``. With multiplex active and no scope installed that read fails-closed, the override is absent, and a non-production Portal's refresh token is POSTed to the-production Portal — ``invalid_grant``, quarantined login, ~10 s after every boot and before any-inbound turn (hosted staging, 2026-09-16). The warm-up must run under the same binding a routed-turn gets, and the binding must reach the executor thread.+"""Boot probes run inside the launch profile's scope under multiplex.++``get_tool_definitions`` runs every ``check_fn``; the vision probe resolves Nous runtime+credentials, whose Portal / inference routing overrides read through ``agent.secret_scope.get_secret``.+With multiplex active and no scope on the executor thread that read fails closed, the override is+absent, and a non-production Portal's refresh token is POSTed to the production Portal. The warm-up+must run under the same binding a routed turn gets, and the binding must reach the executor thread."""from __future__ import annotationsimport asyncioimport types-from pathlib import Pathimport pytest@@ -38,40 +35,46 @@ def multiplex_home(tmp_path, monkeypatch):secret_scope.set_multiplex_active(False)-def _run_warmup(monkeypatch, *, multiplex: bool) -> dict:- """Drive ``_warm_turn_prerequisites`` with the sync warm-up replaced by a probe that records what- the executor thread can see."""- seen: dict = {}-+def _probe(seen: dict):def probe() -> int:from hermes_cli.auth_nous import _nous_portal_env_overrideseen["scope_installed"] = secret_scope._SECRET_SCOPE.get() is not None- try:- seen["portal_override"] = _nous_portal_env_override()- except secret_scope.UnscopedSecretError:- seen["portal_override"] = "UNSCOPED"+ seen["portal_override"] = _nous_portal_env_override()return 1+ return probe+++class _Runner(GatewayStartupMixin):+ def __init__(self, *, multiplex: bool):+ self.config = types.SimpleNamespace(multiplex_profiles=multiplex)+- monkeypatch.setattr(gateway_run, "_warm_turn_machinery_sync", probe)- runner = types.SimpleNamespace(config=types.SimpleNamespace(multiplex_profiles=multiplex))- asyncio.run(GatewayStartupMixin._warm_turn_prerequisites(runner))+def _run_warmup(monkeypatch, *, multiplex: bool) -> dict:+ """Drive ``_warm_turn_prerequisites`` with the sync warm-up replaced by a probe that records what+ the executor thread can see, then what the loop task sees once the warm-up has returned."""+ seen: dict = {}+ monkeypatch.setattr(gateway_run, "_warm_turn_machinery_sync", _probe(seen))++ async def drive() -> None:+ await _Runner(multiplex=multiplex)._warm_turn_prerequisites()+ # Same task as the warm-up (asyncio.run copies the context, so the caller's view proves nothing).+ from hermes_constants import get_hermes_home_override+ seen["scope_after"] = secret_scope._SECRET_SCOPE.get()+ seen["home_override_after"] = get_hermes_home_override()++ asyncio.run(drive())return seendef test_multiplex_warmup_runs_check_fns_inside_the_launch_profile_scope(multiplex_home, monkeypatch):"""The executor thread sees the launch profile's secret scope, so the .env routing override resolves- exactly as it does on a routed turn — never the fail-closed 'absent' that heals to production."""+ exactly as it does on a routed turn — never the fail-closed 'absent' that heals to production. The+ binding is per activity: once the warm-up returns, the loop thread is unscoped again."""seen = _run_warmup(monkeypatch, multiplex=True)assert seen["scope_installed"] is Trueassert seen["portal_override"] == PORTAL---def test_multiplex_warmup_leaves_no_scope_behind(multiplex_home, monkeypatch):- """The binding is per activity: once the warm-up returns, the loop thread is unscoped again."""- _run_warmup(monkeypatch, multiplex=True)- assert secret_scope._SECRET_SCOPE.get() is None- from hermes_constants import get_hermes_home_override- assert get_hermes_home_override() is None+ assert seen["scope_after"] is None+ assert seen["home_override_after"] is Nonedef test_single_profile_warmup_keeps_environ_semantics(tmp_path, monkeypatch):@@ -84,3 +87,4 @@ def test_single_profile_warmup_keeps_environ_semantics(tmp_path, monkeypatch):seen = _run_warmup(monkeypatch, multiplex=False)assert seen["scope_installed"] is Falseassert seen["portal_override"] == PORTAL+