Skip to content

The agent that grows with you

fix(gateway): run the boot warm-up inside the launch profile's scope under multiplex

Ben Barclaya3c4fc84e9e7
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 30578220b5f..b087cdb207d 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -15,6 +15,7 @@ import os
import signal
import time
from contextlib import suppress
+from contextvars import copy_context
from datetime import datetime
from pathlib import Path
from gateway.config import Platform
@@ -109,7 +110,15 @@ class GatewayStartupMixin:
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."""
+ 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)."""
from gateway.run import _warm_turn_machinery_sync
with _log_suppressed(
logging.WARNING, "Turn-machinery warm-up failed; first inbound turn will initialize lazily",
@@ -117,7 +126,14 @@ class GatewayStartupMixin:
):
loop = asyncio.get_running_loop()
t0 = time.monotonic()
- tool_count = await loop.run_in_executor(None, _warm_turn_machinery_sync)
+ 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)
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.py
index b5c5381964e..11f11325f86 100644
--- a/hermes_cli/auth_nous.py
+++ b/hermes_cli/auth_nous.py
@@ -161,11 +161,18 @@ def _scoped_operator_override(name: str) -> Optional[str]:
raises is a multi-profile call that has lost its profile scope. That call has no authority to
route on the launch profile's value — returning the ambient env there would send a secondary's
tokens 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.
"""
from agent.secret_scope import UnscopedSecretError, get_secret
try:
return get_secret(name)
except 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)
return None
diff --git a/tests/gateway/test_startup_warmup_profile_scope.py b/tests/gateway/test_startup_warmup_profile_scope.py
new file mode 100644
index 00000000000..76bf62a5e1e
--- /dev/null
+++ b/tests/gateway/test_startup_warmup_profile_scope.py
@@ -0,0 +1,86 @@
+"""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.
+"""
+from __future__ import annotations
+
+import asyncio
+import types
+from pathlib import Path
+
+import pytest
+
+from agent import secret_scope
+from gateway import run as gateway_run
+from gateway.run_startup import GatewayStartupMixin
+
+PORTAL = "https://portal.staging-nousresearch.com"
+
+
+def multiplex_home(tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / ".env").write_text(f"HERMES_PORTAL_BASE_URL={PORTAL}\n")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.delenv("HERMES_PORTAL_BASE_URL", raising=False)
+ monkeypatch.delenv("NOUS_PORTAL_BASE_URL", raising=False)
+ secret_scope.set_multiplex_active(True)
+ try:
+ yield home
+ finally:
+ 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() -> int:
+ from hermes_cli.auth_nous import _nous_portal_env_override
+ seen["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"
+ return 1
+
+ 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))
+ return seen
+
+
+def 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."""
+ seen = _run_warmup(monkeypatch, multiplex=True)
+ assert seen["scope_installed"] is True
+ assert 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
+
+
+def test_single_profile_warmup_keeps_environ_semantics(tmp_path, monkeypatch):
+ """Multiplex off: no scope is installed and the process env stays the override source."""
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HERMES_PORTAL_BASE_URL", PORTAL)
+ secret_scope.set_multiplex_active(False)
+ seen = _run_warmup(monkeypatch, multiplex=False)
+ assert seen["scope_installed"] is False
+ assert seen["portal_override"] == PORTAL