The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): stop, start and restart one profile under the host multiplexer
Victor Kyriazakos4c342c05de12
diff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex 28d982214eb..cd5e086e503 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -360,6 +360,14 @@ def rescan_gateway_profiles(home: Path, *, timeout: float = 8.0) -> Optional[dicreturn query_gateway_control(home, "rescan-profiles", timeout=timeout)+def request_unserve_profile(home: Path, name: str) -> Optional[dict[str, Any]]:+ return query_gateway_control(home, "unserve-profile", params={"name": name}, timeout=8.0)+++def request_serve_profile_hot(home: Path, name: str) -> Optional[dict[str, Any]]:+ return query_gateway_control(home, "serve-profile", params={"name": name}, timeout=8.0)++def migrate_gateway_profile_identity(home: Path, old_name: str, new_name: str, *,timeout: float = 8.0) -> Optional[dict[str, Any]]:"""Ask the multiplexer serving ``home`` to rekey a renamed profile's in-memory + on-disk routingdiff --git a/gateway/run.py b/gateway/run.pyindex 714df2fdb0f..a38c9ce1224 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -5585,7 +5585,10 @@ async def _start_gateway_start_control_socket(runner):# failure only means consumers fall back to the process-scan/state-file layer, exactly as before# this feature. See #92091.from gateway.control_socket import GatewayControlServer- from gateway.run_profile_reconcile import migrate_profile_identity_verb, purge_profile_identity_verb+ from gateway.run_profile_reconcile import (+ migrate_profile_identity_verb, purge_profile_identity_verb,+ unserve_profile_verb, serve_profile_verb,+ )from gateway.run_plugin_rewire import reload_plugins_verb# pause-for-update: the updater asks us to drain + exit (freeing venv handles) vs. a tree-kill# (same path as SIGUSR1). Handler runs on the socket executor thread, so marshal onto the loop.@@ -5635,6 +5638,8 @@ async def _start_gateway_start_control_socket(runner):_control_server = GatewayControlServer(verb_handlers={"pause-for-update": _pause_for_update_handler,"rescan-profiles": _rescan_profiles_handler,+ "unserve-profile": unserve_profile_verb(runner),+ "serve-profile": serve_profile_verb(runner),"migrate-profile-identity": migrate_profile_identity_verb(runner),"purge-profile-identity": purge_profile_identity_verb(runner),# A plugin installed/enabled by another process loads now and re-wires thediff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex 761d535b486..418c8f122b1 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -873,10 +873,13 @@ class GatewayAdapterLifecycleMixin:publish_runtime_status(served_profiles=[])return 0try:- from hermes_cli.profiles import get_active_profile_name+ from hermes_cli.profiles import get_active_profile_name, profiles_to_serve, profile_is_parkedexcept Exception:return 0active = get_active_profile_name() or "default" # launch profile, pre-identity (adapter boot)+ for name, home in profiles_to_serve(True, include_parked=True):+ if name != "default" and profile_is_parked(home):+ logger.info("profile '%s' is parked (gateway.parked); not served by this gateway", name)connected = 0claimed = self._primary_resource_claims(active)profile_homes = _multiplex_profile_homes(self.config)diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.pyindex 473d217dc50..bf70d9f177b 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -95,7 +95,7 @@ class GatewayProfileReconcileMixin:"""Diff ``profiles/`` against the served set: start adapters for new profiles, tear down andunroute deleted ones, (re)build adapters for served profiles whose config/.env changed. Otherprofiles' adapters are never touched. Returns ``{"added", "removed", "rescanned", "served_profiles"}``."""- from gateway.run import MultiplexConfigError, _multiplex_profile_homes+ from gateway.run import _multiplex_profile_homesresult: Dict[str, Any] = {"added": [], "removed": [], "rescanned": [], "reason": reason}if not self._multiplex_on():return {**result, "multiplex": False, "served_profiles": self.served_profile_names()}@@ -125,61 +125,62 @@ class GatewayProfileReconcileMixin:removed = [n for n in known if n not in current and n != active]changed = [n for n in current if n in known and n != active and n not in addedand profile_serve_signature(current[n]) != sigs.get(n)]- if not (added or removed or changed):- return {**result, "served_profiles": self.served_profile_names()}- for name in removed:- await self._unserve_profile(name, known[name])- result["removed"].append(name)- claimed = self._live_resource_claims(active)- transient_failed = set()- for name in added + changed:- # Only acknowledge the configuration observed before connecting;- # a setup save during an awaited handshake needs another scan.- scan_signature = profile_serve_signature(current[name])- try:- connected = await self._start_one_profile_adapters(name, current[name], claimed)- except MultiplexConfigError as exc:- # Boot refuses to run with such a profile; at runtime we park just this profile.- logger.error("[MULTIPLEX] Profile '%s' not served: %s", name, exc)- connected = 0- sigs[name] = scan_signature- except Exception:- logger.error("[MULTIPLEX] Failed to start adapters for profile '%s'", name, exc_info=True)- connected = 0- # A transient failure is not the deliberate park above: leave the signature- # unacknowledged so the next reconcile retries the connect.- transient_failed.add(name)- else:- sigs[name] = scan_signature- if name in added:- logger.info("[MULTIPLEX] Now serving profile '%s' (%s adapter(s) connected; %s)", name, connected, reason)- result["added"].append(name)- else:- logger.info("[MULTIPLEX] Re-scanned profile '%s' after config/.env change (%s adapter(s) connected)", name, connected)- result["rescanned"].append(name)- self._served_profile_signatures = sigs- # A profile deleted while an adapter above was still connecting must not be recorded back- # (the deleter's signal timed out against this lock and rmtree already ran).- live_now = {str(name) for name, _home in _multiplex_profile_homes(self.config)}- for name in [n for n in current if n not in live_now and n != active]:- await self._unserve_profile(name, current.pop(name))- result["removed"].append(name)- added = [n for n in added if n != name]- self._record_served_profiles(active, list(current.items()))- # ``_note_served_profiles`` fills a missing signature with the current one; that refill- # would park a transiently-failed profile exactly like the config-error case above.- for name in transient_failed:- if isinstance(self._served_profile_signatures, dict):- self._served_profile_signatures.pop(name, None)- # A cached config with no live adapters is owed a home-channel notice nothing can- # deliver, and the planned-restart marker then never clears.- configs = getattr(self, "_profile_configs", None)- if isinstance(configs, dict):- configs.pop(name, None)- if added:- await self._after_profiles_added([(n, current[n]) for n in added])- result["served_profiles"] = self.served_profile_names()- return result+ return await self._apply_profile_changes(current, added, removed, changed, reason=reason)++ async def _apply_profile_changes(self, current, added, removed, changed, *, reason):+ """Apply a selected diff under the reconcile lock, shared by the watcher and control verbs."""+ from gateway.run import MultiplexConfigError, _multiplex_profile_homes+ active = getattr(self, "_primary_profile_name", None) or "default"+ result = {"added": [], "removed": [], "rescanned": [], "reason": reason}+ if not (added or removed or changed):+ return {**result, "served_profiles": self.served_profile_names()}+ for name in removed:+ await self._unserve_profile(name, self._served_profile_homes[name])+ result["removed"].append(name)+ sigs = self._served_profile_signatures or {}+ claimed = self._live_resource_claims(active)+ transient_failed = set()+ for name in added + changed:+ # Only acknowledge the configuration observed before connecting;+ # a setup save during an awaited handshake needs another scan.+ scan_signature = profile_serve_signature(current[name])+ try:+ connected = await self._start_one_profile_adapters(name, current[name], claimed)+ except MultiplexConfigError as exc:+ logger.error("[MULTIPLEX] Profile '%s' not served: %s", name, exc)+ connected = 0+ sigs[name] = scan_signature+ except Exception:+ logger.error("[MULTIPLEX] Failed to start adapters for profile '%s'", name, exc_info=True)+ connected = 0+ transient_failed.add(name)+ else:+ sigs[name] = scan_signature+ if name in added:+ logger.info("[MULTIPLEX] Now serving profile '%s' (%s adapter(s) connected; %s)", name, connected, reason)+ result["added"].append(name)+ else:+ logger.info("[MULTIPLEX] Re-scanned profile '%s' after config/.env change (%s adapter(s) connected)", name, connected)+ result["rescanned"].append(name)+ self._served_profile_signatures = sigs+ # Deletion or parking during an awaited connect must win over publication.+ live_now = {str(name) for name, _home in _multiplex_profile_homes(self.config)}+ for name in [n for n in current if n not in live_now and n != active]:+ await self._unserve_profile(name, current.pop(name))+ result["removed"].append(name)+ added = [n for n in added if n != name]+ self._record_served_profiles(active, list(current.items()))+ # _note_served_profiles refills missing signatures; failed connects must retry.+ for name in transient_failed:+ if isinstance(self._served_profile_signatures, dict):+ self._served_profile_signatures.pop(name, None)+ configs = getattr(self, "_profile_configs", None)+ if isinstance(configs, dict):+ configs.pop(name, None)+ if added:+ await self._after_profiles_added([(n, current[n]) for n in added])+ result["served_profiles"] = self.served_profile_names()+ return resultdef _live_resource_claims(self, active: str) -> Dict[tuple, str]:"""Startup's ``claimed`` map rebuilt from what is live now: primary claims plus every connected@@ -211,10 +212,10 @@ class GatewayProfileReconcileMixin:logger.warning("MCP tool discovery failed for profile '%s'", profile_name, exc_info=True)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+ """Stop and unroute one profile: cancel its reconnects, tear down its adapters, drop itsbookkeeping 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+ The whole teardown runs inside the removed profile's own runtime scope: adapter disconnecthooks, the agent-cache eviction (provider/memory shutdown) and the state/memory handlerelease all read config and credentials at call time, and this coroutine runs on thereconcile task with no profile bound — unscoped they resolved against the LAUNCH home, so a@@ -255,7 +256,61 @@ class GatewayProfileReconcileMixin:with _log_suppressed(logging.DEBUG, "memory-store release failed", exc_info=True):from plugins.memory.holographic.store import MemoryStoreMemoryStore.release_all_under(home)- logger.info("[MULTIPLEX] Profile '%s' deleted — %d adapter(s) stopped and unrouted", name, len(adapters))+ logger.info("[MULTIPLEX] Profile '%s' unserved — %d adapter(s) stopped and unrouted", name, len(adapters))+++def _profile_lifecycle_verb(runner, *, serve: bool):+ """Build on the owning loop; socket handlers themselves run on executor threads."""+ loop = asyncio.get_running_loop()++ async def apply(name):+ from hermes_cli.profiles import profiles_to_serve, profile_is_parked+ if not runner._multiplex_on() or not runner._running or runner._served_profile_homes is None:+ return {"error": "host multiplexer is not ready"}+ async with runner._reconcile_lock():+ active = getattr(runner, "_primary_profile_name", None) or "default"+ if not isinstance(name, str) or not name or name == active:+ return {"error": "a non-launch profile name is required"}+ known = dict(runner._served_profile_homes)+ if not serve:+ if name not in known:+ return {"error": f"profile '{name}' is not served"}+ await runner._unserve_profile(name, known.pop(name))+ runner._record_served_profiles(active, list(known.items()))+ return {"unserved": name, "served_profiles": runner.served_profile_names()}+ installed = dict(profiles_to_serve(True, include_parked=True))+ if name not in installed:+ return {"error": f"unknown profile '{name}'"}+ if name != "default" and profile_is_parked(installed[name]):+ return {"error": f"profile '{name}' is parked (gateway.parked)"}+ if name in known:+ return {"error": f"profile '{name}' is already served"}+ known[name] = installed[name]+ result = await runner._apply_profile_changes(known, [name], [], [], reason="control-socket")+ if name not in result["served_profiles"]:+ return {"error": f"profile '{name}' was removed or parked during startup"}+ return {"served": name, "served_profiles": result["served_profiles"]}++ def handler(params):+ future = asyncio.run_coroutine_threadsafe(apply(params.get("name")), loop)+ try:+ return future.result(timeout=5.0)+ except TimeoutError:+ # Keep running: the client must not interpret an incomplete teardown as stopped.+ return {"pending": True, "served_profiles": runner.served_profile_names()}+ except Exception as exc:+ logger.warning("Profile lifecycle request failed", exc_info=True)+ return {"error": f"{type(exc).__name__}: {exc}"}++ return handler+++def unserve_profile_verb(runner):+ return _profile_lifecycle_verb(runner, serve=False)+++def serve_profile_verb(runner):+ return _profile_lifecycle_verb(runner, serve=True)def _mcp_config_reconciler(runner=None):diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 30e11e4f477..aa677795587 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -4766,6 +4766,9 @@ def _print_unfolded_gateway_note(owner) -> None:def _cmd_start(args):+ from hermes_cli.gateway_profile_lifecycle import profile_lifecycle+ if profile_lifecycle("start", args):+ returnsystem = getattr(args, "system", False)start_all = getattr(args, "all", False)force = getattr(args, "force", False)@@ -4798,13 +4801,14 @@ def _cmd_start(args):def _cmd_stop(args):_refuse_from_inside_gateway("stop", "restart loops")+ from hermes_cli.gateway_profile_lifecycle import profile_lifecycle+ if profile_lifecycle("stop", args):+ returnstop_all = getattr(args, "all", False)system = getattr(args, "system", False)if not stop_all and not find_gateway_pids() and (_served_by_another_host_gateway() or named_profile_served_by_running_multiplexer()):- # A served profile owns no gateway to stop; "No gateway running for this profile" (exit 0) would- # contradict `gateway status` ("running via the host multiplexer") on the same profile.- # A `--force`-started separate gateway HAS a pid of its own and is stopped normally.+ # The launch/default-profile lifecycle still names the whole host.owner = _served_by_another_host_gateway()print_error(f"The host gateway serves profile '{_current_profile_name()}' — there is no separate "@@ -4909,6 +4913,9 @@ def _restart_all(system: bool) -> None:def _cmd_restart(args):_refuse_from_inside_gateway("restart", "restart loops")+ from hermes_cli.gateway_profile_lifecycle import profile_lifecycle+ if profile_lifecycle("restart", args):+ returnsystem = getattr(args, "system", False)restart_all = getattr(args, "all", False)force = getattr(args, "force", False)@@ -5016,6 +5023,9 @@ def _status_host_kind() -> str:def _cmd_status(args):+ from hermes_cli.gateway_profile_lifecycle import print_parked_status+ if print_parked_status():+ returndeep = getattr(args, "deep", False)full = getattr(args, "full", False)system = getattr(args, "system", False)diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.pyindex c36b701a776..73537b9fdda 100644--- a/hermes_cli/gateway_migrate.py+++ b/hermes_cli/gateway_migrate.py@@ -142,6 +142,11 @@ class MigrationPlan:def standalone_secondaries(self) -> list[ProfileGateway]:return [p for p in self.secondaries if p.has_gateway]+ @property+ def expected_served_names(self) -> set[str]:+ from hermes_cli.profiles import profile_is_parked+ return {p.name for p in self.profiles if p.is_default or not profile_is_parked(p.home)}+@propertydef blocked(self) -> bool:return bool(self.blockers)@@ -216,7 +221,7 @@ def _default_home() -> Path:def _profile_homes() -> list[tuple[str, Path]]:from hermes_cli.profiles import profiles_to_serve- return list(profiles_to_serve(multiplex=True))+ return list(profiles_to_serve(multiplex=True, include_parked=True))def _live_gateway_pid(home: Path) -> Optional[int]:@@ -650,7 +655,7 @@ def format_plan(plan: MigrationPlan, *, dry_run: bool) -> list[str]:# which is the mechanism ``apply_migration`` picks — printing this plan's guess contradicted it.target = _resume_target(plan)[0] if plan.manifest is not None else plan.target_service_kind()lines.append(f" - default: {'restart' if plan.default.has_gateway else 'start'} the gateway"- + (f" via {target[0]}" if target else " (detached)") + f", verify it serves {len(plan.profiles)} profiles")+ + (f" via {target[0]}" if target else " (detached)") + f", verify it serves {len(plan.expected_served_names)} profiles")lines.append(f" - record the previous state in {plan.default_home / MANIFEST_NAME} "f"(used to undo a FAILED apply, and to resume this command after a crash)")if signalled:@@ -755,14 +760,16 @@ def _read_manifest(default_home: Path) -> Optional[dict]:def _manifest_not_yet_served(manifest: Optional[dict], live_served: Optional[list[str]]) -> bool:"""The postcondition ``apply_migration`` waits for, re-derived from live state: a LIVE default that- recorded serving every profile the manifest migrated. Anything less — no live gateway, an+ recorded serving every unparked profile the manifest migrated. Anything less — no live gateway, aninstalled-but-dead unit (``systemd_install`` writes the unit before the start that can still fail),a standalone default never restarted — is a half-applied migration, not "already multiplexed".Profiles created after the migration are not in the manifest, so they cannot flag it as interrupted."""if manifest is None:return False+ from hermes_cli.profiles import profile_is_parkedrecs = [r for r in (manifest.get("default"), *(_manifest_secondaries(manifest) or [])) if isinstance(r, dict)]- migrated = {str(r.get("profile") or "default") for r in recs} | {"default"}+ migrated = {str(r.get("profile") or "default") for r in recs+ if not r.get("home") or not profile_is_parked(Path(r["home"]))} | {"default"}return not migrated <= set(live_served or [])@@ -964,7 +971,7 @@ def apply_migration(plan: MigrationPlan, *, served_wait: float = _SERVED_WAIT_SEprint(f" Re-run {MIGRATE_COMMAND} to resume from the manifest.")return False- expected = {p.name for p in plan.profiles}+ expected = plan.expected_served_namesserved = _wait_for_served(plan.default_home, expected, served_wait)if served is not None and expected <= set(served):# Manifest present == migration UNFINISHED. That is the whole resume/half-migrated signaldiff --git a/hermes_cli/gateway_multiplex_mode.py b/hermes_cli/gateway_multiplex_mode.pyindex b915645e899..60cf9d63e3b 100644--- a/hermes_cli/gateway_multiplex_mode.py+++ b/hermes_cli/gateway_multiplex_mode.py@@ -141,7 +141,8 @@ def implicit_multiplex_blocker() -> Optional[str]:# Cheap and first: a single-profile install has nothing to multiplex, and the fail-closed secret# scope the multiplexer arms buys it nothing. (Also keeps every embedded/test runner off the# service-manager probes below.) Create a second profile and restart to start serving it.- if len(profiles_to_serve(multiplex=True)) < 2:+ # Parking is reversible without a host restart, so keep the reconcile watcher alive.+ if len(profiles_to_serve(multiplex=True, include_parked=True)) < 2:return SINGLE_PROFILE_REASONfrom hermes_cli.gateway_migrate import MIGRATE_COMMAND, _host_supports_migration, build_migration_planhost_reason = _host_supports_migration()diff --git a/hermes_cli/gateway_profile_lifecycle.py b/hermes_cli/gateway_profile_lifecycle.pynew file mode 100644index 00000000000..440a91716dc--- /dev/null+++ b/hermes_cli/gateway_profile_lifecycle.py@@ -0,0 +1,94 @@+"""Named-profile lifecycle inside the host gateway, never a service-manager action."""+from __future__ import annotations++from hermes_constants import get_hermes_home, get_default_hermes_root+from hermes_cli.profiles import parked_marker_path, profile_is_parked, profiles_to_serve+++def _confirmed(answer, key, name):+ return isinstance(answer, dict) and answer.get(key) == name and not answer.get("error")+++def _failure(answer):+ if isinstance(answer, dict):+ return answer.get("error") or "host operation is still pending"+ return "host control socket did not answer"+++def profile_lifecycle(command: str, args) -> bool:+ """True when a named-profile command was handled (including an unconfirmed request)."""+ from hermes_cli import gateway as gw+ from gateway.control_socket import request_unserve_profile, request_serve_profile_hot++ name = gw._current_profile_name()+ if not name or name == "default" or getattr(args, "all", False) or getattr(args, "force", False):+ return False+ home = get_hermes_home()+ marker = parked_marker_path(home)+ if command == "start":+ if not profile_is_parked(home):+ return False+ marker.unlink()+ owner = gw._host_multiplexer_for_all_verb()+ if owner is None:+ from hermes_cli.gateway_multiplex_served import live_default_gateway_pid+ if live_default_gateway_pid() is None:+ return False # Unpark even when today's normal start path must start the host first.+ host_home = owner.home if owner is not None else get_default_hermes_root()+ answer = request_serve_profile_hot(host_home, name)+ if _confirmed(answer, "served", name):+ print(f"Profile '{name}' served by the host gateway.")+ else:+ print(f"Profile '{name}' unparked, but serving was not confirmed: {_failure(answer)}.")+ print("The host retries on its next rescan (within 30s). Check gateway status.")+ return True++ # A separate --force gateway still owns its normal process/service lifecycle.+ if gw.find_gateway_pids():+ return False+ owner = gw._served_by_another_host_gateway()+ if owner is None and not gw.named_profile_served_by_running_multiplexer():+ return False+ host_home = owner.home if owner is not None else get_default_hermes_root()+ if command == "stop":+ # Persist intent BEFORE teardown: the periodic rescan must not re-add this profile.+ marker.touch()+ answer = request_unserve_profile(host_home, name)+ if _confirmed(answer, "unserved", name):+ print(f"Profile '{name}' parked; its bots and cron are stopped. "+ f"Start again with: hermes -p {name} gateway start")+ else:+ print(f"Profile '{name}' parked, but immediate stop was not confirmed: {_failure(answer)}.")+ print("The host drops it on its next rescan (within 30s).")+ return True++ answer = request_unserve_profile(host_home, name)+ if not _confirmed(answer, "unserved", name):+ print(f"Profile '{name}' restart was not confirmed: {_failure(answer)}.")+ return True+ answer = request_serve_profile_hot(host_home, name)+ if _confirmed(answer, "served", name):+ print(f"Profile '{name}' restarted by the host gateway.")+ else:+ print(f"Profile '{name}' stopped, but serving was not confirmed: {_failure(answer)}.")+ print("The host retries on its next rescan (within 30s). Check gateway status.")+ return True+++def print_parked_status() -> bool:+ """A parked satellite is still installed, but is not a running gateway."""+ from hermes_cli import gateway as gw+ name = gw._current_profile_name()+ if name and name != "default" and profile_is_parked(get_hermes_home()):+ print(f"Profile '{name}': parked (hermes -p {name} gateway start)")+ return True+ if not name or name == "default":+ parked = [profile for profile, home in profiles_to_serve(True, include_parked=True)+ if profile != "default" and profile_is_parked(home)]+ if parked:+ owner = gw.host_multiplexer_serving()+ if owner is not None:+ print(f"Served profiles: {', '.join(owner.profiles)}")+ for profile in parked:+ print(f"Profile '{profile}': parked (hermes -p {profile} gateway start)")+ return Falsediff --git a/hermes_cli/plugin_python_deps.py b/hermes_cli/plugin_python_deps.pyindex 5194bd20a97..271d9fa33e7 100644--- a/hermes_cli/plugin_python_deps.py+++ b/hermes_cli/plugin_python_deps.py@@ -234,7 +234,7 @@ def enabled_declarations(home: Path) -> list[PythonDeclaration]:def dependency_homes() -> list[Path]:"""Every home whose plugins share this venv: the default home plus live named profiles."""from hermes_cli.profiles import profiles_to_serve- return [home for _name, home in profiles_to_serve(multiplex=True, include_standalone=True)]+ return [home for _name, home in profiles_to_serve(multiplex=True, include_standalone=True, include_parked=True)]def union_specs(declarations: Iterable[PythonDeclaration]) -> list[str]:diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex a4a1e872f66..7101ddb732b 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -1024,23 +1024,43 @@ def _standalone_truthy(value: object) -> bool:return bool(value)-def profiles_to_serve(multiplex: bool, *, include_standalone: bool = False) -> List[Tuple[str, Path]]:+def parked_marker_path(home: Path) -> Path:+ return Path(home) / "gateway.parked"+++def profile_is_parked(home: Path) -> bool:+ """Marker contents are deliberately irrelevant, including for provisioning."""+ return parked_marker_path(home).exists()+++_parked_default_warned: set[Path] = set()+++def profiles_to_serve(multiplex: bool, *, include_standalone: bool = False,+ include_parked: bool = False) -> List[Tuple[str, Path]]:"""``(profile_name, hermes_home)`` pairs a gateway should serve — the single chokepointfor "which profiles does the inbound gateway handle".``multiplex=False``: exactly one entry for the *active* profile (byte-for-byte thehistorical single-profile behavior; name is ``"default"`` or the named profile's id).``multiplex=True``: default plus every live named profile under ``profiles/`` (tombstoned- profiles skipped). Pure directory read: never creates a profile dir (#94590).+ and parked profiles skipped). Pure directory read: never creates a profile dir (#94590).Named profiles that authored ``gateway.standalone: true`` are skipped because they opted- out of the host multiplexer; callers enumerating INSTALLED profiles pass ``include_standalone=True``."""+ out of the host multiplexer; a ``gateway.parked`` marker (``hermes -p X gateway stop``) skips+ a profile the host would otherwise serve. Callers enumerating INSTALLED profiles pass+ ``include_standalone=True, include_parked=True``; serving/ticking callers pass neither."""active = get_active_profile_name() or "default"+ default = _get_default_hermes_home()+ if profile_is_parked(default) and default not in _parked_default_warned:+ logger.warning("Ignoring gateway.parked for the default profile; stop the host gateway instead")+ _parked_default_warned.add(default)if not multiplex:return [(active, get_profile_dir(active))]- serve: List[Tuple[str, Path]] = [("default", _get_default_hermes_home())]+ serve: List[Tuple[str, Path]] = [("default", default)]serve.extend((entry.name, entry) for entry in _iter_named_profile_dirs()- if include_standalone or not profile_is_standalone(entry))+ if (include_standalone or not profile_is_standalone(entry))+ and (include_parked or not profile_is_parked(entry)))return servediff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 33720975b7a..febc3bb4084 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -991,6 +991,7 @@ def _record_attested_cold_start_profiles(token: dict, running_profiles: set) ->from hermes_cli.profiles import get_active_profile_name, profiles_to_serveactive = get_active_profile_name() or "default"cold: dict[str, str] = {}+ # An activation list, not inventory: parked profiles stay offline.for name, home in profiles_to_serve(multiplex=True, include_standalone=True):if name in running_profiles or (name == active and token.get("cold_start_if_installed")):continuediff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.pyindex 77d75e0a532..e14cd8f995a 100644--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@ -215,7 +215,7 @@ def _profile_targets(log_label: str) -> List[Tuple[str, Path]]:fan-out that only needs name/path (#114041)."""from hermes_cli import profiles as profiles_modtry:- targets = list(profiles_mod.profiles_to_serve(multiplex=True, include_standalone=True))+ targets = list(profiles_mod.profiles_to_serve(multiplex=True, include_standalone=True, include_parked=True))except Exception:_log.exception("%s: profile enumeration failed", log_label)targets = []diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.pyindex 88af428de3d..9b85f5768c0 100644--- a/hermes_cli/web_routers/status.py+++ b/hermes_cli/web_routers/status.py@@ -533,6 +533,7 @@ async def get_status(profile: Optional[str] = None):# renders the profile list over a gated bind) so they survive the auth gate; the# per-gateway ``gateways[]`` carries host ports and stays gated below.status["profiles"] = topology["profiles"]+ status["parked_profiles"] = topology.get("parked_profiles", [])status["gateway_mode"] = topology["gateway_mode"]# Host paths, gateway PID, internal health URL and per-gateway ports are deploymentdiff --git a/hermes_cli/web_server_cron.py b/hermes_cli/web_server_cron.pyindex d54255f8de0..22bd8d4d0c0 100644--- a/hermes_cli/web_server_cron.py+++ b/hermes_cli/web_server_cron.py@@ -87,7 +87,7 @@ def _cron_profile_dicts() -> List[Dict[str, Any]]:try:return [{"name": name, "path": str(home), "is_default": name == "default"}- for name, home in profiles_mod.profiles_to_serve(multiplex=True, include_standalone=True)]+ for name, home in profiles_mod.profiles_to_serve(multiplex=True, include_standalone=True, include_parked=True)]except Exception:_log.exception("Failed to list profiles for cron dashboard; falling back to directory scan")return _fallback_profile_dicts(profiles_mod)diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.pyindex c4b00ee8dc3..83fb52db69a 100644--- a/hermes_cli/web_server_gateway.py+++ b/hermes_cli/web_server_gateway.py@@ -146,9 +146,9 @@ def _collect_profile_gateway_topology() -> Dict[str, Any]:platform maps per live gateway, an internal aggregation input never exposed directly."""try:- from hermes_cli.profiles import _check_gateway_running, profiles_to_serve+ from hermes_cli.profiles import _check_gateway_running, profiles_to_serve, profile_is_parkedfrom gateway.status import read_runtime_status- homes = profiles_to_serve(True, include_standalone=True)+ homes = profiles_to_serve(True, include_standalone=True, include_parked=True)except Exception:_log.debug("profile/gateway topology enumeration failed", exc_info=True)return {"profiles": [], "gateway_mode": "unknown", "gateways": [], "profile_platforms": {}}@@ -190,6 +190,7 @@ def _collect_profile_gateway_topology() -> Dict[str, Any]:mode = {0: "none", 1: "single"}.get(len(gateways), "multiple")return {"profiles": [name for name, _home in homes],+ "parked_profiles": [name for name, home in homes if name != "default" and profile_is_parked(home)],"gateway_mode": mode,"gateways": gateways,"profile_platforms": profile_platforms}diff --git a/tests/gateway/test_multiplex_adapter_registry.py b/tests/gateway/test_multiplex_adapter_registry.pyindex 10db9826444..7d4453e4ae5 100644--- a/tests/gateway/test_multiplex_adapter_registry.py+++ b/tests/gateway/test_multiplex_adapter_registry.py@@ -834,7 +834,7 @@ class TestSecondaryProfileConfigHandling:runner._profile_adapters[profile_name] = {}return 2- def fake_profiles_to_serve(multiplex):+ def fake_profiles_to_serve(multiplex, **kw):assert multiplex is Truereturn [("default", Path("/tmp/default")),@@ -902,7 +902,7 @@ class TestSecondaryProfileConfigHandling:monkeypatch.setattr("hermes_cli.profiles.profiles_to_serve",- lambda multiplex: [+ lambda multiplex, **kw: [("default", Path("/tmp/default")),("unsafe", Path("/tmp/unsafe")),],diff --git a/tests/gateway/test_multiplex_hot_serve.py b/tests/gateway/test_multiplex_hot_serve.pyindex a8429633617..5f06bc317ed 100644--- a/tests/gateway/test_multiplex_hot_serve.py+++ b/tests/gateway/test_multiplex_hot_serve.py@@ -111,6 +111,95 @@ async def test_opt_out_rescans_and_opt_in_waits_for_own_gateway_to_stop(tmp_pathassert runner._started.count("solo") == 2+async def test_parked_profile_boot_and_reconcile(tmp_path, monkeypatch, caplog):+ runner, home = _runner(tmp_path, monkeypatch)+ secondary = _mkprofile(home, "worker")+ marker = secondary / "gateway.parked"+ marker.touch()+ # Boot uses the real directory enumerator and config loaders, no bot/network.+ del runner._start_one_profile_adapters+ runner._register_config_hooks = lambda *a, **kw: None+ caplog.set_level("INFO")+ with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):+ await runner._start_secondary_profile_adapters()+ assert _served_record(home) == ["default"]+ assert "profile 'worker' is parked (gateway.parked); not served by this gateway" in caplog.text+ marker.unlink()+ assert (await runner.reconcile_served_profiles())["added"] == ["worker"]+ assert _served_record(home) == ["default", "worker"]+ marker.touch()+ assert (await runner.reconcile_served_profiles())["removed"] == ["worker"]+ assert _served_record(home) == ["default"]+++async def test_profile_control_verbs_round_trip_and_refusals(tmp_path, monkeypatch):+ from gateway import run_profile_reconcile as verbs+ runner, home = _runner(tmp_path, monkeypatch)+ secondary = _mkprofile(home, "worker", "DISCORD_BOT_TOKEN=worker-token\n")+ with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):+ await runner._start_secondary_profile_adapters()+ stop = verbs.unserve_profile_verb(runner)+ start = verbs.serve_profile_verb(runner)+ for handler, name in [(stop, "default"), (stop, "missing"), (start, "missing"),+ (start, "worker"), (start, "default")]:+ assert (await asyncio.to_thread(handler, {"name": name}))["error"]+ old = runner._profile_adapters["worker"][Platform.DISCORD]+ answer = await asyncio.to_thread(stop, {"name": "worker"})+ assert answer["unserved"] == "worker"+ assert answer["served_profiles"] == _served_record(home) == ["default"]+ assert old.disconnected+ marker = secondary / "gateway.parked"+ marker.touch()+ assert (await asyncio.to_thread(start, {"name": "worker"}))["error"]+ marker.unlink()+ (secondary / ".env").write_text("DISCORD_BOT_TOKEN=new-worker-token\n")+ answer = await asyncio.to_thread(start, {"name": "worker"})+ assert answer["served"] == "worker"+ assert answer["served_profiles"] == _served_record(home) == ["default", "worker"]+ assert runner._profile_adapters["worker"][Platform.DISCORD].token.endswith("new-worker-token\n")+++async def test_marker_appearing_unserves_on_reconcile(tmp_path, monkeypatch):+ runner, home = _runner(tmp_path, monkeypatch)+ secondary = _mkprofile(home, "worker", "DISCORD_BOT_TOKEN=worker-token\n")+ with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):+ await runner._start_secondary_profile_adapters()+ adapter = runner._profile_adapters["worker"][Platform.DISCORD]+ (secondary / "gateway.parked").touch()+ assert (await runner.reconcile_served_profiles())["removed"] == ["worker"]+ assert adapter.disconnected+ assert _served_record(home) == ["default"]++[email protected]_only+async def test_profile_lifecycle_over_real_control_socket(tmp_path, monkeypatch):+ from gateway.run import _start_gateway_start_control_socket+ from gateway import control_socket+ runner, home = _runner(tmp_path, monkeypatch)+ secondary = _mkprofile(home, "worker")+ with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):+ await runner._start_secondary_profile_adapters()+ server = await _start_gateway_start_control_socket(runner)+ assert server is not None+ try:+ (secondary / "gateway.parked").touch()+ stopped = await asyncio.to_thread(control_socket.request_unserve_profile, home, "worker")+ assert stopped["unserved"] == "worker"+ assert _served_record(home) == ["default"]+ refused = await asyncio.to_thread(control_socket.request_serve_profile_hot, home, "worker")+ assert "parked" in refused["error"]+ (secondary / "gateway.parked").unlink()+ started = await asyncio.to_thread(control_socket.request_serve_profile_hot, home, "worker")+ assert started["served"] == "worker"+ assert _served_record(home) == ["default", "worker"]+ finally:+ await server.stop()++@pytest.mark.asyncioasync def test_created_then_credentialed_profile_is_served_without_restart(tmp_path, monkeypatch):runner, home = _runner(tmp_path, monkeypatch)diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.pyindex b0b40a96221..aadd17e6be5 100644--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py@@ -154,6 +154,49 @@ def test_dry_run_and_blocked_preflight_change_nothing(fleet, capsys):assert "nothing will be changed" in capsys.readouterr().out+def test_parked_profile_remains_in_migration_inventory(fleet):+ home = fleet.root / "profiles/coder"+ (home / "gateway.parked").touch()++ plan = gm.build_migration_plan()+ inventory = {p.name: p for p in plan.standalone_secondaries}+ assert "coder" in inventory+ assert inventory["coder"].home == home+ assert inventory["coder"].pid == fleet.pids["coder"]+ assert inventory["coder"].services == [("systemd", False)]++ # Parking must not hide migration preflight conflicts either.+ (home / ".env").write_text("TELEGRAM_BOT_TOKEN=111111:default-token\n", encoding="utf-8")+ blocked = gm.build_migration_plan()+ assert any("'coder'" in reason and "credential" in reason for reason in blocked.blockers)+++def test_migration_removes_parked_footprint_without_waiting_for_it_to_serve(fleet, monkeypatch):+ home = fleet.root / "profiles/coder"+ (home / "gateway.parked").touch()+ service_op = gm._service_op++ def boot_unparked_profiles(kind, system, verb, home, **kwargs):+ service_op(kind, system, verb, home, **kwargs)+ if _name(home) == "default" and verb in ("start", "restart"):+ from hermes_cli.profiles import profiles_to_serve+ path = fleet.root / "gateway_state.json"+ runtime = json.loads(path.read_text())+ runtime["served_profiles"] = [name for name, _ in profiles_to_serve(True)]+ path.write_text(json.dumps(runtime))++ monkeypatch.setattr(gm, "_service_op", boot_unparked_profiles)+ plan = gm.build_migration_plan()+ assert any("verify it serves 2 profiles" in line for line in gm.format_plan(plan, dry_run=True))+ ok, manifest = _apply_capturing_manifest(plan, served_wait=0.1)+ assert ok+ assert "coder" not in fleet.pids and "coder" not in fleet.services+ assert (home / "gateway.parked").exists()+ assert {p["profile"] for p in manifest["secondaries"]} == {"coder", "ops"}+ gm._write_manifest(fleet.root, manifest)+ assert not gm.build_migration_plan().interrupted++def _apply_capturing_manifest(plan, *, served_wait=5.0, restore=False):"""Apply, returning (ok, manifest-as-written). A CONFIRMED convergence deletes the manifest(manifest present == unfinished), so the only way to inspect it is to read it mid-flight."""diff --git a/tests/hermes_cli/test_gateway_multiplex_lifecycle.py b/tests/hermes_cli/test_gateway_multiplex_lifecycle.pynew file mode 100644index 00000000000..6e846d8311e--- /dev/null+++ b/tests/hermes_cli/test_gateway_multiplex_lifecycle.py@@ -0,0 +1,171 @@+"""Per-profile lifecycle never stops the shared host or hides an installed profile."""+from pathlib import Path+from types import SimpleNamespace++import pytest+++def homes(tmp_path, monkeypatch):+ from hermes_cli import profiles+ root = tmp_path / '.hermes'+ secondary = root / 'profiles' / 'worker'+ secondary.mkdir(parents=True)+ (secondary / 'config.yaml').write_text('model: {default: worker-model}\n')+ (root / 'config.yaml').write_text('gateway: {multiplex_profiles: true}\n')+ monkeypatch.setattr(Path, 'home', lambda: tmp_path)+ monkeypatch.setenv('HERMES_HOME', str(root))+ monkeypatch.setattr(profiles, 'get_active_profile_name', lambda: 'default')+ return root, secondary++[email protected]('include_parked', [False, True])+def test_parked_is_not_served_but_remains_installed(homes, include_parked):+ from hermes_cli import profiles+ root, secondary = homes+ (secondary / 'gateway.parked').write_text('provisioned offline\n')+ if include_parked:+ actual = profiles.profiles_to_serve(True, include_parked=True)+ else:+ actual = profiles.profiles_to_serve(True)+ assert dict(actual) == ({'default': root, 'worker': secondary} if include_parked else {'default': root})+ assert profiles.parked_marker_path(secondary) == secondary / 'gateway.parked'+ assert profiles.profile_is_parked(secondary)++[email protected]('multiplex', [False, True])+def test_default_marker_is_ignored_with_one_warning(homes, caplog, multiplex):+ from hermes_cli.profiles import profiles_to_serve+ root, _ = homes+ (root / 'gateway.parked').touch()+ for _ in range(2):+ assert 'default' in dict(profiles_to_serve(multiplex))+ warnings = [r for r in caplog.records if 'gateway.parked' in r.message]+ assert len(warnings) == 1+ assert warnings[0].levelname == 'WARNING'++[email protected]('verb', ['stop', 'start', 'restart'])+def test_cli_lifecycle_orders_marker_before_socket(homes, monkeypatch, capsys, verb):+ from hermes_cli import gateway as gw+ from gateway import control_socket+ root, secondary = homes+ marker = secondary / 'gateway.parked'+ owner = SimpleNamespace(home=root, profile_label='default', profiles=('default', 'worker'),+ describe=lambda: 'test host')+ monkeypatch.setenv('HERMES_HOME', str(secondary))+ monkeypatch.setattr(gw, '_current_profile_name', lambda: 'worker')+ monkeypatch.setattr(gw, '_refuse_from_inside_gateway', lambda *a: None)+ monkeypatch.setattr(gw, 'find_gateway_pids', lambda **kw: [])+ monkeypatch.setattr(gw, '_served_by_another_host_gateway', lambda *a: owner)+ monkeypatch.setattr(gw, 'named_profile_served_by_running_multiplexer', lambda *a: True)+ monkeypatch.setattr(gw, '_host_multiplexer_for_all_verb', lambda: owner)+ calls = []++ def unserve(home, name):+ assert home == root and name == 'worker'+ assert marker.exists() is (verb == 'stop')+ calls.append('unserve')+ return {'unserved': name, 'served_profiles': ['default']}++ def serve(home, name):+ assert home == root and name == 'worker'+ assert not marker.exists()+ calls.append('serve')+ return {'served': name, 'served_profiles': ['default', name]}++ monkeypatch.setattr(control_socket, 'request_unserve_profile', unserve, raising=False)+ monkeypatch.setattr(control_socket, 'request_serve_profile_hot', serve, raising=False)+ if verb == 'start':+ marker.touch()+ getattr(gw, '_cmd_' + verb)(SimpleNamespace())+ assert calls == {'stop': ['unserve'], 'start': ['serve'], 'restart': ['unserve', 'serve']}[verb]+ assert marker.exists() is (verb == 'stop')+ output = capsys.readouterr().out+ assert {'stop': "Profile 'worker' parked; its bots and cron are stopped.",+ 'start': "Profile 'worker' served", 'restart': "Profile 'worker' restarted"}[verb] in output+++def test_parked_status_and_topology_keep_roster(homes, monkeypatch, capsys):+ from hermes_cli import gateway as gw, profiles+ from hermes_cli.web_server_gateway import _collect_profile_gateway_topology+ root, secondary = homes+ (secondary / 'gateway.parked').touch()+ monkeypatch.setenv('HERMES_HOME', str(secondary))+ monkeypatch.setattr(gw, '_current_profile_name', lambda: 'worker')+ monkeypatch.setattr(profiles, 'get_active_profile_name', lambda: 'worker')+ monkeypatch.setattr(profiles, '_check_gateway_running', lambda home: False)+ gw._cmd_status(SimpleNamespace())+ assert 'parked (hermes -p worker gateway start)' in capsys.readouterr().out+ topology = _collect_profile_gateway_topology()+ assert topology['profiles'] == ['default', 'worker']+ assert topology['parked_profiles'] == ['worker']+++def test_parked_profile_keeps_implicit_host_multiplexed(homes, monkeypatch):+ from gateway.config import GatewayConfig+ from hermes_cli import gateway_migrate+ from hermes_cli.gateway_multiplex_mode import resolve_multiplex_mode+ _, secondary = homes+ (secondary / 'gateway.parked').touch()+ monkeypatch.setattr(gateway_migrate, '_host_supports_migration', lambda: None)+ monkeypatch.setattr(gateway_migrate, 'build_migration_plan', lambda: SimpleNamespace(+ standalone_secondaries=[], blocked=False))+ config = GatewayConfig()+ assert resolve_multiplex_mode(config).enabled+++def test_dashboard_exposes_parked_profile(homes, monkeypatch):+ from fastapi.testclient import TestClient+ from hermes_cli import web_server, profiles+ _, secondary = homes+ (secondary / 'gateway.parked').touch()+ monkeypatch.setattr(profiles, '_check_gateway_running', lambda home: False)+ with TestClient(web_server.app) as client:+ response = client.get('/api/status')+ assert response.status_code == 200+ assert response.json()['parked_profiles'] == ['worker']++[email protected]('host_running', [False, True])+def test_start_unparks_without_host_rendezvous(homes, monkeypatch, capsys, host_running):+ from hermes_cli import gateway as gw, gateway_multiplex_served as served+ from gateway import control_socket+ root, secondary = homes+ marker = secondary / 'gateway.parked'+ marker.touch()+ monkeypatch.setenv('HERMES_HOME', str(secondary))+ monkeypatch.setattr(gw, '_current_profile_name', lambda: 'worker')+ monkeypatch.setattr(gw, '_host_multiplexer_for_all_verb', lambda: None)+ monkeypatch.setattr(served, 'live_default_gateway_pid', lambda: 42 if host_running else None)+ calls = []++ def serve(home, name):+ assert home == root and name == 'worker' and not marker.exists()+ calls.append('serve')+ return {'served': name}++ def normal_start(**kw):+ assert not marker.exists()+ calls.append('normal')++ monkeypatch.setattr(control_socket, 'request_serve_profile_hot', serve)+ monkeypatch.setattr(gw, '_guard_named_profile_under_multiplexer', normal_start)+ monkeypatch.setattr(gw, '_dispatch_via_service_manager_if_s6', lambda *a: True)+ gw._cmd_start(SimpleNamespace())+ assert not marker.exists()+ assert calls == (['serve'] if host_running else ['normal'])+++def test_default_status_distinguishes_served_and_parked(homes, monkeypatch, capsys):+ from hermes_cli import gateway as gw+ from hermes_cli.gateway_profile_lifecycle import print_parked_status+ root, secondary = homes+ (secondary / 'gateway.parked').touch()+ monkeypatch.setattr(gw, '_current_profile_name', lambda: 'default')+ monkeypatch.setattr(gw, 'host_multiplexer_serving', lambda: SimpleNamespace(+ home=root, profiles=('default',)))+ assert print_parked_status() is False+ output = capsys.readouterr().out+ assert 'Served profiles: default' in output+ assert "Profile 'worker': parked" in outputdiff --git a/tests/hermes_cli/test_gateway_multiplex_served_record.py b/tests/hermes_cli/test_gateway_multiplex_served_record.pyindex f325d31379e..809282a9932 100644--- a/tests/hermes_cli/test_gateway_multiplex_served_record.py+++ b/tests/hermes_cli/test_gateway_multiplex_served_record.py@@ -151,7 +151,7 @@ def test_recycled_pid_does_not_lend_a_stale_record_its_served_profiles(served_ro@pytest.mark.parametrize("verb", ["start", "install", "restart"])-def test_service_verbs_refuse_served_profile_with_exit_78(served_root, monkeypatch, verb):+def test_service_verbs_do_not_start_a_second_gateway(served_root, monkeypatch, verb):import hermes_cli.gateway as gwcalls: list = []monkeypatch.setattr(gw, "_service_backend", lambda: "systemd")@@ -163,9 +163,19 @@ def test_service_verbs_refuse_served_profile_with_exit_78(served_root, monkeypatmonkeypatch.setattr(gw, "is_termux", lambda: False)fn = getattr(gw, f"_cmd_{verb}")ns = argparse.Namespace(system=False, all=False, force=False, run_as_user=None)- with contextlib.redirect_stdout(io.StringIO()), pytest.raises(SystemExit) as exc:+ if verb == "restart":+ from gateway import control_socket+ lifecycle = []+ monkeypatch.setattr(control_socket, "request_unserve_profile",+ lambda home, name: lifecycle.append("unserve") or {"unserved": name})+ monkeypatch.setattr(control_socket, "request_serve_profile_hot",+ lambda home, name: lifecycle.append("serve") or {"served": name})fn(ns)- assert exc.value.code == gw.GATEWAY_FATAL_CONFIG_EXIT_CODE and calls == []+ assert lifecycle == ["unserve", "serve"] and calls == []+ else:+ with contextlib.redirect_stdout(io.StringIO()), pytest.raises(SystemExit) as exc:+ fn(ns)+ assert exc.value.code == gw.GATEWAY_FATAL_CONFIG_EXIT_CODE and calls == []ns.force = Truewith contextlib.redirect_stdout(io.StringIO()):@@ -245,13 +255,18 @@ def test_dashboard_lifecycle_verbs_target_the_multiplexer(served_root, monkeypatassert multiplexed_profile_refusal("coder", "stop") is None-def test_cli_stop_refuses_for_a_served_profile_without_its_own_gateway(served_root, monkeypatch):+def test_cli_stop_parks_when_host_control_socket_is_unavailable(served_root, monkeypatch):import hermes_cli.gateway as gw+ from gateway import control_socketmonkeypatch.setattr(gw, "find_gateway_pids", lambda *a, **k: [])monkeypatch.setattr(gw, "_refuse_from_inside_gateway", lambda *a, **k: None)- with contextlib.redirect_stdout(io.StringIO()), pytest.raises(SystemExit) as exc:+ monkeypatch.setattr(control_socket, "request_unserve_profile", lambda home, name: None)+ output = io.StringIO()+ with contextlib.redirect_stdout(output):gw._cmd_stop(argparse.Namespace(system=False, all=False))- assert exc.value.code == gw.GATEWAY_FATAL_CONFIG_EXIT_CODE+ assert (served_root / "profiles" / "coder" / "gateway.parked").exists()+ assert "immediate stop was not confirmed" in output.getvalue()+ assert "next rescan (within 30s)" in output.getvalue()def test_the_multiplexer_restart_names_the_root_even_under_a_sticky_active_profile(served_root, monkeypatch):diff --git a/tui_gateway/launch_profile_policy.py b/tui_gateway/launch_profile_policy.pyindex 5b2213e27e2..553eeb70f77 100644--- a/tui_gateway/launch_profile_policy.py+++ b/tui_gateway/launch_profile_policy.py@@ -62,7 +62,7 @@ def _servable_profile_homes() -> set:from hermes_constants import named_profile_has_servable_identityfrom hermes_cli.profiles import profiles_to_serve- homes = {Path(home).resolve() for name, home in profiles_to_serve(multiplex=True, include_standalone=True)+ homes = {Path(home).resolve() for name, home in profiles_to_serve(multiplex=True, include_standalone=True, include_parked=True)if name == "default" or named_profile_has_servable_identity(home)}homes.add(Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes").resolve())return homes