The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
teknium11eebdfa164db
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 59869f81e3d,0c4b133aaf1..662662cbc31--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@@ -23,9 -22,9 +23,10 @@@ import { serverOwnsComposerQueue } froimport { $hudMode } from '@/store/hud'import { clearNotifications, notify, notifyError } from '@/store/notifications'import { consumePendingCredentialWarning, requestDesktopOnboarding } from '@/store/onboarding'+import { trackPendingSubmission } from '@/store/pending-submissions'import { isStoredTranscriptReadOnly } from '@/store/read-only-transcript'import {+ $activeSessionId,$sessions,resolveComposerSessionKey,setActiveSessionId,diff --cc gateway/platforms/api_server_openai_routes.pyindex c06f419b3bc,c64d1b71340..ce902f31b52--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@@ -1030,30 -973,9 +1032,30 @@@ class OpenAICompatRoutesMixinstore = _coerce_request_bool(body.get("store"), default=True)if conversation and previous_response_id:return _error_response("Cannot use both 'conversation' and 'previous_response_id'", 400)+ stream = _coerce_request_bool(body.get("stream"), default=False)+ durable_key = None+ idempotency_key = request.headers.get('Idempotency-Key')+ canonical = getattr(self.gateway_runner, 'session_authority', None) is not None+ if canonical and idempotency_key:+ # An exact retry replays the committed response BEFORE the conversation name is+ # expanded: the first success already advanced the conversation, so re-expanding+ # would build a different admission payload and refuse the retry as a conflict.+ # Streaming and nonstreaming share the record: transport mode is not identity.+ from gateway.platforms.api_server import _make_request_fingerprint+ idempotency_scope = self._run_idempotency_scope(request)+ durable_key = (f'idem:{idempotency_scope}:{idempotency_key}',+ _make_request_fingerprint(body, keys=_RESPONSES_FINGERPRINT_KEYS))+ replay = self._response_store.get(durable_key[0])+ if replay is not None:+ if replay.get('fingerprint') != durable_key[1]:+ from gateway.platforms.api_server import _openai_error+ return web.json_response(_openai_error('admission_conflict', code='admission_conflict'), status=409)+ if stream:+ return await self._replay_sse_responses(request, replay)+ return web.json_response(replay['response'], headers=replay.get('headers') or {})if conversation:# A conversation name resolves to its latest response_id (unknown = new conversation).- previous_response_id = self._response_store.get_conversation(conversation)+ previous_response_id = self._current_response_store().get_conversation(conversation)input_messages: List[Dict[str, Any]] = []if isinstance(raw_input, str):@@@ -1201,11 -1114,9 +1203,12 @@@"created_at": created_at, "model": body.get("model", self._model_name),"output": self._extract_output_items(result, start_index=output_start_index),"usage": _responses_usage_payload(usage)}+ if response_data['status'] == 'failed':+ response_data['error'] = {'code': 'agent_error', 'message': _redact_api_error_text(+ result.get('error') or 'The admitted turn failed.')}if store:- self._response_store.put(response_id, {+ response_store = self._current_response_store()+ response_store.put(response_id, {"response": response_data, "conversation_history": full_history,"instructions": instructions, "session_id": _effective_session_id})if conversation:diff --cc gateway/run_bootstrap.pyindex ecb309fc448,00000000000..1fa211c259amode 100644,000000..100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@@ -1,761 -1,0 +1,766 @@@+"""Process startup phases; diagnostics remain in the gateway facade."""+from __future__ import annotations++import threading+from typing import Any, Optional++from gateway.config import GatewayConfig++async def _start_gateway_replace_existing_instance(existing_pid: int, replace: bool) -> bool:+ """Handle a live gateway PID under this HERMES_HOME: replace it (``--replace``) or refuse.+ Returns False when startup must abort (refused, permission denied, target still alive)."""+ from gateway.run import (_clear_takeover_marker_quiet, _replace_target_belongs_to_other_profile, _wait_for_pid_exit, get_hermes_home, logger, suppress)+ from gateway.status import get_process_start_time, remove_pid_file, terminate_pid+ if not replace:+ hermes_home = str(get_hermes_home())+ logger.error(+ "Another gateway instance is already running (PID %d, HERMES_HOME=%s) and did not "+ "publish a host record this process could attach to.",+ existing_pid, hermes_home)+ print(+ f"\n❌ A gateway already owns this host (PID {existing_pid}).\n"+ f" One gateway per host serves every profile, so there is nothing to start here.\n"+ f" Attach is impossible: PID {existing_pid} published no usable host record\n"+ f" (an older build, or an unwritable lock directory).\n"+ f" Take the host over: hermes gateway run --replace\n"+ f" Or stop it first: hermes gateway stop\n")+ return False++ # Never signal a process not provably ours (a poisoned PID record → cross-profile restart loop).+ if _replace_target_belongs_to_other_profile(existing_pid):+ from gateway.status import _get_process_hermes_home+ logger.error(+ "Refusing --replace: PID %d cannot be proven to belong "+ "to this profile's gateway (HERMES_HOME %s). Remove the "+ "stale PID record or stop the owning profile explicitly.",+ existing_pid, _get_process_hermes_home())+ return False+ existing_start_time = get_process_start_time(existing_pid)+ logger.info("Replacing existing gateway instance (PID %d) with --replace.", existing_pid)+ # Takeover marker: target exits 0 on our SIGTERM (exit 1 → systemd Restart=on-failure flap loop).+ try:+ from gateway.status import write_takeover_marker+ write_takeover_marker(existing_pid)+ except Exception as e:+ logger.debug("Could not write takeover marker: %s", e)+ # Snapshot children BEFORE signalling: reparented orphans are invisible yet hold scoped token locks.+ try:+ from gateway.status import _snapshot_gateway_children+ _old_gateway_children = _snapshot_gateway_children(existing_pid)+ except Exception:+ _old_gateway_children = []+ try:+ terminate_pid(existing_pid, force=False)+ except ProcessLookupError:+ pass # Already gone+ except (PermissionError, OSError):+ logger.error("Permission denied killing PID %d. Cannot replace.", existing_pid)+ _clear_takeover_marker_quiet()+ return False+ # Up to 10s for SIGTERM, then SIGKILL.+ if not await _wait_for_pid_exit(existing_pid, 20, 0.5):+ logger.warning("Old gateway (PID %d) did not exit after SIGTERM, sending SIGKILL.", existing_pid)+ old_gateway_exited = False+ try:+ terminate_pid(existing_pid, force=True, expected_start_time=existing_start_time)+ except ProcessLookupError:+ old_gateway_exited = True+ except (PermissionError, OSError):+ pass+ # Confirm SIGKILL took (D-state/zombie) before clearing PID/locks, or two gateways share a token.+ if not old_gateway_exited and not await _wait_for_pid_exit(existing_pid, 20, 0.25):+ logger.error(+ "Old gateway (PID %d) still appears alive after SIGKILL; "+ "aborting replacement to avoid a duplicate gateway.", existing_pid)+ _clear_takeover_marker_quiet()+ return False+ # Reap orphaned children (POSIX; mirrors Windows taskkill /T) so they stop holding scoped token locks.+ try:+ from gateway.status import reap_gateway_children+ reap_gateway_children(_old_gateway_children, parent_pid=existing_pid)+ except Exception:+ logger.debug("Child reap for replaced gateway PID %d failed", existing_pid, exc_info=True)+ remove_pid_file()+ # remove_pid_file() is a no-op when the PID doesn't match; force-unlink covers a crashed old process.+ with suppress(Exception):+ (get_hermes_home() / "gateway.pid").unlink(missing_ok=True)+ # The old process may not have consumed the marker (SIGKILL'd before its handler read it).+ _clear_takeover_marker_quiet()+ # Stopped (Ctrl+Z) processes don't release scoped locks on exit; stale lock files block the new gateway.+ try:+ from gateway.status import release_all_scoped_locks+ _released = release_all_scoped_locks(owner_pid=existing_pid, owner_start_time=existing_start_time)+ if _released:+ logger.info("Released %d stale scoped lock(s) from old gateway.", _released)+ except Exception:+ pass+ return True+++def _start_gateway_configure_logging(verbosity: Optional[int]) -> None:+ """Sync bundled skills, set up file logging + startup security audit, and the -v/-q stderr handler."""+ from gateway.run import (_best_effort, _gateway_stderr_formatter, _hermes_home, logging)+ def _sync_skills() -> None:+ from tools.skills_sync import sync_skills+ sync_skills(quiet=True)++ _best_effort(_sync_skills)++ # Centralized logging (agent.log INFO+, errors.log WARNING+, gateway.log gateway-only); idempotent.+ from hermes_logging import setup_logging, _safe_stderr+ setup_logging(hermes_home=_hermes_home, mode="gateway")++ def _security_audit() -> None:+ # Warn-on-load, never blocks: surfaces root / weak-SSH / unauthenticated-listener exposure.+ from hermes_cli.security_audit_startup import log_startup_security_warnings++ def _raw_cfg():+ from hermes_cli.config import read_raw_config+ return read_raw_config()++ log_startup_security_warnings(hermes_home=_hermes_home, config=_best_effort(_raw_cfg))++ _best_effort(_security_audit, "Startup security audit failed (non-fatal): %s")++ # Optional stderr handler from -v/-q: None (quiet) = none; 0 = WARNING; 1 = INFO; 2+ = DEBUG.+ if verbosity is not None:+ _stderr_level = {0: logging.WARNING, 1: logging.INFO}.get(verbosity, logging.DEBUG)+ _stderr_handler = logging.StreamHandler(_safe_stderr())+ _stderr_handler.setLevel(_stderr_level)+ _stderr_handler.setFormatter(_gateway_stderr_formatter())+ root = logging.getLogger()+ root.addHandler(_stderr_handler)+ if _stderr_level < root.level: # so DEBUG records can reach the handler+ root.setLevel(_stderr_level)+++def _start_gateway_make_shutdown_signal_handler(runner, _signal_initiated_shutdown: list):+ """Build the SIGINT/SIGTERM handler; ``_signal_initiated_shutdown[0]`` records an unplanned signal."""+ from gateway.run import (_best_effort, _hermes_home, asyncio, logger, signal)+ planned_stop_seen = [False]++ def shutdown_signal_handler(received_signal=None):+ # Planned --replace takeover (sibling marked this PID): exit 0 so systemd won't revive us.+ def _takeover() -> bool:+ from gateway.status import consume_takeover_marker_for_self+ return consume_takeover_marker_for_self()++ # Planned stop: CLI marks first, else its SIGTERM looks like an external kill. SIGINT = Ctrl+C.+ def _planned_stop() -> bool:+ from gateway.status import consume_planned_stop_marker_for_self+ return consume_planned_stop_marker_for_self()++ # Fast (<10ms) sync snapshot: stdlib + /proc, no subprocesses (`ps aux` here once blocked ~3s).+ def _snapshot():+ from gateway.shutdown_forensics import snapshot_shutdown_context+ return snapshot_shutdown_context(received_signal)++ planned_takeover = bool(_best_effort(_takeover, "Takeover marker check failed: %s"))+ planned_stop = received_signal == signal.SIGINT or (+ not planned_takeover and bool(_best_effort(_planned_stop, "Planned stop marker check failed: %s")))+ # `hermes gateway stop` writes the marker, THEN signals: the planned-stop watcher can consume+ # the marker in between, and the CLI's own SIGTERM must not then read as an external kill.+ if planned_stop:+ planned_stop_seen[0] = True+ elif planned_stop_seen[0] and not planned_takeover:+ planned_stop = True+ _shutdown_ctx = _best_effort(_snapshot, "snapshot_shutdown_context failed: %s")+ sig_name = _shutdown_ctx["signal"] if _shutdown_ctx else None++ if planned_takeover:+ logger.info("Received %s as a planned --replace takeover — exiting cleanly", sig_name or "SIGTERM")+ elif planned_stop:+ logger.info("Received %s as a planned gateway stop — exiting cleanly", sig_name or "SIGTERM/SIGINT")+ else:+ # Mirrored onto the runner so _stop_impl suppresses the gateway_state=stopped persist for+ # unexpected signals; operator stops take the `planned_stop` branch and leave it False (DO persist).+ _signal_initiated_shutdown[0] = runner._signal_initiated_shutdown = True+ logger.info("Received %s — initiating shutdown", sig_name or "SIGTERM/SIGINT")++ if _shutdown_ctx is not None:+ def _log_context() -> None:+ # The most useful line for "gateway keeps dying" tickets.+ from gateway.shutdown_forensics import format_context_for_log+ logger.warning("Shutdown context: %s", format_context_for_log(_shutdown_ctx))++ def _diagnostic() -> None:+ # Heavyweight (ps auxf, pstree, dmesg), detached so it finishes even if our cgroup is torn+ # down; bounded by an internal timeout, never blocks.+ from gateway.shutdown_forensics import spawn_async_diagnostic+ spawn_async_diagnostic(+ _hermes_home / "logs" / "gateway-shutdown-diag.log", _shutdown_ctx["signal"], timeout_seconds=5.0)++ _best_effort(_log_context, "format_context_for_log failed: %s")+ _best_effort(_diagnostic, "spawn_async_diagnostic failed: %s")+ if not planned_takeover:+ # Supervisor/operator SIGNAL stop (bootout, kickstart -k, systemd, s6, bare kill) — the+ # only kind launchd times with ExitTimeOut. In-band SIGUSR1 restarts never pass through+ # here, and a sibling-driven --replace takeover is not launchd-timed either, so both+ # keep the configured drain. _stop_impl uses this to cap the drain to the live budget.+ runner._stop_requested_by_signal = True+ asyncio.create_task(runner.stop())+ return shutdown_signal_handler+++def _start_gateway_claim_pid_file(force: bool = False) -> bool:+ """Claim the runtime lock + PID file (O_EXCL winner is the authoritative gateway). False = lost."""+ from gateway.run import (_claim_host_gateway_role, logger, os)+ import atexit+ from gateway.status import (+ acquire_gateway_runtime_lock, get_running_pid, release_gateway_runtime_lock,+ remove_pid_file, write_pid_file)+ _current_pid = get_running_pid()+ if _current_pid is not None and _current_pid != os.getpid():+ logger.error("Another gateway instance (PID %d) started during our startup. "+ "Exiting to avoid double-running.", _current_pid)+ return False+ if not acquire_gateway_runtime_lock():+ logger.error("Gateway runtime lock is already held by another instance. Exiting.")+ return False+ try:+ write_pid_file()+ except FileExistsError:+ release_gateway_runtime_lock()+ logger.error("PID file race lost to another gateway instance. Exiting.")+ return False+ atexit.register(remove_pid_file)+ atexit.register(release_gateway_runtime_lock)+ _claim_host_gateway_role(force=force)+ return True+++async def _start_gateway_start_control_socket(runner):+ """Start the gateway control socket (identify/status/pause-for-update); None when unavailable."""+ from gateway.run import (asyncio, logger, os, threading)+ import atexit+ import concurrent.futures+ _control_server = None+ try:+ # Started immediately after the PID-file claim: winning that O_EXCL race is the moment this process+ # becomes the authoritative gateway for its HERMES_HOME, so from here on "does a socket answer?" is+ # a truthful liveness/identity query for updater and fleet consumers. Strictly non-fatal: a bind+ # 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, build_identify_payload- 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+ descriptor = runner.session_runtime_descriptor++ def _identify_runtime():+ payload = build_identify_payload()+ payload.update({key: descriptor[key] for key in (+ "instance_id", "runtime_protocol", "authority_epoch", "state", "api_origin",+ "served_profiles", "parked_profiles", "capabilities") if key in descriptor})+ if getattr(runner, '_draining', False):+ payload.update(state='draining', capabilities=[])+ payload["supervisor"] = {"manual": "none", "desktop": "none"}.get(+ payload.get("supervisor"), payload.get("supervisor", "none"))+ return payload+ # 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.+ # pause-for-update (#92091 step 2): the updater asks this gateway to drain in-flight turns and exit+ # cleanly — releasing every venv file handle — instead of being tree-killed mid-turn. Same drain+ # path as SIGUSR1/service restarts (request_restart(via_service=True)); the updater (or the service+ # manager) relaunches after the code swap.+ _main_loop = asyncio.get_running_loop()++ def _pause_for_update_handler() -> dict:+ try:+ from hermes_cli.gateway import _get_restart_drain_timeout+ _drain = float(_get_restart_drain_timeout())+ except Exception:+ _drain = 30.0+ accepted_box: list[bool] = []+ _done = threading.Event()++ def _request() -> None:+ try:+ accepted_box.append(runner.request_restart(detached=False, via_service=True))+ finally:+ _done.set()++ _main_loop.call_soon_threadsafe(_request)+ _done.wait(timeout=5.0)+ accepted = bool(accepted_box and accepted_box[0])+ return {+ "pausing": accepted, "already_stopping": not accepted,+ "pid": os.getpid(), "drain_timeout": _drain}++ def _rescan_profiles_handler() -> dict:+ """``hermes profile create/delete`` asks the multiplexer to reconcile ``profiles/`` now+ (the watcher also rescans periodically). Runs on the socket executor: marshal onto the loop+ and wait briefly so the caller learns whether the profile is served."""+ if not getattr(runner.config, "multiplex_profiles", False):+ return {"multiplex": False, "served_profiles": runner.served_profile_names()}+ future = asyncio.run_coroutine_threadsafe(+ runner.reconcile_served_profiles(reason="control-socket"), _main_loop)+ try:+ # Bounded: a token-less create reconciles in milliseconds; a credential-add whose adapter+ # connect outlasts this keeps running and the caller sees ``pending`` (not an error).+ return {"multiplex": True, **future.result(timeout=5.0)}+ except concurrent.futures.TimeoutError:+ return {"multiplex": True, "pending": True, "served_profiles": runner.served_profile_names()}++ _control_server = GatewayControlServer(+ verb_handlers={"pause-for-update": _pause_for_update_handler, "identify": _identify_runtime,+ "rescan-profiles": _rescan_profiles_handler,+ "migrate-profile-identity": migrate_profile_identity_verb(runner),++ "unserve-profile": unserve_profile_verb(runner),++ "serve-profile": serve_profile_verb(runner),+ "purge-profile-identity": purge_profile_identity_verb(runner),+ # A plugin installed/enabled by another process loads now and re-wires the+ # live adapters' handlers (#87770); tools/prompt still wait for the next session.+ "reload-plugins": reload_plugins_verb(runner, _main_loop)})+ _control_server.ticket_store = runner.session_ticket_store+ if not await _control_server.start():+ _control_server = None+ else:+ atexit.register(_control_server.cleanup_files)+ # Hosted-room transports install onto this listener; bind it here so every launcher+ # that starts the control socket (not only start_gateway) exposes it.+ runner.session_control_server = _control_server+ except Exception as _cs_exc:+ logger.debug("Control socket startup failed (non-fatal): %s", _cs_exc)+ _control_server = None+ return _control_server+++def _start_gateway_start_cron_and_housekeeping(runner):+ """Start the cron scheduler thread + gateway housekeeping thread; returns+ ``(cron_stop, cron_provider, cron_thread, housekeeping_thread)``."""+ from gateway.run import (Dict, Platform, _cron_profile_gate, _cron_tick_profile_homes, _start_gateway_housekeeping, asyncio, logger, threading)+ # The event loop is passed so cron delivery can use live adapters (E2EE support).+ from cron.scheduler_provider import (+ InProcessCronScheduler, resolve_cron_scheduler, scheduler_for_profile_mode)+ cron_stop = threading.Event()+ # ONE gateway process per host multiplexes every profile, so its cron ticker owns EVERY+ # profile's store — `gateway.multiplex_profiles` gates adapters, not cron. Gating the tick set+ # on that flag left every non-launch profile's jobs in a store no ticker visited: they+ # silently never fired.+ try:+ cron_profile_homes = _cron_tick_profile_homes(runner.config)+ except Exception as exc:+ logger.warning("Could not resolve profile homes for cron: %s", exc)+ cron_profile_homes = []+ # External providers own one unscoped remote registry, so they can only serve a single home.+ cron_provider = scheduler_for_profile_mode(+ resolve_cron_scheduler(), multiplex_profiles=len(cron_profile_homes) > 1)+ cron_start_kwargs: Dict[str, Any] = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()}++ if isinstance(cron_provider, InProcessCronScheduler) and cron_profile_homes:+ # Live enumerator: the ticker re-reads profiles/ every cycle so a profile created while+ # the gateway runs gets its jobs fired without a restart (hot-serve).+ cron_start_kwargs["profile_homes"] = lambda: _cron_tick_profile_homes(runner.config)+ # Stand down, per tick, for a profile whose OWN gateway process ticks it.+ cron_start_kwargs["profile_gate"] = _cron_profile_gate+ # Per-profile adapters so each profile's cron output goes via its own bot, not the+ # default's. Absent (no multiplexed adapters), delivery for a secondary profile falls+ # back to the primary's routed adapters or fails closed — the job still FIRES.+ cron_start_kwargs["profile_adapters"] = getattr(runner, "_profile_adapters", None)+ # runner.adapters belongs to the LAUNCH profile (``default``, or the ``--profile``+ # name); naming it keeps the ticker from routing a secondary's cron through that bot+ # and lets a named multiplexer's own jobs reuse its live adapters.+ cron_start_kwargs["default_profile"] = runner._primary_profile_name+ logger.info(+ "Cron scheduler will tick %d profile(s): %s", len(cron_profile_homes),+ [p[0] if isinstance(p, tuple) else p for p in cron_profile_homes])++ # Only the in-process ticker polls local due jobs, so only it gets the external-drain dispatch gate.+ if isinstance(cron_provider, InProcessCronScheduler):+ cron_start_kwargs["can_dispatch"] = lambda: not (+ runner._draining or runner._external_drain_active)+ # Supervised: a ticker that dies without a stop request is respawned by housekeeping (#111010).+ from cron.scheduler_thread import SupervisedTickerThread+ cron_thread = SupervisedTickerThread(+ cron_provider.start, args=(cron_stop,), kwargs=cron_start_kwargs, stop_event=cron_stop)+ from gateway.runtime_ownership import process_ownership+ process_ownership.start_writer(cron_thread)++ # External providers fire over loopback HTTP to THIS process's api_server; if it never came up (usually+ # API_SERVER_KEY missing) every fire fails while manual runs work — misread as a job bug. Say it ONCE.+ if not isinstance(cron_provider, InProcessCronScheduler):+ try:+ _has_api_server = Platform.API_SERVER in (runner.adapters or {})+ except Exception:+ _has_api_server = True # never let the tell break startup+ if not _has_api_server:+ logger.warning(+ "Cron provider '%s' is active but the api_server adapter is "+ "NOT running in this gateway — scheduled fires arrive over "+ "loopback HTTP and will all fail (jobs only run when "+ "triggered manually). Most common cause: API_SERVER_KEY is "+ "missing from this gateway process's environment. Restart "+ "the gateway through its supervisor (`hermes gateway "+ "restart`) so the profile env loads.",+ getattr(cron_provider, "name", "external"))++ # Gateway-only housekeeping runs independently of the cron provider; shares cron_stop for shutdown.+ housekeeping_thread = threading.Thread(+ target=_start_gateway_housekeeping, args=(cron_stop,),+ kwargs={"adapters": runner.adapters, "loop": asyncio.get_running_loop(),+ "cron_provider": cron_provider, "runner": runner, "cron_thread": cron_thread},+ daemon=True, name="gateway-housekeeping")+ process_ownership.start_writer(housekeeping_thread)+ return cron_stop, cron_provider, cron_thread, housekeeping_thread+++async def _start_gateway_shutdown_tail(+ runner, _control_server, cron_stop: threading.Event, cron_provider,+ cron_thread: Any, housekeeping_thread: threading.Thread,+ _planned_stop_watcher_stop: threading.Event, _planned_stop_watcher_thread: threading.Thread,+ _signal_initiated_shutdown: list) -> bool:+ """Post-``wait_for_shutdown`` teardown; returns the process exit verdict (True = exit 0)."""+ from gateway.run import (_CRON_SHUTDOWN_DRAIN_TIMEOUT, _HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT, _await_thread_exit, _best_effort, _resolve_gateway_exit_verdict, _shutdown_mcp_servers_nonblocking, _stop_cron_provider, logger, suppress)+ # Control socket first: once shutdown begins we are no longer a truthful "serving here" answer and a+ # successor must be able to bind. Early-exit paths rely on the atexit cleanup_files hook instead.+ if _control_server is not None:+ try:+ await _control_server.stop()+ except Exception:+ logger.debug("Control socket stop failed (non-fatal)", exc_info=True)++ def _stop_keepalive() -> None:+ from hermes_cli.nous_auth_keepalive import stop_nous_auth_keepalive+ stop_nous_auth_keepalive()++ _best_effort(_stop_keepalive)++ # Never join(): an in-flight cron delivery is a coroutine on THIS loop; a sync join would drop it.+ # Stop cron scheduler + housekeeping cleanly. These MUST be awaited cooperatively, not join()ed. A cron+ # delivery in flight when the gateway restarts is a coroutine scheduled onto THIS event loop+ # (safe_schedule_threadsafe); the ticker thread is blocked on its future.result(). A synchronous+ # cron_thread.join() would block the loop, so that delivery could never run — it timed out and the+ # message was silently dropped (#58818). Awaiting keeps the loop alive so the in-flight delivery+ # finishes before we tear down.+ cron_stop.set()+ _stop_cron_provider(cron_provider)+ if not await _await_thread_exit(cron_thread, timeout=_CRON_SHUTDOWN_DRAIN_TIMEOUT):+ logger.warning("Cron ticker did not exit within %.0fs of shutdown — an in-flight "+ "delivery may have been dropped.", _CRON_SHUTDOWN_DRAIN_TIMEOUT)+ await _await_thread_exit(housekeeping_thread, timeout=_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT)++ # Stop the planned-stop watcher (daemon=True so this is belt-and-suspenders).+ _planned_stop_watcher_stop.set()+ _planned_stop_watcher_thread.join(timeout=2)++ # Never suppressed: a raise here is a real teardown failure (it once hid a changed signature,+ # leaving every MCP connection and the shared loop up while the gateway reported a clean exit).+ try:+ await _shutdown_mcp_servers_nonblocking(config=getattr(runner, "config", None))+ except Exception:+ logger.warning("MCP shutdown failed; connections may be left open", exc_info=True)++ # 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).+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])++++def _launch_home_may_multiplex(config=None) -> bool:+ """A named profile serving ``default`` as a secondary splits default's local sessions between+ the two stores (routing rows follow the launch home, receipts follow the authority), so the+ multiplexer is the default profile's job.++ An EXPLICIT ``gateway.multiplex_profiles: true`` (config.yaml or ``GATEWAY_MULTIPLEX_PROFILES``)+ on a named launch home exits EX_CONFIG: a config verdict, never a retry. The implicit default+ (unset key, or the retired ``false`` that ``resolve_multiplex_mode`` settles like unset) is not+ the operator's choice, so it is downgraded the way every other implicit-multiplex blocker is:+ this process comes up standalone, says why, and *config* is flipped in place so the boot below+ reserves and serves only the launch profile."""+ from hermes_constants import profile_name_for_home+ from gateway.run import get_hermes_home, logger+ name = profile_name_for_home(get_hermes_home())+ if name in (None, "default"):+ return True+ from hermes_cli.gateway_multiplex_mode import explicit_multiplex_flag+ if config is not None and not explicit_multiplex_flag(get_hermes_home()):+ from hermes_cli.gateway_multiplex_mode import MultiplexDecision, log_multiplex_decision+ decision = MultiplexDecision(+ False, "guard",+ f"profile {name!r} launched the gateway, and only the default profile runs the multiplexer "+ "(start it with `hermes gateway run` from the default profile to serve every profile)")+ config.multiplex_profiles = False+ log_multiplex_decision(decision)+ return True+ from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE+ from gateway.run import _write_runtime_status_quiet+ logger.error(+ "gateway.multiplex_profiles is set on profile %r, but only the default profile can run the "+ "multiplexer. Unset the flag in this profile's config.yaml, or start the gateway from the "+ "default profile (`hermes gateway run`), which serves this profile too.", name)+ _write_runtime_status_quiet(gateway_state="startup_failed", exit_reason="multiplex_requires_default_profile")+ raise SystemExit(GATEWAY_FATAL_CONFIG_EXIT_CODE)+++async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False,+ verbosity: Optional[int] = 0, force: bool = False) -> bool:+ """Start the gateway and run until interrupted; False if it failed to start (non-zero exit so+ systemd can auto-restart). ``replace`` kills any existing instance first (avoids restart-loop+ deadlocks); ``force`` starts without consulting the host owner at all."""+ from gateway.run import (+ GatewayRunner,+ _best_effort,+ _discover_gateway_mcp_tools,+ _enable_multiplex_log_routing,+ _ensure_windows_gateway_venv_imports,+ _gateway_loop_exception_handler,+ _host_attach_or_none,+ _log_standalone_profiles_at_boot,+ _multiplex_profile_homes,+ _refresh_host_gateway_record,+ _resolve_gateway_exit_verdict,+ _run_planned_stop_watcher,+ _shutdown_gateway_health_export,+ _shutdown_mcp_servers_nonblocking,+ _start_gateway_make_restart_signal_handler,+ asyncio,+ get_hermes_home,+ load_gateway_config_for_runner,+ logger,+ os,+ signal,+ suppress,+ threading,+ )+ # Set here (not at import) so incidental gateway.run imports from CLI code don't poison it.+ os.environ["HERMES_EXEC_ASK"] = "1"++ from hermes_cli.resource_limits import apply_nofile_soft_limit+ apply_nofile_soft_limit()++ # Snapshot the revision while sys.modules matches disk so a later `git pull` is detected safely.+ from gateway.code_skew import record_boot_fingerprint+ record_boot_fingerprint()++ # Config verdicts come before the duplicate-instance guard: `--replace` must not stop a healthy+ # gateway for a launch that cannot start.+ resolved_config = config if config is not None else load_gateway_config_for_runner()+ profile_homes = (_multiplex_profile_homes(resolved_config)+ if getattr(resolved_config, 'multiplex_profiles', False) else [])+ if profile_homes and not _launch_home_may_multiplex(resolved_config):+ return False+ if profile_homes and not getattr(resolved_config, 'multiplex_profiles', False):+ profile_homes = [] # implicit default downgraded: this named launch serves only itself++ # Multiplex-only: the ONE host gateway decides first. Attach to it, make it serve this profile,+ # replace it (--replace) or refuse — before anything below binds a port or claims a PID file.+ _host_decision = await _host_attach_or_none(replace, force)+ if _host_decision is not None:+ return _host_decision++ # Duplicate-instance guard scoped to HERMES_HOME (the host record is absent or unusable here).+ from gateway.status import get_running_pid+ existing_pid = get_running_pid()+ if (existing_pid is not None and existing_pid != os.getpid()+ and not await _start_gateway_replace_existing_instance(existing_pid, replace)):+ return False++ from gateway.runtime_ownership import process_ownership, OwnershipConflict+ from gateway.status import remove_pid_file, release_gateway_runtime_lock+ try:+ process_ownership.reserve([get_hermes_home(), *(home for _, home in profile_homes)])+ except OwnershipConflict as exc:+ logger.error("Cannot reserve gateway profiles: %s", exc)+ # A named profile that the LIVE default multiplexer already serves is a configuration+ # verdict (gateway.multiplex_profiles), not a transient fault: exit EX_CONFIG so systemd's+ # RestartPreventExitStatus=78 parks the unit instead of restart-looping (#51228, #97120).+ # Any other same-user contender keeps the ordinary "already running" exit 1.+ from hermes_cli.gateway import named_profile_served_by_running_multiplexer+ if named_profile_served_by_running_multiplexer():+ from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE+ from gateway.run import _write_runtime_status_quiet+ logger.error(+ "The default gateway is running as a profile multiplexer and already serves this profile. "+ "Manage it with `hermes gateway restart` from the default profile instead of starting a "+ "second gateway for the profile.")+ _write_runtime_status_quiet(gateway_state="startup_failed", exit_reason=str(exc))+ raise SystemExit(GATEWAY_FATAL_CONFIG_EXIT_CODE)+ return False+ except OSError as exc:+ logger.error("Cannot reserve gateway profiles: %s", exc)+ return False+ # Freeze discovery: later profile additions must restart and reserve before opening stores.+ if profile_homes:+ resolved_config._runtime_profile_homes = tuple(profile_homes)+ # PID file BEFORE adapters: of two concurrent `run --replace`, only the O_EXCL winner opens sockets.+ # Only --force skips the host-lock refusal. Every generated unit carries --replace, so reading it as+ # --force there disabled the one arbiter of the two-units-at-once race; a replace that took the+ # owner over already freed the lock with that process.+ if not _start_gateway_claim_pid_file(force=force):+ release_gateway_runtime_lock()+ return False++ _control_server = None+ runner = None+ _planned_stop_watcher_stop = None+ try:+ _start_gateway_configure_logging(verbosity)++ runner = GatewayRunner(resolved_config)+ from gateway.run_runtime import initialize_gateway_runtime+ await initialize_gateway_runtime(runner)+ # Multiplex: swap the launch-home file handlers for per-profile routers so each profile's records+ # land in its own logs/. Must run after the runner resolved (possibly None) config and setup_logging.+ # See #82936.+ _enable_multiplex_log_routing(runner.config)+ # ``--replace`` is explicit startup authority, not a durable reconnect policy: GatewayRunner scopes+ # it to cold adapter connects and clears it before the background reconnect watcher starts.+ runner._platform_lock_takeover_on_start = bool(replace)++ # Unexpected signals exit non-zero so service managers revive us; planned stops write a marker first.+ _signal_initiated_shutdown = [False]++ shutdown_signal_handler = _start_gateway_make_shutdown_signal_handler(+ runner, _signal_initiated_shutdown)++ restart_signal_handler = _start_gateway_make_restart_signal_handler(runner)++ loop = asyncio.get_running_loop()++ # Swallow transient network errors from background tasks; one unhandled httpx error would kill us.+ # Issues #31066 / #31110: an unhandled ``telegram.error.TimedOut`` (or peer NetworkError / httpx+ # connection error) in any awaited coroutine would propagate to the loop and kill the gateway process,+ # taking down every profile attached to the same runner. systemd then restarts the service after ~5s but+ # the active conversation turn is lost. The fix is intentionally narrow: only well-known transient+ # network errors are swallowed (and logged with full traceback so the originating call site is still+ # discoverable). Anything else is forwarded to the default handler so real bugs still surface.+ loop.set_exception_handler(_gateway_loop_exception_handler)++ if threading.current_thread() is threading.main_thread():+ # add_signal_handler raises NotImplementedError on Windows; SIGUSR1 is POSIX-only.+ handlers = [(sig, shutdown_signal_handler, (sig,)) for sig in (signal.SIGINT, signal.SIGTERM)]+ if hasattr(signal, "SIGUSR1"):+ handlers.append((signal.SIGUSR1, restart_signal_handler, ())) # windows-footgun: ok — hasattr-guarded+ for sig, handler, args in handlers:+ with suppress(NotImplementedError):+ loop.add_signal_handler(sig, handler, *args) # windows-footgun: ok — suppress(NotImplementedError)+ else:+ logger.info("Skipping signal handlers (not running in main thread).")++ # Windows has no add_signal_handler, so `hermes gateway stop`'s SIGTERM would never drain; poll the+ # planned-stop marker (written BEFORE the kill) instead. Runs everywhere so masked-SIGTERM drains.+ # Windows fallback: asyncio.add_signal_handler raises NotImplementedError on Windows, so `hermes gateway+ # stop`'s SIGTERM (which Python maps to TerminateProcess on Windows) never invokes+ # shutdown_signal_handler. That means the drain loop never runs, mark_resume_pending never fires, and+ # sessions are silently lost across restarts (issue #33778). The fix is a marker-polling thread: `hermes+ # gateway stop` writes the planned-stop marker BEFORE killing, and this thread notices it and drives the+ # same shutdown path the signal handler would have. Runs on every platform (cheap, defensive) so+ # non-signal-bearing environments (Windows native, sandboxed CI runners that mask SIGTERM) still get a+ # clean drain.+ _planned_stop_watcher_stop = threading.Event()+ _planned_stop_watcher_thread = threading.Thread(+ target=_run_planned_stop_watcher,+ args=(_planned_stop_watcher_stop, runner, loop, shutdown_signal_handler), daemon=True,+ name="planned-stop-watcher")+ _planned_stop_watcher_thread.start()++ # Right after the PID claim (which makes us authoritative); non-fatal — consumers fall back to scan.+ _control_server = await _start_gateway_start_control_socket(runner)+ if _control_server is None:+ raise RuntimeError("gateway session bootstrap control listener unavailable")+ # Now the attach channel answers: republish the host record with the settled served set.+ _refresh_host_gateway_record(runner)+ _log_standalone_profiles_at_boot(runner)+ from gateway.run_runtime import start_gateway_runtime_api+ await start_gateway_runtime_api(runner)++ def _lifecycle_record_startup() -> None:+ # Report if the previous life died uncleanly (SIGKILL / OOM / VM death), then claim the+ # sentinel for this life. After the PID-file claim so a --replace loser can't clobber it.+ from gateway.lifecycle_ledger import record_startup+ record_startup()++ def _start_keepalive() -> None:+ from hermes_cli.nous_auth_keepalive import start_nous_auth_keepalive+ start_nous_auth_keepalive()++ _best_effort(_lifecycle_record_startup, "Lifecycle ledger startup record failed: %s")+ _best_effort(_start_keepalive, "Nous auth keepalive did not start: %s")+ _ensure_windows_gateway_venv_imports()++ # discover_mcp_tools() blocks up to 120s; on the loop thread it would freeze platform heartbeats.+ try:+ # MCP tool discovery — run in an executor so the asyncio event loop stays responsive even when a+ # configured MCP server is slow or unreachable. discover_mcp_tools() uses a blocking 120s wait+ # internally; calling it from the loop thread would freeze platform heartbeats (Discord shard,+ # Telegram polling) until it returned. See #16856.+ await _discover_gateway_mcp_tools(runner.config)+ except Exception as e:+ logger.debug("MCP tool discovery failed: %s", e)++ try:+ success = await runner.start()+ except BaseException:+ _shutdown_gateway_health_export(runner)+ raise+ if not success:+ _shutdown_gateway_health_export(runner)+ return False++ def _recover_pending() -> None:+ from gateway.shutdown_flush import recover_pending_to_db+ recovered = recover_pending_to_db(+ session_resolver=runner.session_store.resolve_session_id_for_key,+ )+ if recovered:+ logger.info("Recovered %d pending message(s) from shutdown flush", recovered)++ _best_effort(_recover_pending)+ if runner.should_exit_cleanly:+ _shutdown_gateway_health_export(runner)+ if runner.exit_reason:+ logger.error("Gateway exiting cleanly: %s", runner.exit_reason)+ # Explicit exit codes (GATEWAY_FATAL_CONFIG_EXIT_CODE) must propagate so s6 finish maps 78 → 125.+ if runner.exit_code is not None:+ raise SystemExit(runner.exit_code)+ return True+ if not runner._running:+ # Startup aborted by restart/shutdown before running mode; preserve that path without starting cron.+ try:+ await runner.wait_for_shutdown()+ try:+ await _shutdown_mcp_servers_nonblocking(config=getattr(runner, "config", None))+ except Exception:+ logger.warning("MCP shutdown failed; connections may be left open", exc_info=True)+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])+ finally:+ _shutdown_gateway_health_export(runner)++ cron_stop, cron_provider, cron_thread, housekeeping_thread = (+ _start_gateway_start_cron_and_housekeeping(runner))++ # READY only once adapters, cron and housekeeping run; missing systemd state just disables watchdog.+ from gateway.run_runtime import publish_gateway_runtime_ready+ publish_gateway_runtime_ready(runner)+ runner._start_systemd_watchdog()++ from gateway.run_runtime import wait_gateway_runtime+ try:+ await wait_gateway_runtime(runner)+ finally:+ try:+ await runner.stop()+ finally:+ verdict = await _start_gateway_shutdown_tail(+ runner, _control_server, cron_stop, cron_provider, cron_thread, housekeeping_thread,+ _planned_stop_watcher_stop, _planned_stop_watcher_thread, _signal_initiated_shutdown)+ return verdict++ finally:+ try:+ if runner is not None:+ from gateway.run_runtime import drain_gateway_runtime+ await drain_gateway_runtime(runner)+ # Startup may have opened adapters before an exception. The same+ # stop path owns their writers and DB handles on every exit.+ await runner.stop()+ finally:+ if _planned_stop_watcher_stop is not None:+ _planned_stop_watcher_stop.set()+ if _control_server is not None:+ await _control_server.stop()+ remove_pid_file()+ release_gateway_runtime_lock()diff --cc gateway/run_profile_reconcile.pyindex a817bd9b3e1,bf70d9f177b..52df18d051e--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@@ -122,114 -118,70 +122,131 @@@ class GatewayProfileReconcileMixinif name not in warned:logger.warning("[MULTIPLEX] Profile '%s' still runs its own gateway; ""stop it before the host can serve this profile", name)- del current[name]+ del live[name]self._profile_own_gateway_warned = blockedsigs = self._served_profile_signatures or {}- from gateway.run_runtime import park_profile, unpark_profile- added = [n for n in current if n not in known and n != active]- 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 added- and profile_serve_signature(current[n]) != sigs.get(n)]- 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++ from gateway.run_runtime import unpark_profile+ for name in [n for n in self._parked_profile_names() if n not in live]:+ unpark_profile(self, name)+ parked = self._parked_profile_names()+ # The watcher never re-parks the same profile every cycle; a creator's explicit signal does.+ retry_parked = reason == "control-socket"+ added = [n for n in live if n not in known and n != active and (retry_parked or n not in parked)]+ removed = [n for n in known if n not in live and n != active]+ changed = [n for n in live if n in known and n != active and n not in added+ and profile_serve_signature(live[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)+ current = {n: h for n, h in live.items() if n in known or n == active}- for name in list(added):- reason = await self._serve_profile_runtime(name, live[name])- if reason is not None:- added.remove(name)- park_profile(self, name, reason)- result["parked"].append(name)- continue- unpark_profile(self, name)- current[name] = live[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 profiles_to_serve(multiplex=True)}- 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, live=live, result=result)++++ async def _apply_profile_changes(self, current, added, removed, changed, *, reason,++ live=None, result=None):++ """Apply a selected diff under the reconcile lock, shared by the watcher and the++ serve/unserve control verbs. New profiles first get a runtime (reservation + store); one++ whose home another gateway owns or whose store is unusable is parked, not served."""++ from gateway.run import MultiplexConfigError++ from gateway.run_runtime import park_profile, unpark_profile++ from hermes_cli.profiles import profiles_to_serve+ active = getattr(self, "_primary_profile_name", None) or "default"- result = {"added": [], "removed": [], "rescanned": [], "reason": reason}++ result = dict(result or {"added": [], "removed": [], "rescanned": [], "parked": [], "reason": reason})++ result.setdefault("parked", [])++ live = live if live is not None else dict(current)++ known = dict(self._served_profile_homes or {})++ sigs = self._served_profile_signatures or {}+ 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])++ await self._unserve_profile(name, known[name])+ result["removed"].append(name)- sigs = self._served_profile_signatures or {}++ for name in list(added):++ reason_ = await self._serve_profile_runtime(name, live[name])++ if reason_ is not None:++ added.remove(name)++ park_profile(self, name, reason_)++ result["parked"].append(name)++ continue++ unpark_profile(self, name)++ current[name] = live[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- # Deletion or parking during an awaited connect must win over publication.- live_now = {str(name) for name, _home in _multiplex_profile_homes(self.config)}++ # 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 profiles_to_serve(multiplex=True)}+ 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.++ # ``_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+ def _parked_profile_names(self) -> list:+ """Profiles that exist but could not be served (unusable store, home owned elsewhere); boot's+ ``initialize_gateway_runtime`` parks into the same published ``name -> reason`` map."""+ from gateway.run_runtime import parked_profile_map+ return list(parked_profile_map(self))++ async def _serve_profile_runtime(self, name: str, home: "Path") -> Optional[str]:+ """Grow the reservation by *home* and build its session authority (boot's per-secondary+ steps). Returns the park reason — reservation released — when another gateway owns the home+ (a stray per-profile daemon) or its store cannot be opened; None when served. An+ adapters-only runner (no authority registry) grows the reservation alone."""+ from gateway.run_runtime import release_profile_home, reserve_profile_home, serve_profile_runtime+ from gateway.runtime_ownership import OwnershipConflict+ try:+ reserve_profile_home(self, name, home)+ except (OwnershipConflict, OSError) as exc:+ logger.error("[MULTIPLEX] Profile '%s' not served: %s", name, exc)+ return f"home owned by another gateway: {exc}"+ if getattr(self, "session_authorities", None) is None:+ return None+ try:+ await serve_profile_runtime(self, name, home)+ except Exception as exc:+ logger.error("[MULTIPLEX] Profile '%s' not served: its session store is unusable (%s): %s",+ name, home, exc)+ release_profile_home(self, home)+ return f"session store unusable: {exc}"+ return None+def _live_resource_claims(self, active: str) -> Dict[tuple, str]:"""Startup's ``claimed`` map rebuilt from what is live now: primary claims plus every connectedsecondary's credential/listener, so a hot-added profile reusing a token is parked, never adiff --cc hermes_cli/web_routers/sessions.pyindex b6991c1af20,e4060177182..b1ec221acc0--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@@ -19,12 -19,13 +19,13 @@@ from fastapi.responses import Streamingfrom hermes_cli.web_deps import latefrom hermes_cli.web_server_gateway import _strip_session_list_rows-from hermes_cli.web_server_sessions import _maybe_auto_archive_for_profile, _session_latest_descendant+from hermes_cli.web_server_sessions import _session_latest_descendantfrom hermes_cli.web_models import (BulkDeleteSessions, SessionImport, SessionOwnerBackfill, SessionPrune, SessionRename)- from hermes_cli.web_routers._common import log as _log, destructive_profile, http_failure+ from hermes_cli.web_routers._common import CORRUPT_STORE_DETAIL, log as _log, destructive_profile, http_failurefrom hermes_state import is_malformed_db_errorfrom hermes_state_errors import is_transient_sqlite_error+ from hermes_state_health import STORAGE_CORRUPT, note_storage_error, storage_statelist_router = APIRouter()search_router = APIRouter()diff --cc hermes_cli/web_server_app.pyindex 466757f639b,00000000000..07a3795318dmode 100644,000000..100644--- a/hermes_cli/web_server_app.py+++ b/hermes_cli/web_server_app.py@@@ -1,188 -1,0 +1,190 @@@+"""HTTP lifespan composition; standalone backend services remain opt-in owners."""++from contextlib import asynccontextmanager+import asyncio+import logging+import os+import threading++from fastapi import FastAPI+from hermes_cli.pty_session import run_reaper++_log = logging.getLogger("hermes_cli.web_server")+++@asynccontextmanager+async def standalone_lifespan(app: "FastAPI"):+ from hermes_cli.web_server import (+ _eager_reconcile_own_session_db, _warm_gateway_module,+ _start_desktop_cron_ticker, _dashboard_selftest_loop,+ _auto_archive_ticker_loop, _terminate_desktop_managed_gateway,+ )+ from hermes_cli.web_server_chat import PTY_REGISTRY++ app.state.event_channels = {} # dict[str, set]+ app.state.event_lock = asyncio.Lock()+ app.state.pty_active_session_files = {} # dict[str, Path]+ # Serializes chat-argv resolution so concurrent /api/pty connections don't+ # overlap ``npm install`` / ``npm run build``. Locks live on app.state (not+ # module globals) so they bind to the running loop, not the import-time one.+ app.state.chat_argv_lock = asyncio.Lock()++ # Bring state.db schema current BEFORE the first session-list poll+ # (#79531/#80037): a store left behind by `hermes update` otherwise 500s+ # every poll until its owner completes schema reconciliation.+ # Off-thread so a locked store never delays the socket (Desktop+ # ready-probe times out at 10s, GH-73083). NOT a daemon, and joined at+ # shutdown: its sqlite connection must be closed by the thread that is+ # stepping it. A daemon copy that outlived the lifespan had its+ # connection closed from the main thread mid-probe (pytest's leaked-DB+ # sweep) and segfaulted the interpreter. The worker is time-bounded by+ # SessionDB's lock patience, so the join cannot hang shutdown.+ eager_reconcile_thread = threading.Thread(+ target=_eager_reconcile_own_session_db,+ name="statedb-eager-reconcile",+ )+ eager_reconcile_thread.start()++ # Import hermes_cli.gateway *before* the yield: on Windows + 3.11 the+ # import holds the GIL, so run_in_executor still froze the loop 15-22s and+ # the Desktop's 10s ready-probe timed out (GH-73083).+ _warm_gateway_module()++ # Snapshot the checkout revision so lazy-import paths (model picker) can+ # refuse with "restart required" after `hermes update` replaced the code+ # (#86207); the update flow does not reliably restart the dashboard.+ from gateway.code_skew import record_boot_fingerprint++ record_boot_fingerprint()++ # Hosted Bot rooms belong to the backend process. Recovery may need a+ # contended state.db migration, so keep it off the pre-yield path: Group+ # Chat must degrade on its own rather than block every Desktop feature.+ from tui_gateway import methods_groups as _hosted_groups+ import tui_gateway.server # noqa: F401++ hosted_room_start_cancel = threading.Event()++ def _start_hosted_rooms() -> None:+ try:+ _hosted_groups.start_hosted_room_service()+ except Exception:+ _log.exception("Hosted Group Chat recovery failed during backend startup")+ finally:+ if hosted_room_start_cancel.is_set():+ _hosted_groups.stop_hosted_room_service(timeout=1.0)++ hosted_room_start_thread = threading.Thread(+ target=_start_hosted_rooms,+ daemon=True,+ name="hosted-room-startup",+ )+ hosted_room_start_thread.start()+- # Desktop-spawned backends (HERMES_DESKTOP=1) fire cron jobs themselves,- # since the app has no gateway running the scheduler. Server `hermes- # dashboard` is unaffected — it relies on its own gateway.++ # Desktop-spawned backends fire cron jobs themselves, since the app has no++ # gateway running the scheduler. Server `hermes dashboard` is unaffected —++ # it relies on its own gateway.++ from hermes_cli.process_identity import is_desktop_owned_backend+ cron_stop: "threading.Event | None" = None+ cron_thread: "threading.Thread | None" = None- if os.getenv("HERMES_DESKTOP") == "1":++ desktop_owned = is_desktop_owned_backend()++ if desktop_owned:+ # Reap an orphaned gateway from an abnormal previous exit (reparented to+ # launchd, still holding the platform WebSocket) before forking a fresh+ # one that would race the same credential (#77276). Runs+ # unconditionally; protection of a healthy standalone gateway lives+ # INSIDE the reaper (registration probed with cleanup_stale=False).+ try:+ from hermes_cli.gateway import _reap_unsupervised_gateway_orphans++ _reap_unsupervised_gateway_orphans()+ except Exception:+ _log.exception("Desktop startup: orphan gateway reap failed")++ cron_stop = threading.Event()+ cron_thread = threading.Thread(+ target=_start_desktop_cron_ticker,+ args=(cron_stop,),+ daemon=True,+ name="desktop-cron-ticker",+ )+ cron_thread.start()++ # Reap idle/dead keep-alive PTY sessions (30-min TTL).+ pty_reaper_task = asyncio.create_task(run_reaper(PTY_REGISTRY))+ # Periodic authenticated self-test feeding the ``dashboard`` component on /api/status.+ selftest_task = asyncio.create_task(_dashboard_selftest_loop())+ # Live auto-archive timer, independent of list requests.+ auto_archive_task = asyncio.create_task(_auto_archive_ticker_loop())++ # Managed local runtime (local_runtime.enabled): bring llama-server back so a+ # restart doesn't strand a llamacpp main model. Off-thread and best-effort;+ # failure falls back to cloud providers like a cold start. Server only —+ # models load on first inference (an empty router holds no VRAM).+ def _boot_local_runtime():+ try:+ from hermes_cli.config import load_config+ from hermes_cli.local_runtime.bootstrap import ensure_local_runtime++ ensure_local_runtime(load_config())+ except Exception as exc: # noqa: BLE001+ logging.getLogger(__name__).warning("local runtime boot failed: %s", exc)++ threading.Thread(target=_boot_local_runtime, daemon=True, name="local-runtime-boot").start()++ from hermes_cli.free_tier_bootstrap import start_background_bootstrap++ start_background_bootstrap()++ try:+ yield+ finally:+ hosted_room_start_cancel.set()+ _hosted_groups.stop_hosted_room_service(timeout=5.0)+ hosted_room_start_thread.join(timeout=1.0)+ if cron_stop is not None:+ cron_stop.set()+ pty_reaper_task.cancel()+ selftest_task.cancel()+ auto_archive_task.cancel()+ eager_reconcile_thread.join()+ await PTY_REGISTRY.close_all()+ # Stop the managed llama-server with its parent (an orphan pins VRAM).+ try:+ from hermes_cli.local_runtime.bootstrap import shutdown_local_runtime++ shutdown_local_runtime()+ except Exception: # noqa: BLE001+ pass- if os.getenv("HERMES_DESKTOP") == "1":++ if desktop_owned:+ _terminate_desktop_managed_gateway()+++@asynccontextmanager+async def http_lifespan(app: FastAPI):+ """The gateway already owns schema, rooms, scheduler and model services."""+ from hermes_cli.web_server import _dashboard_selftest_loop+ from hermes_cli.web_server_chat import PTY_REGISTRY++ app.state.event_channels = {}+ app.state.event_lock = asyncio.Lock()+ app.state.pty_active_session_files = {}+ app.state.chat_argv_lock = asyncio.Lock()+ tasks = [+ asyncio.create_task(run_reaper(PTY_REGISTRY), name="gateway-api-pty-reaper"),+ asyncio.create_task(_dashboard_selftest_loop(), name="gateway-api-selftest"),+ ]+ try:+ yield+ finally:+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ await PTY_REGISTRY.close_all()+++@asynccontextmanager+async def app_lifespan(app: FastAPI):+ lifespan = http_lifespan if getattr(app.state, "gateway_runner", None) is not None else standalone_lifespan+ async with lifespan(app):+ yield