The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main into ethie/pm-clean
ethernetf4a38b1ee87d
diff --cc apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.tsindex 7cd8c3d549e,0252a978806..a2477675de0--- a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts@@@ -60,8 -62,54 +62,52 @@@ export function invalidatePersistedDisp}}- export function suppressTranscriptForView(state: ClientSessionState, suppress: boolean): ClientSessionState {- if (!suppress || state.messages.length === 0) {+ export interface TranscriptViewCutoff {+ cutoffIds: ReadonlySet<string>+ // Content fingerprints of the arm-time rows (optional). Compaction+ // re-sequences the cached tail with FRESH row ids mid-hold+ // (archive_and_compact: "consumers that reference durable row ids+ // re-resolve by content"), so an id-only cutoff would pass the whole+ // re-sequenced cached prefix as if it were live and paint the exact+ // compressed tail the hold exists to hide (#73646 via #117867).+ cutoffKeys?: ReadonlySet<string>+ }++ // Volatile-free content fingerprint: role + text of text parts, JSON of the+ // rest. Deliberately ignores row ids and per-row timestamps so a re-sequenced+ // copy of the same content fingerprints identically. Ceiling: a genuinely new+ // row whose content is byte-identical to an arm-time row stays hidden until+ // the hold releases (bounded by the REST window).+ export function transcriptRowContentKey(message: ChatMessage): string {+ return `${message.role}:${+ (message.parts ?? [])- .map(part =>- 'text' in part && typeof part.text === 'string' ? `${part.type}:${part.text}` : JSON.stringify(part)- )++ .map(part => part.type === 'text' ? `${part.type}:${part.text}` : JSON.stringify(part))+ .join('|')+ }`+ }++ export function suppressTranscriptForView(+ state: ClientSessionState,+ cutoff: TranscriptViewCutoff | null+ ): ClientSessionState {+ if (cutoff === null) {+ return state+ }++ if (cutoff.cutoffIds.size === 0) {+ // Fail-closed: the gate was armed before any cached row existed, so there+ // is no unproven prefix to hide selectively — everything stays off the+ // view until REST authority lands (#73646).+ return { ...state, messages: [] }+ }++ const messages = state.messages.filter(+ message =>+ !cutoff.cutoffIds.has(message.id) &&+ !(cutoff.cutoffKeys?.has(transcriptRowContentKey(message)) ?? false)+ )++ if (messages.length === state.messages.length) {return state}diff --cc gateway/config_loader.pyindex 01dc63555a3,2c97082b9fb..da7af329087--- a/gateway/config_loader.py+++ b/gateway/config_loader.py@@@ -390,9 -390,17 +390,17 @@@ def read_yaml_layers(home: Path) -> dicconfig_yaml_path = home / "config.yaml"yaml_cfg: dict = {}if config_yaml_path.exists():- with open(config_yaml_path, encoding="utf-8") as f:+ with open(config_yaml_path, encoding="utf-8-sig") as f:yaml_cfg = yaml.safe_load(f) or {}+ from hermes_cli.config import _expand_env_vars++ # ${VAR} / ${env:VAR} expansion — the same primitive the CLI loader applies, so platform+ # adapter settings (webhook secret, api_server key, teams credentials) arrive resolved+ # instead of as literal refs. User layer first: the managed overlay is expanded by+ # apply_managed_overlay itself and must not be re-resolved (config_effective._effective order).+ yaml_cfg = _expand_env_vars(yaml_cfg)+# Managed scope: overlay administrator-pinned values (this loader bypasses# hermes_cli.config.load_config, so managed quick_commands / stt would otherwise be ignored).from hermes_cli import managed_scopediff --cc hermes_cli/AGENTS.mdindex 6927947e2b2,32e557dbac4..3ef2a5e9de7--- a/hermes_cli/AGENTS.md+++ b/hermes_cli/AGENTS.md@@@ -19,9 -19,9 +19,9 @@@ Moved bodies late-bind cli-level nameshandles input + autocomplete; `KawaiiSpinner` (`agent/display.py`) animates API calls and printsthe `┊` activity feed. `load_cli_config()` in `cli.py` merges CLI defaults + user YAML.--`hermes_cli/gateway.py` is the `hermes gateway` facade (process discovery, systemd backend, command--dispatch); topical siblings re-exported by the facade: `gateway_service_unit.py` (systemd unit--generation/refresh), `gateway_launchd.py` (macOS LaunchAgent backend), `gateway_setup_wizard.py`++`hermes_cli/gateway.py` is the `hermes gateway` facade (process discovery, PM-aware systemd unit++generation/refresh, command dispatch); topical siblings re-exported by the facade include++`gateway_launchd.py` (macOS LaunchAgent backend), `gateway_setup_wizard.py`(`hermes gateway setup`: `_PLATFORMS` registry, status table, per-platform prompts, service offer),`gateway_windows*.py`, `gateway_supervised_restart.py`, `gateway_migrate*.py`, `gateway_multiplex_*.py`,`gateway_enroll.py`, `gateway_command_errors.py`. Sibling bodies read facade names through `_gw()`@@@ -242,9 -246,9 +242,8 @@@ supervisor (control-socket `identify` afor a fresh supervised PID, never stop + foreground `run_gateway` (that stamps the CLI's PID and wedgesevery KeepAlive respawn, #110637).--Service installs are a matrix, not a unit file: `gateway_service_unit.py::generate_systemd_unit(system=,--run_as_user=)` (systemd unit generation / `systemd_unit_is_current` / `refresh_systemd_unit_if_needed` live in that--sibling and read facade helpers late-bound through `hermes_cli.gateway`, so patch them on the facade; user unit AND `--system` unit with `User=`; an unresolvable `User=` is a blocker,++Service installs are a matrix, not a unit file: `gateway.py::generate_systemd_unit(system=,++run_as_user=)` (systemd unit generation / `systemd_unit_is_current` / `refresh_systemd_unit_if_needed` are PM-aware facade owners; user unit AND `--system` unit with `User=`; an unresolvable `User=` is a blocker,never a dir-owner fallback), `gateway_launchd.py::generate_launchd_plist` (`gui/<uid>` then `user/<uid>` domains, never a`~/Library/LaunchAgents` glob; the whole launchd backend — plist refresh, `launchctl` bootstrap/kickstart,`launchd_start/stop/restart/status`, detached-process degrade — lives in that sibling, with the domain cachediff --cc hermes_cli/gateway.pyindex f1659a65962,b5594027849..f7a5bb47874--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@@ -2921,411 -2963,6 +2921,431 @@@ def _remap_path_for_user(path: str, tar+def _systemd_env_line(name: str, value: str) -> str:+ """One ``Environment="NAME=value"`` line: ``\\`` and ``"`` escaped for systemd's quoting, ``%``+ doubled so specifier expansion leaves the value alone."""+ escaped = value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%")+ return f'Environment="{name}={escaped}"\n'+++def _installed_unit_ld_library_path(system: bool) -> str:+ """``LD_LIBRARY_PATH`` baked into the installed unit; ``""`` when absent."""+ return _unit_environment_value(get_systemd_unit_path(system=system), "LD_LIBRARY_PATH") or ""+++def _ld_library_path_line(system: bool, target_home_dir: str | None = None) -> str:+ """Carry the installer's LD_LIBRARY_PATH into the unit (glibc reads it only at process start, so+ ~/.hermes/.env is too late for CUDA libs — #14613); system units remap caller-home components.++ The installed unit is the fallback source: the unit is regenerated and compared on every+ start/restart/status, and a shell without the export (ssh, cron, ``sudo`` strips ``LD_*``)+ must not be able to "repair" the line away."""+ raw = os.environ.get("LD_LIBRARY_PATH", "") or _installed_unit_ld_library_path(system)+ components = [p for p in raw.split(":") if p]+ if target_home_dir is not None:+ components = [_remap_path_for_user(p, target_home_dir) for p in components]+ return _systemd_env_line("LD_LIBRARY_PATH", ":".join(components)) if components else ""+++def _hermes_home_for_target_user(target_home_dir: str) -> str:+ """Remap the current HERMES_HOME (root's, under sudo) to the target user's equivalent:+ ``/root/.hermes[/profiles/x]`` → ``/home/alice/.hermes[/profiles/x]``; custom paths kept as-is."""+ current_hermes_raw = os.environ.get("HERMES_HOME", "").strip()+ current_hermes = Path(current_hermes_raw).expanduser() if current_hermes_raw else get_hermes_home()+ # Keep paths lexical: resolving a non-existent path can bake a different HERMES_HOME into the unit.+ current_default = Path.home() / ".hermes"+ target_default = Path(target_home_dir) / ".hermes"+ try:+ # Default ~/.hermes or a profile/subdir of it → preserve the relative structure under the target.+ return str(target_default / current_hermes.relative_to(current_default))+ except ValueError:+ return str(current_hermes) # Completely custom path (not under ~/.hermes) — keep as-is+++def _build_service_path_dirs(project_root: Path | None = None) -> list[str]:+ """Build PATH directory list for service units, excluding non-existent dirs."""+ if project_root is None:+ project_root = PROJECT_ROOT++ def _is_dir(path: Path) -> bool:+ try:+ return path.is_dir()+ except OSError:+ return False++ candidates = []+ # Python and dependency executable paths are selected at boot, not persisted.++ hermes_home = get_hermes_home()+ extras = (project_root / "node_modules" / ".bin", hermes_home / "node" / "bin", hermes_home / "node_modules" / ".bin")+ for extra in extras:+ if _is_dir(extra):+ candidates.append(str(extra))+ return candidates+++def _stable_service_working_dir() -> str:+ """WorkingDirectory that won't disappear under systemd (HERMES_HOME, else PROJECT_ROOT). cwd is+ irrelevant to ``-m`` resolution, and a pinned transient checkout rots: systemd fails at CHDIR+ (status=200) before Python loads, so the unit self-heal never runs and Restart=always crash-loops."""+ try:+ home = get_hermes_home()+ if home and Path(home).is_dir():+ return str(Path(home).resolve())+ except Exception:+ pass+ return str(PROJECT_ROOT)+++def _systemd_watchdog_seconds(hermes_home: str | Path | None = None) -> int:+ """Resolve the managed-overlay-aware watchdog setting for a service home."""+ override_token = reset_home_override = None+ if hermes_home is not None:+ from hermes_constants import (reset_hermes_home_override, set_hermes_home_override)+ override_token = set_hermes_home_override(hermes_home)+ reset_home_override = reset_hermes_home_override+ try:+ config = load_gateway_config()+ return coerce_systemd_watchdog_seconds(getattr(config, "systemd_watchdog_seconds", 0))+ except Exception:+ logger.debug("Could not resolve effective systemd watchdog configuration", exc_info=True)+ return 0+ finally:+ if override_token is not None and reset_home_override is not None:+ reset_home_override(override_token)+++def _pm_managed_node_dirs(home: Path) -> list[str]:+ """Node dirs pm's installed-state records under *home*'s store, resolved+ via ``Facts.env_for`` (``{{store}}`` templates against the store beside+ the recorded facts). Only dirs present on disk count; a record whose+ store dirs are gone vouches for nothing.+ """+ from pm.lock import Facts++ store = Path(home) / "tools"+ facts = Facts(store / "facts.json")+ dirs: list[str] = []+ for name in ("node", "npm", "npx"):+ for value in facts.env_for(name, store).get("PATH") or []:+ if value and Path(value).is_dir():+ dirs.append(str(value))+ return dirs+++def _append_node_dir_for_service(path_entries: list[str], hermes_root: Path | None = None) -> None:+ """Append the Node dir a service unit should use.++ PM's installed-state is the owner: facts.json under the target hermes+ home's store records node/npm PATH entries, and those dirs — resolved via+ Facts.env_for — are used verbatim. With managed Node recorded, consulting+ the invoker's PATH would make a system unit depend on who ran sudo, so+ lookup stops there. The legacy ``<hermes>/node`` tree and finally a PATH+ lookup are fallbacks for installs pm never recorded.+ """+ home = Path(hermes_root) if hermes_root is not None else Path(get_hermes_home())+ try:+ managed_dirs = _pm_managed_node_dirs(home)+ except Exception:+ managed_dirs = [] # pm absent or unreadable: fall through to the legacy probe+ for entry in managed_dirs:+ if entry not in path_entries:+ path_entries.append(entry)+ if managed_dirs:+ return++ from hermes_constants import (hermes_managed_node_tree_present, iter_hermes_node_dirs)+ managed_node_present = hermes_managed_node_tree_present(hermes_root)+ for directory in iter_hermes_node_dirs(hermes_root) if managed_node_present else ():+ entry = str(directory)+ try:+ present = directory.is_dir()+ except OSError:+ present = False+ if present and entry not in path_entries:+ path_entries.append(entry)++ # With managed Node present, consulting the invoker's PATH would make a system unit depend on who ran sudo.+ if managed_node_present:+ return++ resolved_node = shutil.which("node")+ if not resolved_node:+ return++ # Use the dir where node is FOUND, not the symlink target (~/.local/bin/node often links into one profile).+ resolved_node_dir = str(Path(resolved_node).parent)+ if resolved_node_dir not in path_entries:+ path_entries.append(resolved_node_dir)+++def _systemd_command(argv: list[str]) -> str:+ """Quote argv for systemd, including its non-shell specifier expansion."""+ return " ".join('"' + part.replace("\\", "\\\\").replace('"', '\\"')+ .replace("%", "%%").replace("$", "$$") + '"' for part in argv)+++def _prepare_service_launcher(*, system: bool = False, run_as_user: str | None = None) -> None:+ """Publish the source command before a service definition references it."""+ from hermes_cli._launchers import ENTRY_POINTS, ensure_install_launchers, resolve_store_python+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override++ root, home = PROJECT_ROOT, get_hermes_home()+ owner = None+ if system:+ username, _group, home_dir, uid = _system_service_identity(run_as_user)+ root = Path(_remap_path_for_user(str(root), home_dir))+ home = Path(_hermes_home_for_target_user(home_dir))+ owner = (uid, username)+ token = set_hermes_home_override(home)+ try:+ if resolve_store_python(root) is None:+ return # Externally owned Nix/developer runtime.+ local = root / ".hermes" / "bin"+ paths = ensure_install_launchers(root, local)+ if len(paths) != len(ENTRY_POINTS):+ raise RuntimeError("Could not publish the gateway installation launcher")+ if owner is not None:+ import pwd+ uid, username = owner+ gid = pwd.getpwnam(username).pw_gid+ for path in (local.parent, local, *map(Path, paths)):+ os.chown(path, uid, gid)+ finally:+ reset_hermes_home_override(token)+++def generate_systemd_unit(system: bool = False, run_as_user: str | None = None) -> str:+ from hermes_cli._launchers import installation_command++ python_path = get_python_path()+ working_dir = _stable_service_working_dir()+ project_root = PROJECT_ROOT++ path_entries = _build_service_path_dirs()+ if not system:+ # System units add managed Node once the TARGET user's home is known (not the sudo caller's).+ _append_node_dir_for_service(path_entries)++ # TimeoutStopSec must cover the full stop budget (cron drain + cleanup) or systemd SIGKILLs mid-drain.+ restart_timeout = resolve_systemd_timeout_stop_sec(_get_restart_drain_timeout(), _get_cron_drain_timeout())++ if system:+ username, group_name, home_dir, uid = _system_service_identity(run_as_user)+ hermes_home = _hermes_home_for_target_user(home_dir)+ # Profile arg relative to the TARGET user's ~/.hermes when hermes_home lives under it.+ target_root = Path(home_dir) / ".hermes"+ try:+ Path(hermes_home).resolve().relative_to(target_root.resolve())+ profile_arg = _profile_arg(hermes_home, default_root=target_root)+ except ValueError:+ profile_arg = _profile_arg(hermes_home)+ # Remap paths under the calling user's home (/root/) to the target user's so the service can read them.+ python_path = _remap_path_for_user(python_path, home_dir)+ working_dir = str(hermes_home) if hermes_home else _remap_path_for_user(working_dir, home_dir)+ project_root = Path(_remap_path_for_user(str(project_root), home_dir))+ path_entries = [_remap_path_for_user(p, home_dir) for p in path_entries]+ # Managed Node for the TARGET user's tree, prepended so it outranks remapped shell-PATH entries.+ _target_node_entries: list[str] = []+ _append_node_dir_for_service(_target_node_entries, Path(hermes_home) if hermes_home else None)+ path_entries = [e for e in _target_node_entries if e not in path_entries] + path_entries+ user_home = Path(home_dir)+ identity_lines = f"User={username}\nGroup={group_name}\n"+ # Restart-safe cron/Kanban workers cross `systemd-run --user`, which needs this user's manager;+ # without the ordering the gateway and user@<uid>.service race at boot and the one-shot bus+ # adoption in run_gateway() can miss (#104893).+ ordering_lines = f"After=user@{uid}.service\nWants=user@{uid}.service\n"+ env_lines = (+ f'Environment="HOME={home_dir}"\n'+ f'Environment="USER={username}"\n'+ f'Environment="LOGNAME={username}"\n'+ ) + _ld_library_path_line(system=True, target_home_dir=home_dir)+ wanted_by = "multi-user.target"+ else:+ hermes_home = str(get_hermes_home().resolve())+ profile_arg = _profile_arg(hermes_home)+ user_home = Path.home()+ identity_lines = ordering_lines = ""+ env_lines = _ld_library_path_line(system=False)+ wanted_by = "default.target"++ watchdog_seconds = _systemd_watchdog_seconds(hermes_home)+ systemd_type, systemd_watchdog_directives = "simple", ""+ if watchdog_seconds > 0:+ systemd_type, systemd_watchdog_directives = "notify", f"NotifyAccess=main\nWatchdogSec={watchdog_seconds}s\n"+ path_entries.extend(_build_user_local_paths(user_home, path_entries))+ path_entries.extend(_build_wsl_interop_paths(path_entries))+ path_entries.extend(["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin"])+ sane_path = ":".join(path_entries)+ start = installation_command(project_root, [*shlex.split(profile_arg), "gateway", "run"],+ python=python_path, home=hermes_home)+ cleanup = installation_command(project_root, module="gateway.cgroup_cleanup",+ python=python_path, home=hermes_home)+ stop_mark = installation_command(project_root, module="gateway.systemd_stop_mark",+ python=python_path, home=hermes_home)+ return f"""[Unit]+Description={SERVICE_DESCRIPTION}+After=network-online.target+Wants=network-online.target+{ordering_lines}StartLimitIntervalSec=0++[Service]+Type={systemd_type}+{systemd_watchdog_directives}{identity_lines}ExecStart={_systemd_command(start)}+WorkingDirectory={working_dir}+{env_lines}Environment="PATH={sane_path}"++Environment="HERMES_HOME={hermes_home}"+Environment="HERMES_SUPERVISED_CHILD=1"+Restart=always+RestartSec=5+RestartForceExitStatus={GATEWAY_SERVICE_RESTART_EXIT_CODE}+SuccessExitStatus={GATEWAY_SERVICE_RESTART_EXIT_CODE}+RestartPreventExitStatus={GATEWAY_FATAL_CONFIG_EXIT_CODE}+KillMode=mixed+KillSignal=SIGTERM+ExecReload=/bin/kill -USR1 $MAINPID+ExecStop=-{_systemd_command(stop_mark)}+ExecStopPost=-{_systemd_command(cleanup)}+TimeoutStopSec={restart_timeout}+StandardOutput=journal+StandardError=journal++[Install]+WantedBy={wanted_by}+"""+++def _normalize_service_definition(text: str) -> str:+ return "\n".join(line.rstrip() for line in text.strip().splitlines())+++# Directives older systemd silently strips; ignored in stale-checks so such units aren't flagged forever.+_SYSTEMD_OPTIONAL_DIRECTIVES = ("RestartMaxDelaySec", "RestartSteps")+++def _strip_optional_systemd_directives(text: str) -> str:+ """Remove systemd directives that older hosts silently drop."""+ filtered = []+ for line in text.splitlines():+ stripped = line.strip()+ is_directive = stripped and not stripped.startswith("#")+ if not (is_directive and stripped.split("=", 1)[0].strip() in _SYSTEMD_OPTIONAL_DIRECTIVES):+ filtered.append(line)+ return "\n".join(filtered)+++def _normalize_launchd_plist_for_comparison(text: str) -> str:+ """Normalize plist text for staleness checks, ignoring the PATH payload: the generated PATH is+ captured from the invoking shell and varies across shells."""+ import re+ return re.sub(+ r"(<key>PATH</key>\s*<string>)(.*?)(</string>)", r"\1__HERMES_PATH__\3",+ _normalize_service_definition(text), flags=re.S,+ )+++def systemd_unit_is_current(system: bool = False) -> bool:+ # HERMES_HOME sync chokepoint for every compare/regenerate path: under `sudo … --system` it is often+ # stripped to /root/.hermes, so refresh would rewrite a correct unit and status warn forever.+ # Idempotent; the os.environ mutation persists for later runtime reads (restart's PID/drain).+ _sync_hermes_home_from_systemd_unit(system=system)++ unit_path = get_systemd_unit_path(system=system)+ if not unit_path.exists():+ return False++ installed = unit_path.read_text(encoding="utf-8-sig")+ expected_user = _read_systemd_user_from_unit(unit_path) if system else None+ expected = generate_systemd_unit(system=system, run_as_user=expected_user)+ # Ignore directives older systemd drops (RestartMaxDelaySec, RestartSteps) to avoid a perpetual "outdated" flag.+ norm = lambda text: _normalize_service_definition(_strip_optional_systemd_directives(text)) # noqa: E731+ return norm(installed) == norm(expected)+++def _temp_home_in_service_definition(definition: str) -> str | None:+ """Temp-dir HERMES_HOME baked into a systemd unit / launchd plist, or None. A temp home means a+ test/E2E harness generated it; installing it leaves the gateway "running" but deaf to every platform."""+ import re+ import tempfile+ candidates = re.findall(r'HERMES_HOME=([^"\n]+)', definition)+ candidates += re.findall(r"<key>HERMES_HOME</key>\s*<string>(.*?)</string>", definition, flags=re.S)+ temp_roots = {+ Path(tempfile.gettempdir()).resolve(),+ Path("/tmp"), Path("/var/tmp"), Path("/private/tmp"), Path("/private/var/tmp"), # no-tmp: ok — detects a temp HERMES_HOME in service definitions+ }+ for raw in candidates:+ try:+ resolved = Path(raw.strip().strip('"')).resolve()+ except (OSError, ValueError):+ continue+ if any(resolved == root or root in resolved.parents for root in temp_roots):+ return raw.strip()+ return None+++def _refuse_temp_home_service_write(definition: str, kind: str) -> bool:+ """Refuse (with guidance) when a service definition carries a temp HERMES_HOME."""+ temp_home = _temp_home_in_service_definition(definition)+ if temp_home is None:+ return False+ print(f"✗ Refusing to write the gateway {kind}: HERMES_HOME resolves to a temporary directory ({temp_home}).")+ print(+ " This usually means a test/E2E environment exported HERMES_HOME. "+ "Unset it (or run from a clean shell) and retry."+ )+ return True++++def _retire_hermes_replace_dropin(system: bool = False) -> bool:++ """Remove only the legacy ``--replace`` drop-in written by Hermes."""++ unit_path = get_systemd_unit_path(system=system)++ dropin = unit_path.parent / f"{unit_path.name}.d" / "20-replace.conf"++ try:++ text = dropin.read_text(encoding="utf-8-sig")++ except OSError:++ return False++ if not all(token in text for token in ("Added to end the gateway respawn storm", "--replace", "ExecStart=")):++ return False++ dropin.unlink()++ return True+++++def refresh_systemd_unit_if_needed(system: bool = False) -> bool:+ """Rewrite the installed systemd unit when the generated definition has changed."""+ unit_path = get_systemd_unit_path(system=system)+ if not unit_path.exists():+ return False++ # systemd_unit_is_current is the HERMES_HOME-sync chokepoint; its env mutation persists for the regenerate below.- if systemd_unit_is_current(system=system):++ current = systemd_unit_is_current(system=system)++ if _retire_hermes_replace_dropin(system=system):++ _run_systemctl(["daemon-reload"], system=system, check=True, timeout=30)++ print(f"↻ Removed the stale Hermes --replace drop-in from the gateway {_service_scope_label(system)} service")++ if current:++ return True++ elif current:+ return False++ expected_user = _read_systemd_user_from_unit(unit_path) if system else None+ new_unit = generate_systemd_unit(system=system, run_as_user=expected_user)++ # Test safety belt: the user unit path is under Path.home(), which conftest does NOT sandbox, and a+ # pytest-tmp HERMES_HOME baked into the developer's real unit breaks their gateway on next reboot.+ if not system and any(m in new_unit for m in ("/pytest-of-", '/hermes_test"', "/hermes_test/")):+ return False++ # Structural variant: refuse ANY temp-dir HERMES_HOME (manual E2E homes lack the pytest markers).+ if _refuse_temp_home_service_write(new_unit, "systemd unit"):+ return False++ _prepare_service_launcher(system=system, run_as_user=expected_user)+ unit_path.write_text(new_unit, encoding="utf-8")+ _run_systemctl(["daemon-reload"], system=system, check=True, timeout=30)+ print(f"↻ Updated gateway {_service_scope_label(system)} service definition to match the current Hermes install")+ return True++def _print_linger_enable_warning(username: str, detail: str | None = None, *, system: bool = False) -> None:print()if system:diff --cc hermes_cli/main.pyindex 512e9398ce2,231ff8f5be5..09fd6b5c343--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@@ -570,8 -608,14 +588,9 @@@ def _apply_profile_override() -> Nonehermes_home_env = os.environ.get("HERMES_HOME", "")if profile_name is None and hermes_home_env and Path(hermes_home_env).parent.name == "profiles":return- # The post-swap updater child inherits the home its parent already resolved (possibly the- # root for `-p default`); re-reading the sticky active_profile here would finish the update- # — receipt, config migration, exit code — in another profile's home.- if profile_name is None and hermes_home_env and os.environ.get("HERMES_UPDATE_POST_SWAP") == "1":- return- if profile_name is None and not _under_gateway_supervisor(argv) and not _desktop_ssh_backend(argv):+ if (profile_name is None and not _under_gateway_supervisor(argv) and not _desktop_ssh_backend(argv)+ and not _s6_supervised_gateway_run(argv)):try:from hermes_constants import get_default_hermes_rootdiff --cc scripts/desktop-update/windows.ps1index 26bceb4b48e,4a52ea5c05b..c4f42760d80--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@@ -1205,7 -1187,19 +1205,9 @@@ function Set-InstallRootCurrentDirectorreturn $resolved}-function Resolve-HermesVenvDir([string]$Root) {- # Match hermes_constants.project_venv_dir(): installer-created venv wins,- # while uv-default .venv remains a supported source-install layout.- $legacy = Join-Path $Root "venv"- if (Test-Path -LiteralPath $legacy -PathType Container) { return $legacy }- $uvDefault = Join-Path $Root ".venv"- if (Test-Path -LiteralPath $uvDefault -PathType Container) { return $uvDefault }- return $legacy-}-$finalCode = 1+ $manualAction = $false+ $manualMsg = ""$finalMsg = "update did not complete"$script:TreeSafeToFinalize = $true@@@ -1620,6 -1681,25 +1622,36 @@@ try}}+ # Desktop stopped every locally running profile gateway before handing off+ # so their venv launchers could not hold the update lock. That happens+ # before `hermes update` captures its Windows pause inventory, leaving the+ # updater nothing to resume on its normal success path. Restore the same+ # all-profile fleet only after the updated runtime verifies. A remote-served+ # Desktop must stay passive: its -NoGateway hand-off owns no local poller.+ if ($res.Code -eq 0 -and -not $desktopBuildFailed -and -not $NoGateway) {- $gatewayRestart = Invoke-HermesStep $pythonExe @("-m", "hermes_cli.main", "gateway", "start", "--all") "gateway restart"- if ($gatewayRestart.Code -ne 0) {++ $gatewayRestartFailed = $false++ try {++ # Resolve again after update: PM may have published a new generation,++ # and its command can include an isolation/bootstrap prefix.++ $gatewayCommand = @(Get-HermesRuntimeCommand -InstallRoot $InstallRoot)++ $gatewayArgs = @($gatewayCommand | Select-Object -Skip 1) + @("gateway", "start", "--all")++ $gatewayRestart = Invoke-HermesStep $gatewayCommand[0] $gatewayArgs "gateway restart"++ $gatewayRestartFailed = $gatewayRestart.Code -ne 0++ } catch {++ $gatewayRestartFailed = $true++ Write-HandoffLog "gateway restart setup failed: $($_.Exception.Message)"++ }++ if ($gatewayRestartFailed) {+ # The update itself succeeded; a restart miss is a manual follow-up+ # (Write-Result's manual flag -> Desktop boot dialog), never a failed+ # update: a non-zero exit here would run the error finale and hide+ # the fact that the new runtime is installed and verified.+ $manualAction = $true+ $manualMsg = "Update complete, but Hermes could not restart every messaging gateway. Run `hermes gateway start --all` in a terminal."+ Write-HandoffLog $manualMsg+ }+ }+if ($res.Code -eq 0 -and -not $desktopBuildFailed) {$finalCode = 0$finalMsg = "Update complete."diff --cc tests/agent/test_secret_scope_tier1_migration.pyindex 5d3bd4b3181,233bc83ad80..ba1757a00f8--- a/tests/agent/test_secret_scope_tier1_migration.py+++ b/tests/agent/test_secret_scope_tier1_migration.py@@@ -37,6 -39,13 +37,12 @@@ class _Scopedef __exit__(self, *exc):ss.reset_secret_scope(self.token)-+ class _ExplodingScope(dict):+ """A bound secret scope whose resolution fails (resolver/backend error)."""+ def get(self, name, default=None):+ raise RuntimeError("resolver boom")++# ── Cluster A: gateway/pairing.py allowlist reads ─────────────────────────class TestPairingAllowlistRead:@@@ -64,6 -73,18 +70,17 @@@ss.set_multiplex_active(True)assert _read_allowlist_env("TELEGRAM_ALLOWED_USERS") == "own-env"+ def test_scope_failure_never_borrows_env(self, monkeypatch):+ # A bound scope that errors must propagate -- a blanket suppress would+ # silently borrow the default profile's os.environ allowlist.+ from gateway.pairing import _read_allowlist_env++ monkeypatch.setenv("TELEGRAM_ALLOWED_USERS", "other-profile")+ ss.set_multiplex_active(True)+ with _Scope(_ExplodingScope()):+ with pytest.raises(RuntimeError, match="resolver boom"):+ _read_allowlist_env("TELEGRAM_ALLOWED_USERS")+-# ── Cluster A: gateway/authz_mixin.py gate reads ───────────────────────────class TestAuthzPlatformGateEnv:@@@ -174,6 -198,16 +191,15 @@@ class TestToolGatewayUserTokenss.set_multiplex_active(True)assert _read_user_token_override() == "own-env-tok"+ def test_scope_failure_never_borrows_env(self, monkeypatch):+ from tools.managed_tool_gateway import _read_user_token_override++ monkeypatch.setenv("TOOL_GATEWAY_USER_TOKEN", "other-profile-tok")+ ss.set_multiplex_active(True)+ with _Scope(_ExplodingScope()):+ with pytest.raises(RuntimeError, match="resolver boom"):+ _read_user_token_override()+-class TestOpenRouterCheckApiKey:def test_scoped_value_wins(self, monkeypatch):from tools.openrouter_client import check_api_key@@@ -191,6 -225,16 +217,15 @@@with _Scope({"UNRELATED": "x"}):assert check_api_key() is False+ def test_scope_failure_never_borrows_env(self, monkeypatch):+ from tools.openrouter_client import check_api_key++ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-other-profile")+ ss.set_multiplex_active(True)+ with _Scope(_ExplodingScope()):+ with pytest.raises(RuntimeError, match="resolver boom"):+ check_api_key()+-# ── Cluster D: auxiliary client key resolution ──────────────────────────────class TestAuxiliaryScopedKeyEnv:@@@ -222,4 -266,47 +257,45 @@@assert _scoped_key_env("") == ""+ def test_scope_failure_never_borrows_env(self, monkeypatch):+ from agent.auxiliary_client import _scoped_key_env++ monkeypatch.setenv("OPENAI_API_KEY", "sk-other-profile")+ ss.set_multiplex_active(True)+ with _Scope(_ExplodingScope()):+ with pytest.raises(RuntimeError, match="resolver boom"):+ _scoped_key_env("OPENAI_API_KEY")+++ # ── Cluster F: hermes_cli config env readers ───────────────────────────────++ class TestScopedEnvironGet:+ """``_scoped_environ_get`` (feeds ``get_env_value`` / ``get_env_value_prefer_dotenv``)+ documents that ``UnscopedSecretError`` propagates; a blanket ``except Exception``+ after the call would silently borrow the launch profile's env on a bound-scope+ failure."""++ def test_scope_failure_never_borrows_env(self, monkeypatch):+ from hermes_cli.config import _scoped_environ_get++ monkeypatch.setenv("SOME_PROFILE_KEY", "other-profile")+ ss.set_multiplex_active(True)+ with _Scope(_ExplodingScope()):+ with pytest.raises(RuntimeError, match="resolver boom"):+ _scoped_environ_get("SOME_PROFILE_KEY")++ def test_unscoped_multiplex_propagates(self, monkeypatch):+ from hermes_cli.config import _scoped_environ_get++ monkeypatch.setenv("SOME_PROFILE_KEY", "launch-env")+ ss.set_multiplex_active(True)+ with pytest.raises(ss.UnscopedSecretError):+ _scoped_environ_get("SOME_PROFILE_KEY")++ def test_single_profile_env_read(self, monkeypatch):+ from hermes_cli.config import _scoped_environ_get++ monkeypatch.setenv("SOME_PROFILE_KEY", "own-env")+ assert _scoped_environ_get("SOME_PROFILE_KEY") == "own-env"+-# ── Cluster E: azure identity presence reads ────────────────────────────────-diff --cc tests/gateway/test_config.pyindex ad41594ebed,38a9fccf74f..14648888881--- a/tests/gateway/test_config.py+++ b/tests/gateway/test_config.py@@@ -2,6 -2,6 +2,7 @@@import loggingimport os++from pathlib import Pathfrom unittest.mock import patchimport pytestdiff --cc tests/gateway/test_proxy_mode.pyindex 796ea45a875,d5979343191..2c5a9a9c64e--- a/tests/gateway/test_proxy_mode.py+++ b/tests/gateway/test_proxy_mode.py@@@ -1,5 -1,5 +1,6 @@@"""Tests for gateway proxy mode — forwarding messages to a remote API server."""++import typesfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@@ -78,12 -82,14 +79,13 @@@ class _FakeSessionasync def __aexit__(self, *args):pass-def _patch_aiohttp(session):-- """Patch aiohttp.ClientSession to return our fake session."""-- return patch(-- "aiohttp.ClientSession",-- return_value=session,++ """Install the optional aiohttp boundary without requiring the extra."""++ module = types.SimpleNamespace(++ ClientSession=MagicMock(return_value=session),++ ClientTimeout=MagicMock(),)-++ return patch.dict("sys.modules", {"aiohttp": module})class TestGetProxyUrl:"""Test _get_proxy_url() config resolution."""@@@ -101,6 -108,39 +103,39 @@@with patch("gateway.run._load_gateway_config", return_value=cfg):assert runner._get_proxy_url() == "http://10.0.0.1:8642"-+ class _SelectiveScope(dict):+ """Bound scope that resolves GATEWAY_PROXY_URL but fails on the KEY read."""+ def get(self, name, default=None):+ if name == "GATEWAY_PROXY_URL":+ return "http://proxy.local:8642"+ if name == "GATEWAY_PROXY_KEY":+ raise RuntimeError("resolver boom")+ return dict.get(self, name, default)+++ class TestProxyKeyScopeFailure:+ """The proxy key read must propagate a bound-scope failure -- the ambient env+ may hold another profile's credential (pre-fix: ``except Exception -> os.getenv``)."""++ @pytest.mark.asyncio+ async def test_proxy_key_scope_failure_never_borrows_env(self, monkeypatch):+ from agent import secret_scope as ss++ monkeypatch.setenv("GATEWAY_PROXY_KEY", "foreign-key")+ runner = _make_runner()+ runner._run_still_current_fn = lambda *a, **k: True++ ss.set_multiplex_active(True)+ token = ss.set_secret_scope(_SelectiveScope())+ try:- with pytest.raises(RuntimeError, match="resolver boom"):- await runner._run_agent_via_proxy("hi", "ctx", [], _make_source(), "sess-1")++ with _patch_aiohttp(MagicMock()):++ with pytest.raises(RuntimeError, match="resolver boom"):++ await runner._run_agent_via_proxy("hi", "ctx", [], _make_source(), "sess-1")+ finally:+ ss.reset_secret_scope(token)+ ss.set_multiplex_active(False)++class TestResolveProxyUrl:def test_no_proxy_bypasses_matching_host(self, monkeypatch):@@@ -230,7 -273,7 +265,7 @@@ class TestRunAgentViaProxypasswith patch("gateway.run._load_gateway_config", return_value={}):-- with patch("aiohttp.ClientSession", return_value=_ErrorSession()):++ with _patch_aiohttp(_ErrorSession()):with patch("aiohttp.ClientTimeout"):result = await runner._run_agent_via_proxy(message="hi",diff --cc tests/gateway/test_restart_drain.pyindex 3f5711030b1,1c7b40c6115..6d2b28cb156--- a/tests/gateway/test_restart_drain.py+++ b/tests/gateway/test_restart_drain.py@@@ -263,7 -263,44 +263,44 @@@ async def test_run_restart_excluded_fro)+ @pytest.mark.asyncio+ async def test_restart_from_served_profile_chat_restarts_the_host_gateway(monkeypatch):+ """A /restart handled inside a served profile's runtime scope restarts the HOST gateway: the+ detached watcher relaunches `hermes gateway restart` under the launch home (under a named+ profile's home it exits 78 and nothing comes back), and stop() - which flushes pending+ messages under get_hermes_home() - runs outside the requester's profile scope."""+ from agent.secret_scope import current_secret_scope+ from hermes_constants import get_hermes_home++ launch_home = get_hermes_home()+ profile_home = launch_home / "profiles" / "research"+ profile_home.mkdir(parents=True)+ (profile_home / ".env").write_text("RESEARCH_ONLY_TOKEN=x\n", encoding="utf-8")++ runner, _adapter = make_restart_runner()+ seen = {}++ async def _recording_stop(**_kwargs):+ seen["stop_home"] = get_hermes_home()+ seen["stop_secret_scope"] = current_secret_scope()++ runner.stop = _recording_stop+ watcher_envs = []+ monkeypatch.setattr(gateway_run, "_resolve_hermes_bin", lambda: ["hermes"])+ monkeypatch.setattr(+ subprocess, "Popen", lambda _argv, **kwargs: watcher_envs.append(kwargs["env"]) or MagicMock()+ )++ async with gateway_run._async_profile_runtime_scope(profile_home):+ assert get_hermes_home() == profile_home+ assert runner.request_restart(detached=True, via_service=False) is True+ await runner._restart_task++ assert [env.get("HERMES_HOME") for env in watcher_envs] == [str(launch_home)]+ assert seen == {"stop_home": launch_home, "stop_secret_scope": None}++[email protected]_only[email protected]("windows")@pytest.mark.asyncioasync def test_windows_detached_restart_scrubs_gateway_marker(monkeypatch, tmp_path):"""Faking sys.platform="win32" on Linux could not reach the real Windowsdiff --cc tests/gateway/test_slash_config_writes_routed_profile.pyindex 18c5a119d26,3135e2469c0..6fcf9a9ac3a--- a/tests/gateway/test_slash_config_writes_routed_profile.py+++ b/tests/gateway/test_slash_config_writes_routed_profile.py@@@ -12,16 -12,20 +12,20 @@@ through ``_gateway_config_home()`` likfrom __future__ import annotationsimport pytest-import yaml+import hermes_yaml as yamlimport gateway.run as gateway_run+ from gateway.config import GatewayConfigfrom gateway.run import GatewayRunner, _profile_runtime_scope- from gateway.slash_commands import GatewaySlashCommandsMixin+ from tools import write_approval as wa- class _Runner(GatewaySlashCommandsMixin):- _run_in_executor_with_context = GatewayRunner._run_in_executor_with_context- _get_executor = GatewayRunner._get_executor+ class _Runner(GatewayRunner):+ """Bare runner (no __init__): the dispatcher binds the routed runtime scope ONCE around every+ table handler (#119915), so drive the handlers through it rather than calling them directly."""++ def __init__(self): # skip GatewayRunner.__init__: only the dispatcher + slash mixins are exercised+ self.config = GatewayConfig(multiplex_profiles=True)def _session_key_for_source(self, _source):return "k"diff --cc tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.pyindex 6db5f9260ba,00000000000..1367e881228mode 100644,000000..100644--- a/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py+++ b/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py@@@ -1,75 -1,0 +1,89 @@@+"""Native launch/result acceptance: real publisher, no checkout-local venv."""+from __future__ import annotations++import json+import os+from pathlib import Path+import subprocess++import pytest++from tests.installation_launcher_fixture import publish_fixture_launcher++ROOT = Path(__file__).resolve().parent.parent.parent.parent+CLI = """+import json, os, sys+from pathlib import Path+def main():+ if '--version' in sys.argv:+ print('Install directory: ' + str(Path(__file__).resolve().parents[1])); return 0+ if '--help' in sys.argv:+ print('--keep-stash'); return 0+ with Path(os.environ['HANDOFF_CALLS']).open('a') as stream:+ stream.write(json.dumps({'argv': sys.argv[1:], 'cwd': os.getcwd()}) + '\\n')+ print('Desktop build failed') # no warning-driven second build on PM++ if sys.argv[1:] == ['gateway', 'start', '--all']:++ return int(os.environ.get('GATEWAY_EXIT', '0'))+ return int(os.environ['HANDOFF_EXIT'])+if __name__ == '__main__':+ sys.exit(main())+"""+[email protected]('windows')- @pytest.mark.parametrize('code', [0, 1, 2])- def test_pm_handoff_runs_once_and_reports_the_actual_result(tmp_path: Path, code: int) -> None:++ ('code', 'no_gateway', 'gateway_code'),++ [(0, False, 0), (1, False, 0), (2, False, 0), (0, True, 0), (0, False, 1)],++)++def test_pm_handoff_reports_update_and_gateway_results(++ tmp_path: Path, code: int, no_gateway: bool, gateway_code: int,++) -> None:+ install = tmp_path / 'checkout with spaces'+ publish_fixture_launcher(install, CLI)+ (install / 'hermes_cli/desktop_update_verify.py').write_text('pass\n')+ home = tmp_path / 'profile'; home.mkdir()+ calls = tmp_path / 'calls.jsonl'++ command = ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',++ str(ROOT / 'scripts/desktop-update/windows.ps1'), '-InstallRoot', str(install), '-NoUi']++ if no_gateway:++ command.append('-NoGateway')+ result = subprocess.run(- ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',- str(ROOT / 'scripts/desktop-update/windows.ps1'), '-InstallRoot', str(install), '-NoUi'],++ command,+ cwd=tmp_path, env={**os.environ, 'HERMES_HOME': str(home),+ 'HERMES_RUNTIME_DIR': str(tmp_path / 'empty-store'),- 'HANDOFF_CALLS': str(calls), 'HANDOFF_EXIT': str(code)},++ 'HANDOFF_CALLS': str(calls), 'HANDOFF_EXIT': str(code),++ 'GATEWAY_EXIT': str(gateway_code)},+ capture_output=True, text=True, timeout=120,+ )+ assert result.returncode == code, result.stdout + result.stderr- assert [json.loads(line) for line in calls.read_text().splitlines()] == [- {'argv': ['update', '--yes', '--gateway', '--branch', 'main', '--keep-stash'], 'cwd': str(install)}- ]++ expected = [{'argv': ['update', '--yes'] + ([] if no_gateway else ['--gateway'])++ + ['--branch', 'main', '--keep-stash'], 'cwd': str(install)}]++ if code == 0 and not no_gateway:++ expected.append({'argv': ['gateway', 'start', '--all'], 'cwd': str(install)})++ assert [json.loads(line) for line in calls.read_text().splitlines()] == expected+ receipt = json.loads((home / '.hermes-update-result.json').read_text(encoding='utf-8-sig'))+ assert receipt['ok'] == (code == 0)++ assert receipt.get('manual', False) == (code == 0 and not no_gateway and gateway_code != 0)+ assert not (home / '.hermes-update-in-progress').exists()++[email protected]('windows')+def test_earlier_pm_userbin_launcher_is_identity_checked(tmp_path: Path) -> None:+ home = tmp_path / 'profile'+ userbin = home / 'bin'; userbin.mkdir(parents=True)+ root = tmp_path / 'source'+ launcher = publish_fixture_launcher(root, CLI)+ external = userbin / launcher.name+ launcher.rename(external)+ wrong = tmp_path / 'other'+ (wrong / 'pm').mkdir(parents=True)+ (wrong / 'hermes_cli').mkdir()+ (wrong / 'hermes_cli/_launchers.py').touch()+ helper = str(ROOT / 'scripts/desktop-update/runtime.ps1').replace("'", "''")+ for target, expected_code in [(root, 0), (wrong, 1)]:+ script = f". '{helper}'; try {{ @(Get-HermesRuntimeCommand -InstallRoot '{target}') | ConvertTo-Json -Compress }} catch {{ exit 1 }}"+ result = subprocess.run(['powershell', '-NoProfile', '-Command', script],+ env={**os.environ, 'HERMES_HOME': str(home)},+ capture_output=True, text=True, timeout=45)+ assert result.returncode == expected_code, result.stdout + result.stderr+ if expected_code == 0:+ assert json.loads(result.stdout) == str(external)diff --cc tests/tui_gateway/test_compute_host_routed_secret_hydration.pyindex 00000000000,ec5c13d253f..4ce0762ac51mode 000000,100644..100644--- a/tests/tui_gateway/test_compute_host_routed_secret_hydration.py+++ b/tests/tui_gateway/test_compute_host_routed_secret_hydration.py@@@ -1,0 -1,68 +1,68 @@@+ """A routed compute-host session hydrates the profile's EXTERNAL secret sources before building its+ scope (#119521): the isolated turn process never ran the launch dotenv path for that profile, so+ without hydration a vault-only provider key is absent from the scope and the agent build fails closed."""++ from __future__ import annotations++ import io+ import types+ from pathlib import Path++ import pytest++ from tui_gateway import server+ from tui_gateway.compute_host import ComputeHost++[email protected]_only[email protected]("linux")+ def test_routed_session_build_sees_the_profiles_external_secret_source(monkeypatch, tmp_path):+ """Two routed homes A→B→A, each with a ``secrets.command`` helper that is the ONLY holder of its+ provider key. Inside each build the scope resolves that profile's key and not the other's."""+ from agent.secret_scope import get_secret, set_multiplex_active+ from hermes_cli import env_loader++ launch = tmp_path / ".hermes"+ launch.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(launch))+ monkeypatch.setenv("VAULT_ONLY_KEY", "from-launch-env")+ env_loader.reset_secret_source_cache()+ monkeypatch.setattr("agent.secret_scope._MULTIPLEX_ACTIVE", False)+ set_multiplex_active(True)++ homes = {}+ for name in ("a", "b"):+ home = launch / "profiles" / name+ home.mkdir(parents=True)+ (home / ".env").write_text(f"{name.upper()}_MARKER=1\n", encoding="utf-8")+ (home / "config.yaml").write_text(+ "secrets:\n command:\n enabled: true\n"+ f" command: \"printf 'VAULT_ONLY_KEY=vault-{name}\\\\n'\"\n",+ encoding="utf-8")+ homes[name] = home++ host = ComputeHost(stdout=io.StringIO(), heartbeat_secs=0)+ seen = []++ def fake_make_agent(sid, key, **kwargs):+ seen.append(get_secret("VAULT_ONLY_KEY"))+ return types.SimpleNamespace(session_id=key)++ def fake_init_session(sid, key, agent, history, **kwargs):+ monkeypatch.setitem(server._sessions, sid, {"agent": agent, "session_key": key})++ monkeypatch.setattr(server, "_make_agent", fake_make_agent)+ monkeypatch.setattr(server, "_transfer_db_to_agent", lambda agent, db: False)+ monkeypatch.setattr(server, "_init_session", fake_init_session)+ try:+ for name in ("a", "b", "a"):+ host._build_server_session(+ server, {"sid": f"s-{name}", "session_key": f"k-{name}", "history": [],+ "profile_home": str(homes[name])}, f"s-{name}")+ finally:+ host.close()+ env_loader.reset_secret_source_cache()+ for name in ("a", "b"):+ server._sessions.pop(f"s-{name}", None)+ # The wrong side is ABSENT: never the launch env, never the other profile's vault.+ assert seen == ["vault-a", "vault-b", "vault-a"]+ assert Path(homes["a"]).exists()diff --cc tui_gateway/model_switch.pyindex 423e4ae44e8,9a9668a8b3a..3c9fd73a129--- a/tui_gateway/model_switch.py+++ b/tui_gateway/model_switch.py@@@ -68,37 -68,43 +68,45 @@@ def _profile_runtime_scope_tokens(profi"""from agent.secret_scope import is_multiplex_activescopes = _TurnScopes()- if profile_home:- home = Path(profile_home)- # External sources first: the requested profile may never have been served in this process.- if hydrate_secrets:- from hermes_cli.env_loader import hydrate_profile_secret_sources- hydrate_profile_secret_sources(home)- secrets = build_profile_secret_scope(home)- overlay = None- scopes.home = set_hermes_home_override(str(home))- else:- # The launch home IS get_hermes_home() (``_profile_home`` answers None for "already the- # launch profile"); single-profile, only its secrets need binding. Once multiplexing is- # active the override is bound too: an unset override is the "unbound context" signal- # plugin runtime bindings and per-home slots fail closed on (#118538).- # Resolved at call time like the launch state.db handle: a harness that re-homes the process- # after import must not have the import-time home's ``.env`` read on every turn.- from tui_gateway.launch_profile_policy import launch_secret_scope, launch_terminal_env- home = _launch_home()- secrets = launch_secret_scope(home)- scopes.secret = set_secret_scope(secrets)- if not is_multiplex_active():- return scopes- scopes.home = set_hermes_home_override(str(home))- overlay = launch_terminal_env()- if scopes.secret is None:- scopes.secret = set_secret_scope(secrets)- # Same terminal policy the gateway binds per turn: a docker-configured profile- # must never resolve the launch process's pinned env. Failure → refusal scope.- from tools.terminal_scope import install_profile_terminal_scope- scopes.terminal = install_profile_terminal_scope(home, env_overlay=overlay)- return scopes+ try:+ if profile_home:+ home = Path(profile_home)+ # External sources first: the requested profile may never have been served in this process.+ if hydrate_secrets:+ from hermes_cli.env_loader import hydrate_profile_secret_sources+ hydrate_profile_secret_sources(home)+ secrets = build_profile_secret_scope(home)+ overlay = None+ scopes.home = set_hermes_home_override(str(home))+ else:+ # The launch home IS get_hermes_home() (``_profile_home`` answers None for "already the+ # launch profile"); single-profile, only its secrets need binding. Once multiplexing is+ # active the override is bound too: an unset override is the "unbound context" signal+ # plugin runtime bindings and per-home slots fail closed on (#118538).++ # Resolve at call time like the launch state.db handle: a harness that++ # re-homes the process after import must not read the old home's .env.+ from tui_gateway.launch_profile_policy import launch_secret_scope, launch_terminal_env- home = Path(_hermes_home)++ home = _launch_home()+ secrets = launch_secret_scope(home)+ # No home stamp: this IS the process's own profile, and the stamp exists only to+ # mark a FOREIGN home for serves_routed_profile().+ scopes.secret = set_secret_scope(secrets)+ if not is_multiplex_active():+ return scopes+ scopes.home = set_hermes_home_override(str(home))+ overlay = launch_terminal_env()+ if scopes.secret is None:+ scopes.secret = set_secret_scope(secrets, profile_home=str(home) if profile_home else None)+ # Same terminal policy the gateway binds per turn: a docker-configured profile+ # must never resolve the launch process's pinned env. Failure → refusal scope.+ from tools.terminal_scope import install_profile_terminal_scope+ scopes.terminal = install_profile_terminal_scope(home, env_overlay=overlay)+ return scopes+ except Exception:+ # A raise mid-bind leaves no return value for the caller to release —+ # undo whatever was bound before propagating.+ _release_profile_runtime_scope_tokens(scopes)+ raisedef _release_profile_runtime_scope_tokens(scopes: "_TurnScopes | None") -> None: