Skip to content

The agent that grows with you

fix(multiplex): close the profile-scope holes the scope machinery misses

teknium1c718267ef3ce
diff --git a/gateway/run.py b/gateway/run.py
index 38b5c95ca44..2e442bd94ff 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -4834,22 +4834,42 @@ async def _await_thread_exit(
return not thread.is_alive()
-async def _shutdown_mcp_servers_nonblocking(timeout: float = 5.0) -> bool:
+async def _shutdown_mcp_servers_nonblocking(timeout: float = 5.0, config: Any = None) -> bool:
"""Close MCP servers off-loop with a bounded wait; True when done within ``timeout``.
``shutdown_mcp_servers()`` can block ~15s; on the loop thread short-grace supervisors (s6 3s)
SIGKILL us before ``mark_exited()`` runs, so every later boot reports a phantom unclean death.
On timeout shutdown proceeds and the daemon thread is left to finish or die.
+ Teardown is per served profile, under that profile's runtime scope — the mirror of startup
+ discovery (``_discover_mcp_tools_for_profiles``) and of the periodic reconcile chore. A
+ server's close path reads its own config/credentials at call time, so an unscoped shutdown on
+ a bare thread resolved every served profile's teardown against the LAUNCH home. The trailing
+ wildcard call (under the launch profile's own scope) stops the shared loop and reaps anything
+ the per-profile passes did not own.
+
See #82874.
"""
+ from tui_gateway.launch_profile_policy import launch_profile_scope_if_multiplexed
+
+ profile_homes = (
+ _multiplex_profile_homes(config) if getattr(config, "multiplex_profiles", False) else [])
+
def _do() -> None:
+ from tools.mcp_tool_common import _core
+ from tools.mcp_tool_lifecycle import shutdown_mcp_servers
+ for profile_name, profile_home in profile_homes:
+ try:
+ with _profile_runtime_scope(Path(profile_home), hydrate_secrets=False):
+ shutdown_mcp_servers(scope=_core._mcp_registry_scope())
+ except Exception:
+ logger.debug("MCP shutdown raised for profile '%s'", profile_name, exc_info=True)
try:
- from tools.mcp_tool_lifecycle import shutdown_mcp_servers
- shutdown_mcp_servers()
+ with launch_profile_scope_if_multiplexed():
+ shutdown_mcp_servers()
except Exception:
logger.debug("MCP shutdown raised", exc_info=True)
- thread = threading.Thread(target=_do, name="mcp-shutdown", daemon=True)
+ thread = threading.Thread(target=copy_context().run, args=(_do,), name="mcp-shutdown", daemon=True)
thread.start()
done = await _await_thread_exit(thread, timeout=timeout)
if not done:
@@ -5455,7 +5475,7 @@ async def _start_gateway_shutdown_tail(
_planned_stop_watcher_thread.join(timeout=2)
with suppress(Exception):
- await _shutdown_mcp_servers_nonblocking()
+ await _shutdown_mcp_servers_nonblocking(config=getattr(runner, "config", None))
# The failure verdict comes AFTER the cooperative teardown: returning early here leaked the
# cron ticker + housekeeping threads (and open MCP connections) for embedded callers (#12175).
@@ -5602,7 +5622,7 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
try:
await runner.wait_for_shutdown()
with suppress(Exception):
- await _shutdown_mcp_servers_nonblocking()
+ await _shutdown_mcp_servers_nonblocking(config=getattr(runner, "config", None))
return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])
finally:
_shutdown_gateway_health_export(runner)
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 921e7d83088..70c6cba359a 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -516,7 +516,7 @@ class GatewayAdapterLifecycleMixin:
# A row still 'running' at startup died mid-dispatch and blocks request_handoff until reclaimed.
def _scope(profile_home): # local: tests bind this watcher onto bare SimpleNamespace runners
- return GatewayAdapterLifecycleMixin._scope_or_null(_async_profile_runtime_scope, profile_home)
+ return GatewayAdapterLifecycleMixin._async_scope_or_null(_async_profile_runtime_scope, profile_home)
for _pname, _phome in _handoff_watch_scopes(self):
with _log_suppressed(logging.DEBUG, "Stale-handoff reclaim failed", exc_info=True):
@@ -1378,8 +1378,27 @@ class GatewayAdapterLifecycleMixin:
@staticmethod
def _scope_or_null(scope_factory, profile_home):
- """``scope_factory(profile_home)`` or a nullcontext when the profile home is unknown."""
- return scope_factory(profile_home) if profile_home is not None else contextlib.nullcontext()
+ """``scope_factory(profile_home)`` for a known profile home, else the LAUNCH profile's own
+ scope once this process multiplexes.
+
+ ``None`` here means "no routed profile for this body" — the launch profile's own work, or a
+ profile name that no longer resolves. Returning a bare ``nullcontext()`` made the launch
+ profile the one tenant that ran with ambient ``os.environ`` and the process home, which a
+ secondary's context may have poisoned; under the one-process-per-host ruling it is a tenant
+ like any other. Single-profile hosts are unchanged: the helper is a no-op until activation.
+ """
+ if profile_home is not None:
+ return scope_factory(profile_home)
+ from tui_gateway.launch_profile_policy import launch_profile_scope_if_multiplexed
+ return launch_profile_scope_if_multiplexed()
+
+ @staticmethod
+ def _async_scope_or_null(scope_factory, profile_home):
+ """``async with`` twin of :meth:`_scope_or_null` (for ``_async_profile_runtime_scope``)."""
+ if profile_home is not None:
+ return scope_factory(profile_home)
+ from tui_gateway.launch_profile_policy import async_launch_profile_scope_if_multiplexed
+ return async_launch_profile_scope_if_multiplexed()
def _canonicalize(self, source, *, transport_profile: Optional[str] = None,
primary_home: Optional[Path] = None):
@@ -1411,7 +1430,7 @@ class GatewayAdapterLifecycleMixin:
async def _handler(event):
self._canonicalize(getattr(event, "source", None), transport_profile=profile_name)
- async with self._scope_or_null(_async_profile_runtime_scope, profile_home):
+ async with self._async_scope_or_null(_async_profile_runtime_scope, profile_home):
return await self._handle_message(event)
return _handler
@@ -1424,7 +1443,7 @@ class GatewayAdapterLifecycleMixin:
async def _handler(event, _session_key):
self._canonicalize(event.source, transport_profile=profile_name)
- async with self._scope_or_null(_async_profile_runtime_scope, profile_home):
+ async with self._async_scope_or_null(_async_profile_runtime_scope, profile_home):
return await self._handle_active_session_busy_message(event, self._session_key_for_source(event.source))
return _handler
diff --git a/gateway/run_goals.py b/gateway/run_goals.py
index 9f6adf037e6..31412fd5d79 100644
--- a/gateway/run_goals.py
+++ b/gateway/run_goals.py
@@ -466,8 +466,12 @@ class GatewayGoalsMixin:
warned_no_route: set = set()
def _scope(profile_home):
- return (_async_profile_runtime_scope(profile_home) if profile_home is not None
- else nullcontext())
+ # profile_home None = the launch profile's own store; once the process multiplexes it
+ # binds its own scope instead of running on ambient env (see _scope_or_null).
+ if profile_home is not None:
+ return _async_profile_runtime_scope(profile_home)
+ from tui_gateway.launch_profile_policy import async_launch_profile_scope_if_multiplexed
+ return async_launch_profile_scope_if_multiplexed()
async def _scan_one_store(profile_name: Optional[str]) -> None:
from hermes_cli.loops import list_active_loops
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index eaf3e00ccee..6fdde98e63d 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -1438,10 +1438,14 @@ class GatewayNotificationsMixin:
from hermes_constants import get_hermes_home_override
source = self._build_process_event_source(evt)
if source is None or not getattr(source, "profile", None):
- return contextlib.nullcontext()
+ # No routed profile: the launch profile's own completion. Bind ITS scope once the
+ # process multiplexes — unscoped, a fail-closed ledger read raises on a legitimate
+ # launch-profile event (no-op while single-profile).
+ from tui_gateway.launch_profile_policy import async_launch_profile_scope_if_multiplexed
+ return async_launch_profile_scope_if_multiplexed()
profile_home = self._resolve_profile_home_for_source(source)
if get_hermes_home_override() == str(profile_home):
- return contextlib.nullcontext()
+ return contextlib.nullcontext() # already inside this profile's scope
return _async_profile_runtime_scope(profile_home)
async def _deliver_completion_notification(
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index 220884319f8..06df26be986 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -192,41 +192,50 @@ class GatewayProfileReconcileMixin:
async def _unserve_profile(self, name: str, home: "Path") -> None:
"""Stop and unroute one deleted profile: cancel its reconnects, tear down its adapters, drop its
- bookkeeping and release this process's handles into its home so the deleter's rmtree succeeds."""
- from gateway.run import _write_runtime_status_quiet
+ bookkeeping and release this process's handles into its home so the deleter's rmtree succeeds.
+
+ The whole teardown runs inside the DELETED profile's own runtime scope: adapter disconnect
+ hooks, the agent-cache eviction (provider/memory shutdown) and the state/memory handle
+ release all read config and credentials at call time, and this coroutine runs on the
+ reconcile task with no profile bound — unscoped they resolved against the LAUNCH home, so a
+ teardown hook needing this profile's credential failed closed (or, worse, borrowed the launch
+ profile's). Secrets are not re-hydrated: teardown must not block the loop on a source fetch.
+ """
+ from gateway.run import _profile_runtime_scope, _write_runtime_status_quiet
pending = (getattr(self, "_profile_failed_platforms", None) or {}).pop(name, None) or {}
tasks = [t for t in pending.values() if isinstance(t, asyncio.Task) and not t.done()]
for task in tasks:
task.cancel()
if tasks:
await asyncio.wait(tasks, timeout=self._adapter_disconnect_timeout_secs())
- adapters = (getattr(self, "_profile_adapters", None) or {}).pop(name, None) or {}
- for platform, adapter in list(adapters.items()):
- await self._bounded_adapter_teardown(adapter, platform, profile=name)
- # Its ``<name>:<platform>`` runtime entries describe a profile that no longer exists.
- _write_runtime_status_quiet(drop_profile_platforms=name)
- for attr in ("pairing_stores", "_busy_text_modes_by_profile", "_busy_input_modes_by_profile",
- "_busy_text_timing_by_profile", "_human_delay_by_profile"):
- store = getattr(self, attr, None)
- if isinstance(store, dict):
- store.pop(name, None)
- if isinstance(self._served_profile_homes, dict):
- self._served_profile_homes.pop(name, None)
- if isinstance(self._served_profile_signatures, dict):
- self._served_profile_signatures.pop(name, None)
- from gateway.session import _session_key_namespace
- prefix = _session_key_namespace(name) + ":"
- cache = getattr(self, "_agent_cache", None)
- for key in [k for k in list(cache or {}) if str(k).startswith(prefix)]:
- with _log_suppressed(logging.DEBUG, "agent eviction failed for %s", key, exc_info=True):
- self._evict_cached_agent(key)
- with _log_suppressed(logging.DEBUG, "profile handle release failed", exc_info=True):
- from hermes_state_registry import close_all_under
- close_all_under(home)
- with _log_suppressed(logging.DEBUG, "memory-store release failed", exc_info=True):
- from plugins.memory.holographic.store import MemoryStore
- MemoryStore.release_all_under(home)
- logger.info("[MULTIPLEX] Profile '%s' deleted — %d adapter(s) stopped and unrouted", name, len(adapters))
+ with _profile_runtime_scope(Path(home), hydrate_secrets=False):
+ adapters = (getattr(self, "_profile_adapters", None) or {}).pop(name, None) or {}
+ for platform, adapter in list(adapters.items()):
+ await self._bounded_adapter_teardown(adapter, platform, profile=name)
+ # Its ``<name>:<platform>`` runtime entries describe a profile that no longer exists.
+ _write_runtime_status_quiet(drop_profile_platforms=name)
+ for attr in ("pairing_stores", "_busy_text_modes_by_profile", "_busy_input_modes_by_profile",
+ "_busy_text_timing_by_profile", "_human_delay_by_profile"):
+ store = getattr(self, attr, None)
+ if isinstance(store, dict):
+ store.pop(name, None)
+ if isinstance(self._served_profile_homes, dict):
+ self._served_profile_homes.pop(name, None)
+ if isinstance(self._served_profile_signatures, dict):
+ self._served_profile_signatures.pop(name, None)
+ from gateway.session import _session_key_namespace
+ prefix = _session_key_namespace(name) + ":"
+ cache = getattr(self, "_agent_cache", None)
+ for key in [k for k in list(cache or {}) if str(k).startswith(prefix)]:
+ with _log_suppressed(logging.DEBUG, "agent eviction failed for %s", key, exc_info=True):
+ self._evict_cached_agent(key)
+ with _log_suppressed(logging.DEBUG, "profile handle release failed", exc_info=True):
+ from hermes_state_registry import close_all_under
+ close_all_under(home)
+ with _log_suppressed(logging.DEBUG, "memory-store release failed", exc_info=True):
+ from plugins.memory.holographic.store import MemoryStore
+ MemoryStore.release_all_under(home)
+ logger.info("[MULTIPLEX] Profile '%s' deleted — %d adapter(s) stopped and unrouted", name, len(adapters))
def _mcp_config_reconciler(runner=None):
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 8053b36bc0e..9db244ffb56 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -2267,12 +2267,8 @@ class GatewayTurnMixin:
(#112878). The launch profile is a profile too: bind its ``.env`` over the env frozen at
activation (a key injected by systemd / ``op run`` has no file to rebuild it from), never a
secondary's scope and never live ``os.environ``."""
- from agent.secret_scope import is_multiplex_active
- if not is_multiplex_active():
- return nullcontext()
- from hermes_constants import get_process_hermes_home
- from tui_gateway.launch_profile_policy import launch_profile_runtime_scope
- return launch_profile_runtime_scope(get_process_hermes_home())
+ from tui_gateway.launch_profile_policy import launch_profile_scope_if_multiplexed
+ return launch_profile_scope_if_multiplexed()
def _media_delivery_scope_for_source(self, source: SessionSource):
"""Home + terminal-policy scope for validating a turn's MEDIA / local-file paths on the
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index bfc8b2b3aa3..d19ea4ba256 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -2571,6 +2571,47 @@ def _worker_terminal_timeout_env(
return str(desired)
+def _worker_profile_scope(hermes_home: str, *, bind_home: bool = True):
+ """Bind an assigned profile's runtime scope (secrets + terminal policy, optionally home) for
+ one dispatch-side read or spawn-env build.
+
+ The dispatcher runs detached from any turn, so nothing binds a profile for it: ``load_config``,
+ the toolset probes' ``get_secret`` reads and ``build_subprocess_env``'s passthrough resolution
+ all fall back to the LAUNCH profile's ambient ``os.environ`` / ``TERMINAL_*``. Binding was
+ previously conditional on ``is_multiplex_active()`` and skipped the terminal scope entirely, so
+ a worker for profile B inherited whatever TERMINAL_* the host process happened to carry.
+
+ ``bind_home=False`` for the spawn-env build: which variables may cross into a child is the
+ DISPATCHER's ``terminal.env_passthrough`` policy (#109494) — only their VALUES come from the
+ assignee's scope. Toolset resolution does bind the home, as it always has.
+
+ The secret mapping is never widened: a profile that is not this process's own home gets its own
+ ``.env`` + external sources ONLY, while the launch home keeps its established
+ env-over-``.env`` precedence (``launch_secret_scope``) so systemd / ``op run`` injection still
+ resolves for a standalone dispatcher.
+ """
+ from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope
+ from hermes_constants import get_process_hermes_home, reset_hermes_home_override, set_hermes_home_override
+ from tools.terminal_scope import install_profile_terminal_scope, reset_terminal_scope
+ from tui_gateway.launch_profile_policy import launch_secret_scope, launch_terminal_env
+
+ home = Path(hermes_home)
+ is_launch_home = str(home.resolve()) == str(Path(get_process_hermes_home()).resolve())
+ home_token = set_hermes_home_override(str(home)) if bind_home else None
+ secret_token = set_secret_scope(
+ launch_secret_scope(home) if is_launch_home else build_profile_secret_scope(home))
+ terminal_token = install_profile_terminal_scope(
+ home, env_overlay=launch_terminal_env() if is_launch_home else None)
+ try:
+ yield
+ finally:
+ reset_terminal_scope(terminal_token)
+ reset_secret_scope(secret_token)
+ if home_token is not None:
+ reset_hermes_home_override(home_token)
+
+
def _resolve_worker_cli_toolsets(hermes_home: Optional[str]) -> Optional[list[str]]:
"""Return the assigned profile's effective CLI toolsets for a worker.
@@ -2583,25 +2624,12 @@ def _resolve_worker_cli_toolsets(hermes_home: Optional[str]) -> Optional[list[st
if not hermes_home:
return None
try:
- from agent.secret_scope import (
- build_profile_secret_scope, is_multiplex_active, reset_secret_scope, set_secret_scope)
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
from hermes_cli.config import load_config
from hermes_cli.tools_config import _get_platform_tools
- token = set_hermes_home_override(hermes_home)
- # Toolset availability probes read credentials (``get_secret``); under multiplex an
- # unscoped read raises and the pin was silently dropped for every worker.
- secret_token = (
- set_secret_scope(build_profile_secret_scope(Path(hermes_home)))
- if is_multiplex_active() else None)
- try:
+ with _worker_profile_scope(hermes_home):
cfg = load_config()
toolsets = sorted(_get_platform_tools(cfg, "cli"))
- finally:
- if secret_token is not None:
- reset_secret_scope(secret_token)
- reset_hermes_home_override(token)
return toolsets or None
except Exception as exc:
_kb._log.debug(
@@ -2744,8 +2772,7 @@ def _default_spawn(task: Task, workspace: str, *, board: Optional[str] = None) -
profile_arg = normalize_profile_name(task.assignee)
- from agent.secret_scope import (
- build_profile_secret_scope, is_multiplex_active, reset_secret_scope, set_secret_scope)
+ from agent.secret_scope import is_multiplex_active
from tools.environments.local import build_subprocess_env, strip_launch_profile_env
try:
@@ -2756,21 +2783,16 @@ def _default_spawn(task: Task, workspace: str, *, board: Optional[str] = None) -
profile_home = None
multiplex_active = is_multiplex_active()
- # build_subprocess_env's secret scrub resolves terminal.env_passthrough vars
- # through get_secret(), which raises UnscopedSecretError with no profile scope
- # installed while multiplexing is on — mirrors _resolve_worker_cli_toolsets's
- # own scope-then-read ordering a few functions up in this module.
- secret_token = (
- set_secret_scope(build_profile_secret_scope(Path(profile_home)))
- if multiplex_active and profile_home else None)
- try:
+ # build_subprocess_env's secret scrub resolves terminal.env_passthrough vars through
+ # get_secret(), and its TERMINAL_* reads go through the terminal scope. Unscoped, both read the
+ # LAUNCH profile's ambient environment for a worker spawned on B's behalf — so bind B's secret
+ # + terminal scope, not just secrets and not only under multiplex.
+ with (_worker_profile_scope(profile_home, bind_home=False) if profile_home
+ else contextlib.nullcontext()):
env = build_subprocess_env(
scrub_secrets=multiplex_active,
inherit_profile_home=True,
)
- finally:
- if secret_token is not None:
- reset_secret_scope(secret_token)
# The dispatcher is detached from every conversation; its worker must never
# inherit routing mirrored by a previous gateway turn.
from gateway.session_context import _VAR_MAP
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 81859abc0bb..2c568bf31bf 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -1436,6 +1436,18 @@ def start_server(
_apply_ssh_session_token(ssh_session_token or "")
_apply_ssh_owner_nonce(ssh_owner_nonce)
+ # One host process serves every profile, and this one can be asked for any of them via
+ # ``?profile=``. Decide at boot instead of on the first such request: activation is one-way, so
+ # everything the backend had already done by then (idle-reaper flushes, hosted rooms, cron)
+ # stayed on single-profile assumptions and was never re-scoped. No-op on a single-profile host.
+ try:
+ from tui_gateway.launch_profile_policy import activate_multi_profile_hosting_eagerly
+
+ if activate_multi_profile_hosting_eagerly():
+ _log.debug("multi-profile hosting activated at startup (more than one profile home)")
+ except Exception as exc:
+ _log.debug("eager multi-profile activation skipped: %s", exc)
+
# Dashboard-mode starts don't route through main.py's `serve` path, which
# applies the same RLIMIT_NOFILE floor (policy in resource_limits, #81547).
from hermes_cli.resource_limits import apply_nofile_soft_limit
diff --git a/tests/gateway/test_launch_profile_scope_fallback.py b/tests/gateway/test_launch_profile_scope_fallback.py
new file mode 100644
index 00000000000..ee50409ae08
--- /dev/null
+++ b/tests/gateway/test_launch_profile_scope_fallback.py
@@ -0,0 +1,50 @@
+"""The launch profile is a tenant: a body with no routed profile binds ITS scope, not ambient env.
+
+``GatewayAdapterLifecycleMixin._scope_or_null`` used to return ``contextlib.nullcontext()`` whenever
+the profile home was ``None`` — the launch profile's own handoff reclaims, reconnect attention
+flags and platform events therefore ran completely unscoped on a multiplexing host: a legitimate
+launch-profile ``get_secret`` failed closed, and anything reading process env picked up whatever a
+secondary context had left there.
+"""
+import pytest
+
+from agent import secret_scope
+from agent.secret_scope import get_secret
+from gateway.run_adapters import GatewayAdapterLifecycleMixin
+from tui_gateway import launch_profile_policy
+
+POISON = "LAUNCHSCOPE_TEST_KEY"
+
+
+def multiplexing_host(tmp_path, monkeypatch):
+ launch = tmp_path / "launch"
+ launch.mkdir()
+ (launch / ".env").write_text(f"{POISON}=launch-dotenv\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", False)
+ monkeypatch.setattr(launch_profile_policy, "_snapshot", None)
+ launch_profile_policy.activate_multi_profile_hosting()
+ # A secondary's context poisons the process env AFTER activation; the frozen snapshot must win.
+ monkeypatch.setenv(POISON, "secondary-poison")
+ return launch
+
+
+def test_scope_or_null_binds_launch_profile_when_no_routed_home(multiplexing_host):
+ with GatewayAdapterLifecycleMixin._scope_or_null(lambda home: None, None):
+ # Base: nullcontext -> UnscopedSecretError on a legitimate launch-profile read.
+ assert get_secret(POISON) == "launch-dotenv"
+
+
+async def test_async_scope_or_null_binds_launch_profile_when_no_routed_home(multiplexing_host):
+ async with GatewayAdapterLifecycleMixin._async_scope_or_null(lambda home: None, None):
+ assert get_secret(POISON) == "launch-dotenv"
+
+
+def test_single_profile_host_keeps_ambient_precedence(monkeypatch):
+ """Never activated -> no binding at all, so ``os.environ`` precedence is byte-identical."""
+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", False)
+ monkeypatch.setenv(POISON, "ambient")
+ with GatewayAdapterLifecycleMixin._scope_or_null(lambda home: None, None):
+ assert get_secret(POISON) == "ambient"
diff --git a/tests/gateway/test_startup_restart_race.py b/tests/gateway/test_startup_restart_race.py
index dccb94f54b4..71573634315 100644
--- a/tests/gateway/test_startup_restart_race.py
+++ b/tests/gateway/test_startup_restart_race.py
@@ -339,7 +339,7 @@ async def test_failure_exit_still_stops_cron_housekeeping_and_mcp(monkeypatch):
watcher = threading.Thread(target=watcher_stop.wait, daemon=True)
watcher.start()
- async def fake_mcp_shutdown():
+ async def fake_mcp_shutdown(*_args, **_kwargs):
stopped.append("mcp")
monkeypatch.setattr(gateway_run, "_shutdown_mcp_servers_nonblocking", fake_mcp_shutdown)
diff --git a/tests/hermes_cli/test_kanban_worker_terminal_scope.py b/tests/hermes_cli/test_kanban_worker_terminal_scope.py
new file mode 100644
index 00000000000..a6974ba541c
--- /dev/null
+++ b/tests/hermes_cli/test_kanban_worker_terminal_scope.py
@@ -0,0 +1,68 @@
+"""A kanban worker spawned for profile B builds its env under B's terminal scope, not the ambient one.
+
+``_default_spawn`` bound only a secret scope, and only when ``is_multiplex_active()``. The dispatcher
+runs detached from any turn, so ``build_subprocess_env`` (terminal ``env_passthrough`` resolution)
+and ``_resolve_worker_cli_toolsets`` read whatever ``TERMINAL_*`` the host process happened to carry
+— the LAUNCH profile's policy applied to another tenant's worker.
+"""
+import subprocess # noqa: F401 — imported so a stray real spawn is obvious in a traceback
+
+import pytest
+
+from hermes_cli import kanban_db_dispatch
+from tools.terminal_scope import get_terminal_scope
+
+
+class _StopSpawn(Exception):
+ """Abort ``_default_spawn`` at the env-build seam so no worker process is created."""
+
+
+def profile_b(tmp_path, monkeypatch):
+ """A fake HOME so ``profiles/`` never resolves to the live install (see hermes-agent-dev)."""
+ launch = tmp_path / "fakehome" / ".hermes"
+ served = launch / "profiles" / "b"
+ served.mkdir(parents=True)
+ (served / "config.yaml").write_text(
+ "terminal:\n backend: docker\n docker_image: b-image\n", encoding="utf-8")
+ monkeypatch.setenv("HOME", str(tmp_path / "fakehome"))
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ monkeypatch.setenv("TERMINAL_ENV", "local") # ambient launch-profile policy
+ monkeypatch.setenv("TERMINAL_DOCKER_IMAGE", "launch-image")
+ return served
+
+
+def test_worker_profile_scope_installs_the_assigned_profiles_terminal_policy(profile_b):
+ """The seam both dispatch-side readers use: toolset resolution and the spawn-env build."""
+ with kanban_db_dispatch._worker_profile_scope(str(profile_b)):
+ scope = get_terminal_scope() or {}
+ assert scope.get("TERMINAL_ENV") == "docker"
+ assert scope.get("TERMINAL_DOCKER_IMAGE") == "b-image", (
+ f"worker inherited the launch profile's terminal policy: {scope}")
+
+
+def test_default_spawn_builds_the_worker_env_under_the_assigned_profiles_scope(
+ profile_b, tmp_path, monkeypatch):
+ from hermes_cli.kanban_db import Task
+
+ seen: list[dict] = []
+
+ import tools.environments.local as local_env
+
+ def _capture(*_args, **_kwargs):
+ seen.append(dict(get_terminal_scope() or {}))
+ raise _StopSpawn # the invariant is observed; nothing must actually spawn
+
+ monkeypatch.setattr(local_env, "build_subprocess_env", _capture)
+
+ task = Task(
+ id="t1", title="t", body=None, assignee="b", status="claimed", priority=0,
+ created_by=None, created_at=0, started_at=None, completed_at=None,
+ workspace_kind="dir", workspace_path=None, claim_lock=None, claim_expires=None,
+ tenant=None)
+ with pytest.raises(_StopSpawn):
+ kanban_db_dispatch._default_spawn(task, str(tmp_path / "ws"))
+
+ assert seen, "_default_spawn never reached build_subprocess_env"
+ assert seen[0].get("TERMINAL_ENV") == "docker", (
+ f"spawn env built under the launch profile's terminal policy: {seen[0]}")
diff --git a/tests/tui_gateway/test_reaper_flush_profile_scope.py b/tests/tui_gateway/test_reaper_flush_profile_scope.py
new file mode 100644
index 00000000000..f804cf1e738
--- /dev/null
+++ b/tests/tui_gateway/test_reaper_flush_profile_scope.py
@@ -0,0 +1,44 @@
+"""The idle reaper's incremental transcript flush must land in the SESSION's profile home.
+
+``session_reaper._flush_session_messages`` runs on the reaper tick and on the exit-flush worker —
+threads with no turn on the stack. Unscoped, ``agent._persist_session`` resolved
+``get_hermes_home()`` to the LAUNCH profile, so a served profile's transcript was written into
+another tenant's state.db. ``_finalize_session`` binds the same session at the same chokepoint.
+"""
+import threading
+
+import pytest
+
+from hermes_constants import get_hermes_home
+from tui_gateway import server as tui_server
+
+
+class _Agent:
+ def __init__(self, seen):
+ self._session_messages = [{"role": "user", "content": "hi"}]
+ self._seen = seen
+
+ def _persist_session(self, _messages):
+ self._seen.append(str(get_hermes_home()))
+
+
+def homes(tmp_path, monkeypatch):
+ launch, served = tmp_path / "launch", tmp_path / "served"
+ for home in (launch, served):
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ return launch, served
+
+
+def test_incremental_flush_persists_into_the_sessions_own_home(homes, monkeypatch):
+ launch, served = homes
+ seen: list[str] = []
+ session = {"agent": _Agent(seen), "profile_home": str(served)}
+ monkeypatch.setattr(tui_server, "_sessions", {"sid": session}, raising=False)
+ monkeypatch.setattr(tui_server, "_sessions_lock", threading.RLock(), raising=False)
+ monkeypatch.setattr(tui_server, "_INCREMENTAL_FLUSH_INTERVAL_S", 30.0, raising=False)
+
+ assert tui_server._flush_dirty_sessions(now=1000.0) == 1
+ assert seen == [str(served)], f"transcript flushed into {seen} instead of the served home"
+ assert str(launch) not in seen
diff --git a/tui_gateway/launch_profile_policy.py b/tui_gateway/launch_profile_policy.py
index 42883f33ce8..e6a311bc0d3 100644
--- a/tui_gateway/launch_profile_policy.py
+++ b/tui_gateway/launch_profile_policy.py
@@ -48,6 +48,34 @@ def activate_multi_profile_hosting() -> None:
set_multiplex_active(True)
+def activate_multi_profile_hosting_eagerly() -> bool:
+ """Activate at HOST startup when this machine has more than one servable profile home.
+
+ Activation used to be lazy and one-way — it fired the first time a *request* asked for a second
+ home. Everything the host had already done by then (idle-reaper ticks, cron start, adapter
+ connects, MCP discovery) ran under single-profile assumptions and is never re-scoped, and the
+ launch profile's env had already been mutated by then, so ``capture_launch_env`` froze a
+ polluted snapshot. One ``hermes serve`` / ``hermes gateway run`` per host means the process
+ knows at boot whether it can be asked for a second home: decide there, once.
+
+ A genuinely single-profile host still never activates (byte-identical behaviour, ``os.environ``
+ precedence preserved). Returns True when this call activated hosting.
+ """
+ from agent.secret_scope import is_multiplex_active
+ if is_multiplex_active():
+ return False
+ try:
+ from hermes_cli.profiles import profiles_to_serve
+ homes = {Path(home).resolve() for _name, home in profiles_to_serve(multiplex=True)}
+ homes.add(Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes").resolve())
+ except Exception:
+ return False
+ if len(homes) < 2:
+ return False
+ activate_multi_profile_hosting()
+ return True
+
+
def _launch_env() -> Dict[str, str]:
"""The launch profile's env: frozen once multiplexing is active; the LIVE process env before
(no secondary has run yet, so it is provably the launch profile's, and freezing it early would
@@ -96,3 +124,30 @@ def launch_profile_runtime_scope(launch_home: "str | Path") -> Iterator[None]:
finally:
reset_terminal_scope(terminal_token)
reset_secret_scope(secret_token)
+
+
+def launch_profile_scope_if_multiplexed():
+ """The launch profile's own runtime scope once this process multiplexes; ``nullcontext``
+ before.
+
+ The single seam for "no routed profile here": under the one-process-per-host ruling the launch
+ profile is a tenant like any other, so a body that used to run with NO scope at all (ambient
+ ``os.environ`` + the process home) must bind the launch profile explicitly — otherwise a
+ secondary's context can have poisoned the ambient state, and a fail-closed ``get_secret`` raises
+ on a perfectly legitimate launch-profile read. Before activation the process env IS the launch
+ profile's, so binding nothing is still correct (and keeps single-profile hosts byte-identical —
+ callers assert the returned object is literally a ``nullcontext``).
+ """
+ from agent.secret_scope import is_multiplex_active
+ if not is_multiplex_active():
+ return contextlib.nullcontext()
+ from hermes_constants import get_process_hermes_home
+ return launch_profile_runtime_scope(get_process_hermes_home())
+
+
+async def async_launch_profile_scope_if_multiplexed():
+ """``async with`` twin of :func:`launch_profile_scope_if_multiplexed` (no I/O of its own: the
+ launch scope is rebuilt from already-hydrated sources, so there is nothing to move off-loop)."""
+ with launch_profile_scope_if_multiplexed():
+ yield
diff --git a/tui_gateway/session_reaper.py b/tui_gateway/session_reaper.py
index 081f0cf6c9c..e872816585f 100644
--- a/tui_gateway/session_reaper.py
+++ b/tui_gateway/session_reaper.py
@@ -30,8 +30,13 @@ def _flush_session_messages(session: dict | None) -> bool:
snapshot = getattr(agent, "_session_messages", None) if hasattr(agent, "_persist_session") else None
if not snapshot:
return False
+ # state.db, config and the token ledger are resolved at CALL time, and every caller of this helper
+ # is an unscoped reaper / exit-flush thread with no turn on the stack. Without the session's own
+ # binding a SERVED profile's transcript is written into the LAUNCH profile's home — the same class
+ # as _finalize_session, which binds it at the identical chokepoint (session_lifecycle.py).
try:
- agent._persist_session(snapshot)
+ with _session_profile_runtime_scope(session or {}):
+ agent._persist_session(snapshot)
return True
except Exception:
logger.debug("incremental session flush failed", exc_info=True)
diff --git a/website/docs/developer-guide/multiplexing-gateway.md b/website/docs/developer-guide/multiplexing-gateway.md
index 512e43893a3..ad9f7bd63d2 100644
--- a/website/docs/developer-guide/multiplexing-gateway.md
+++ b/website/docs/developer-guide/multiplexing-gateway.md
@@ -54,6 +54,18 @@ is documented as a known limitation at the end of this document.
a plain module global, not a contextvar: it describes the deployment mode,
not a per-task value. Its only job is to arm the fail-closed behavior in
`get_secret()`.
+- The dashboard/Desktop backend (`hermes serve`) has no such flag, so
+ `hermes_cli/web_server.py::start_server` calls
+ `tui_gateway.launch_profile_policy.activate_multi_profile_hosting_eagerly()`
+ at boot: the host arms the guard when the machine has more than one servable
+ profile home, instead of waiting for the first `?profile=<other>` request.
+ Activation is one-way, and anything the backend had already done by then
+ (idle-reaper transcript flushes, hosted rooms, cron) was never re-scoped. A
+ genuinely single-profile host still never activates.
+- With the guard armed the **launch profile is a tenant too**: a body with no
+ routed profile binds `launch_profile_scope_if_multiplexed()` (its `.env` over
+ the env frozen at activation) rather than running unscoped on ambient
+ `os.environ`.
## Scope composition