The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: round-5 CI backlog after the 779-commit main merge
ethernetf3b13992119e
diff --git a/gateway/config.py b/gateway/config.pyindex 84c924898a4..fe3111e91c2 100644--- a/gateway/config.py+++ b/gateway/config.py@@ -177,12 +177,12 @@ _Platform__bundled_plugin_aliases: Optional[dict] = None # manifest ``name:`` (def _bundled_platform_manifest_name(plugin_dir: Path) -> Optional[str]:"""Lowercased ``name:`` from a bundled platform's plugin manifest (None when absent/unreadable)."""try:- import yaml+ from hermes_yaml import safe_loadmanifest_file = next((plugin_dir / m for m in ("plugin.yaml", "plugin.yml") if (plugin_dir / m).exists()), None)if manifest_file is None:return None- data = yaml.safe_load(manifest_file.read_text(encoding="utf-8-sig")) or {}+ data = safe_load(manifest_file.read_text(encoding="utf-8-sig")) or {}name = data.get("name") if isinstance(data, dict) else Nonereturn str(name).strip().lower() or Noneexcept Exception:diff --git a/gateway/run.py b/gateway/run.pyindex f9d9f9ca30d..e4ab157d554 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -4715,7 +4715,7 @@ def _start_gateway_housekeeping((60, "Org sync pull tick", profile_scoped_chore(runner, _housekeeping_org_skill_sync)),(60, "Auto-archive tick", profile_scoped_chore(runner, _housekeeping_auto_archive)),# Due-gated inside: the first tick after startup runs an overdue check, not tick 60.- (1, "Plugin update check", profile_scoped_chore(runner, _housekeeping_plugin_update_check)),+ (1, "Plugin update check", _housekeeping_plugin_update_check),(1, "Deferred FTS retry tick", _housekeeping_deferred_fts_retry),(1, "gateway housekeeping memory trim", _housekeeping_memory_trim),(1, "MCP config reconcile", _mcp_config_reconciler(runner)),diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 5a37e632e33..79b1aa35623 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -617,355 +617,6 @@ def _run_backup_locked(args, hermes_root: Path) -> bool:# --- Import ----def _validate_backup_zip(zf: zipfile.ZipFile) -> tuple[bool, str]:- """Check that a zip looks like a Hermes backup."""- names = zf.namelist()- if not names:- return False, "zip archive is empty"- # Telltale files a hermes home has — at the root or one level deep (zipped directory).- if not any(Path(n).name in {"config.yaml", ".env", "state.db"} for n in names):- return False, "zip does not appear to be a Hermes backup (no config.yaml, .env, or state databases found)"- return True, ""---def _detect_prefix(zf: zipfile.ZipFile) -> str:- """Detect if the zip has a common directory prefix wrapping all entries."""- names = [n for n in zf.namelist() if not n.endswith("/")]- first_parts = {Path(n).parts[0] for n in names if len(Path(n).parts) > 1}- if len(first_parts) == 1 and first_parts <= {".hermes", "hermes"}:- return first_parts.pop() + "/"- return ""---def _extract_member_atomically(- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:- """Restore one zip member onto *target* with no truncation window.-- ``open(target, "wb")`` would truncate the user's file before any replacement bytes exist.- ``atomic_replace`` (not bare ``os.replace``) resolves a symlinked target first, so a- dotfiles-linked ``config.yaml`` keeps the link (#16743), and falls back to copy/fsync/unlink- on ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs.- """- # Mode is None when the target does not exist: the umask-derived create-mode applies.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)- if mode is None:- mode = new_file_mode- else:- # Deliberately NOT a faithful copy: setuid/setgid are dropped. The bytes come from the- # archive, so carrying elevated bits would hand the zip's author the identity an existing- # setuid file runs as — and ``_external/`` publishes members anywhere under ``$HOME``.- mode &= ~(stat.S_ISUID | stat.S_ISGID)- # Truncate the stem: mkstemp adds ~16 chars and a member near NAME_MAX would otherwise fail.- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial")- try:- with os.fdopen(fd, "wb") as dst:- if mode is not None:- # Apply the mode BEFORE the replace so the target never transits through mkstemp's- # 0600 and the EXDEV/EBUSY ``copystat`` fallback copies the intended bits.- if hasattr(os, "fchmod"): # Unix-only; Windows takes the path-based chmod- os.fchmod(dst.fileno(), mode)- else:- os.chmod(tmp_name, mode)- # Stream: a multi-gigabyte state.db member must not be held in memory in one piece.- with zf.open(member) as src:- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- real_path = Path(atomic_replace(tmp_name, target))- # Owner first, mode second (as ``atomic_yaml_write``): chown drops setuid/setgid and- # ``mode`` no longer carries them, so neither step can re-elevate the restored file.- _restore_file_owner(real_path, owner)- _restore_file_mode(real_path, mode)- except BaseException:- with suppress(OSError):- os.unlink(tmp_name)- raise---def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:- """``(sessions, messages)`` in session database *path*; read-only, best effort.-- ``None`` means "unknown" (missing, not a Hermes session store, unreadable) — never "zero":- acting on an unreadable database would mask the very loss this count exists to surface.- Same contract as :func:`_count_cron_jobs`.- """- if not path.is_file():- return None- try:- conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)- except sqlite3.Error:- return None- try:- sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]- messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]- return int(sessions), int(messages)- except (sqlite3.Error, TypeError, ValueError):- return None- finally:- conn.close()---def _import_db_member(- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:- """Publish a SQLite ``.db`` member onto *target* without replacing its inode.-- A rename-publish over a live database is the #65942 / #90950 corruption class: a gateway,- dashboard, or WebUI holding it open keeps serving the unlinked inode and writing sessions no- other process will see, and a sidecar WAL beside the new file describes the old database —- nothing fails, the sessions are simply gone (#100960). Route the member through the same- ``_safe_restore_db`` page copy ``/snapshot restore`` uses, so the live inode is preserved and- every open connection converges. Raises ``OSError`` when the database could not be- replaced safely, so the caller reports a skipped file instead of a silent success.- """- if not target.exists():- # "Missing" is not "unheld": a gateway or dashboard that had the database open when it- # was unlinked still writes the deleted inode (the ``(deleted)`` fingerprint of #90950).- # Publishing a fresh inode here re-creates the same split brain the branch below exists- # to prevent, so refuse and name the holders instead (#110179).- holders = _foreign_db_holder_pids(target)- if holders:- raise OSError(- f"{target.name} was deleted but is still open in PID(s) "- f"{', '.join(str(pid) for pid in sorted(holders))}; publishing a new file would "- "leave them writing an invisible database. Stop those processes and re-run the import."- )- _extract_member_atomically(zf, member, target, new_file_mode)- return- # The database keeps its own mode/ownership: the bytes come from the archive, the file does not.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport")- try:- with os.fdopen(fd, "wb") as dst:- with zf.open(member) as src: # stream: never hold a multi-GB state.db in memory- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- if not _safe_restore_db(Path(tmp_name), target):- raise OSError(- "live-safe restore refused or failed; the existing database was "- "left untouched. Stop the gateway/dashboard processes holding it "- "open and re-run the import."- )- _restore_file_owner(target, owner)- _restore_file_mode(target, mode)- finally:- with suppress(OSError):- os.unlink(tmp_name)---def _confirm_import_overwrite(hermes_root: Path) -> bool:- """Prompt before importing over an existing installation; True when import may proceed."""- if not any((hermes_root / m).exists() for m in ("config.yaml", ".env")):- return True- print("\nWarning: Target directory already has Hermes configuration.\n"- "Importing will overwrite existing files with backup contents.\n")- try:- answer = input("Continue? [y/N] ").strip().lower()- except (EOFError, KeyboardInterrupt):- print("\nAborted.")- sys.exit(1)- if answer in {"y", "yes"}:- return True- print("Aborted.")- return False---def _import_members(- zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int-) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:- """Publish every member; return ``(restored, restored_external, errors, skipped_runtime, db_shrunk)``.-- ``db_shrunk`` holds ``(rel, live_counts, imported_counts)`` for every session database the- import replaced with one holding fewer rows — allowed, but never silent (#100960).- """- errors: list[str] = []- skipped_runtime: list[str] = []- db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []- restored = restored_external = 0- home_dir = Path.home().resolve()- new_file_mode = default_new_file_mode() # once: every member is published via mkstemp (0600)- for member in members:- # ``_external/`` members restore to their home-relative location (~/.honcho/config.json),- # NOT under HERMES_HOME; provider configs commonly hold credentials, so tighten to 0600.- external = member.startswith(_EXTERNAL_PREFIX)- if external:- rel = member[len(_EXTERNAL_PREFIX):]- target = home_dir / rel- root = home_dir- tighten = target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES- else:- rel = member[len(prefix):] if prefix and member.startswith(prefix) else member- if rel and Path(rel).name in _IMPORT_SKIP_NAMES: # see ``_IMPORT_SKIP_NAMES``- skipped_runtime.append(rel)- continue- # A ``.db`` member is page-restored into the live file; an archived WAL/SHM/journal- # describes a different database image and installed beside it (over a live sidecar)- # would replay a foreign WAL on next open. Current backups never ship these- # (_EXCLUDED_SUFFIXES); older or hand-built archives might.- if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):- skipped_runtime.append(rel)- continue- target = hermes_root / rel- root = hermes_root.resolve()- tighten = target.name in _SECRET_FILE_NAMES- if not rel:- continue-- label = member if external else rel- if not _is_within(target, root):- errors.append(f"{label}: path traversal blocked")- else:- try:- target.parent.mkdir(parents=True, exist_ok=True)- if target.suffix == ".db":- # Count before the write: afterwards the dropped rows are gone.- before = _count_session_rows(target)- _import_db_member(zf, member, target, new_file_mode)- after = _count_session_rows(target)- if before and after and after[1] < before[1]:- db_shrunk.append((rel, before, after))- else:- _extract_member_atomically(zf, member, target, new_file_mode)- if tighten:- try:- os.chmod(target, 0o600)- except OSError:- if not external: # external configs are tightened best-effort only- raise- restored += 1- restored_external += external- except (PermissionError, OSError) as exc:- errors.append(f"{label}: {exc}")-- if restored % 500 == 0:- print(f" {restored}/{file_count} files ...")-- return restored, restored_external, errors, skipped_runtime, db_shrunk---def run_import(args) -> None:- """Restore a Hermes backup from a zip file."""- zip_path = Path(args.zipfile).expanduser().resolve()- if not zip_path.is_file():- print(f"Error: File not found: {zip_path}")- sys.exit(1)- if not zipfile.is_zipfile(zip_path):- print(f"Error: Not a valid zip file: {zip_path}")- sys.exit(1)- # The restore target is the home the command operates under (the printed "Target:");- # ``get_default_hermes_root()`` would silently retarget a profile restore at the live root.- hermes_root = get_hermes_home()- with zipfile.ZipFile(zip_path, "r") as zf:- ok, reason = _validate_backup_zip(zf)- if not ok:- print(f"Error: {reason}")- sys.exit(1)- prefix = _detect_prefix(zf)- members = [n for n in zf.namelist() if not n.endswith("/")]- file_count = len(members)- print(f"Backup contains {file_count} files\nTarget: {display_hermes_home()}")- if prefix:- print(f"Detected archive prefix: {prefix!r} (will be stripped)")- if not args.force and not _confirm_import_overwrite(hermes_root):- return- print(f"\nImporting {file_count} files ...")- hermes_root.mkdir(parents=True, exist_ok=True)- t0 = time.monotonic()- restored, restored_external, errors, skipped_runtime, db_shrunk = _import_members(- zf, members, prefix, hermes_root, file_count)- elapsed = time.monotonic() - t0- print(f"\nImport complete: {restored} files restored in {elapsed:.1f}s\n Target: {display_hermes_home()}")- if restored_external:- print(f"\n Restored {restored_external} memory-provider file(s) to "- f"their original location(s) outside {display_hermes_home()}.")- if errors:- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")- if db_shrunk:- # The backup predates work that is now overwritten — say so (#100960: twelve sessions- # disappeared with nothing logged anywhere).- print("\n ⚠ Session data replaced by older backup contents:")- for rel, before, after in db_shrunk:- print(f" {rel}: {before[0]} session(s) / {before[1]} message(s)"- f" -> {after[0]} / {after[1]}")- print(f" Anything recorded after the backup was taken is not in it. {_snapshot_recovery_hint()}")- if skipped_runtime:- _print_capped(f"\n Preserved {len(skipped_runtime)} runtime state "- f"file(s) (kept this machine's, not the backup's):",- sorted(skipped_runtime), " ")- restored_profiles = _restore_profile_wrappers(hermes_root)- print()- if not (hermes_root / "hermes-agent").is_dir():- print("Note: The hermes-agent codebase was not included in the backup.\n"- " If this is a fresh install, run: hermes update")- if restored_profiles:- print("\nTo re-enable gateway services for profiles:")- for pname in restored_profiles:- print(f" hermes -p {pname} gateway install")- _revive_gateway_after_import(hermes_root)- print("Done. Your Hermes configuration has been restored.")---def _restore_profile_wrappers(hermes_root: Path) -> List[str]:- """Re-create shell wrapper scripts for restored named profiles; return the profile names seen."""- profiles_dir = hermes_root / "profiles"- restored_profiles: list[tuple[str, bool]] = []- if not profiles_dir.is_dir():- return []- try:- from hermes_cli.profiles import (- create_wrapper_script, check_alias_collision, _is_wrapper_dir_in_path, _get_wrapper_dir)- for entry in sorted(profiles_dir.iterdir()):- if not entry.is_dir() or not any((entry / m).exists() for m in ("config.yaml", ".env")):- continue # only profiles with config get wrappers- profile_name = entry.name- collision = check_alias_collision(profile_name)- if collision:- print(f" Skipped alias '{profile_name}': {collision}")- restored_profiles.append(- (profile_name, not collision and create_wrapper_script(profile_name) is not None))- if restored_profiles:- created = [n for n, ok in restored_profiles if ok]- skipped = [n for n, ok in restored_profiles if not ok]- if created:- print(f"\n Profile aliases restored: {', '.join(created)}")- if skipped:- print(f" Profile aliases skipped: {', '.join(skipped)}")- if not _is_wrapper_dir_in_path():- print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.\n"- " Add to your shell config (~/.bashrc or ~/.zshrc):\n"- ' export PATH="$HOME/.local/bin:$PATH"')- except ImportError: # hermes_cli.profiles unavailable (fresh install)- if any(profiles_dir.iterdir()):- print("\n Profiles detected but aliases could not be created.\n"- " Run: hermes profile list (after installing hermes)")- return [n for n, _ in restored_profiles]---def _revive_gateway_after_import(hermes_root: Path) -> None:- """Install/start the gateway service after a restore, best-effort and prompt-free.-- Bot tokens and cron jobs are inert without a gateway (a platform-less gateway is supported, so- this is safe for any backup); failures print a manual fallback, never fail the import. Only- revived when the restore landed in the default home or no other install exists: a sandbox or- profile restore must not install a second gateway on the default service name.- """- native_default = _get_platform_default_hermes_home()- if hermes_root != native_default and any(- (native_default / marker).exists() for marker in ("config.yaml", ".env", "state.db")):- print("\nRestored into a non-default home; leaving the gateway service alone to avoid clashing "- f"with the install at {native_default}.\n"- "To start a gateway for this home, run: hermes gateway install")- return- try:- from hermes_cli.gateway import ensure_gateway_service, _is_service_running- if not _is_service_running():- print()- ensure_gateway_service(context="import")- except Exception:- print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway install")-# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---diff --git a/hermes_cli/backup_restore.py b/hermes_cli/backup_restore.pyindex e075bcc37cb..0845b02a4fb 100644--- a/hermes_cli/backup_restore.py+++ b/hermes_cli/backup_restore.py@@ -414,14 +414,23 @@ def _import_db_member(on users who have already lost something once. Route the member throughthe same ``_safe_restore_db`` page copy that ``/snapshot restore`` has usedsince #65942: the live inode is preserved, every open connection converges- on the imported data, and the sidecars are handled there. A target that- does not exist yet has no holders and no inode worth preserving, so it- takes the ordinary atomic publish.+ on the imported data, and the sidecars are handled there.Raises ``OSError`` when the database could not be replaced safely, so thecaller reports a skipped file instead of counting a silent success."""if not target.exists():+ # "Missing" is not "unheld": a gateway or dashboard that had the database open when it+ # was unlinked still writes the deleted inode (the ``(deleted)`` fingerprint of #90950).+ # Publishing a fresh inode here re-creates the same split brain the branch below exists+ # to prevent, so refuse and name the holders instead (#110179).+ holders = _foreign_db_holder_pids(target)+ if holders:+ raise OSError(+ f"{target.name} was deleted but is still open in PID(s) "+ f"{', '.join(str(pid) for pid in sorted(holders))}; publishing a new file would "+ "leave them writing an invisible database. Stop those processes and re-run the import."+ )_extract_member_atomically(zf, member, target, new_file_mode)returndiff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex fd181e54959..8694604880e 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -67,27 +67,6 @@ from hermes_cli.setup import (prompt_yes_no,)from hermes_cli.colors import Colors, color-from hermes_cli.gateway_service_unit import (- _systemd_env_line,- _installed_unit_ld_library_path,- _ld_library_path_line,- _hermes_home_for_target_user,- _build_service_path_dirs,- _stable_service_working_dir,- _systemd_watchdog_seconds,- _append_node_dir_for_service,- _service_venv_dir,- generate_systemd_unit,- _normalize_service_definition,- _SYSTEMD_OPTIONAL_DIRECTIVES,- _strip_optional_systemd_directives,- _normalize_launchd_plist_for_comparison,- systemd_unit_is_current,- _temp_home_in_service_definition,- _refuse_temp_home_service_write,- refresh_systemd_unit_if_needed,-)-logger = logging.getLogger(__name__)# Shared ``subprocess.run`` kwargs for text-mode probes (stdout/stderr captured, decode-tolerant).@@ -2920,6 +2899,411 @@ def _remap_path_for_user(path: str, target_home_dir: str) -> str:+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 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):+ 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 --git a/hermes_cli/gateway_service_unit.py b/hermes_cli/gateway_service_unit.pydeleted file mode 100644index 99527168de6..00000000000--- a/hermes_cli/gateway_service_unit.py+++ /dev/null@@ -1,354 +0,0 @@-"""Gateway service-unit definitions: systemd unit generation, staleness comparison and refresh.--Extracted from ``hermes_cli/gateway.py``. Bodies read facade helpers through ``_gw()`` (late-binding on ``hermes_cli.gateway``) so the seams tests and callers patch on the facade keep-intercepting the moved code.-"""-from __future__ import annotations--import logging-import os-import shutil-import sys-from pathlib import Path--logger = logging.getLogger(__name__)---def _gw():- from hermes_cli import gateway # late: the facade imports this module- return gateway---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 _gw()._unit_environment_value(_gw().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 _gw()._installed_unit_ld_library_path(system)- components = [p for p in raw.split(":") if p]- if target_home_dir is not None:- components = [_gw()._remap_path_for_user(p, target_home_dir) for p in components]- return _gw()._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 _gw().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 = _gw().PROJECT_ROOT-- def _is_dir(path: Path) -> bool:- try:- return path.is_dir()- except OSError:- return False-- candidates = []- venv_bin = project_root / "venv" / "bin"- if _is_dir(venv_bin):- candidates.append(str(venv_bin))- elif sys.prefix != sys.base_prefix:- candidates.append(str(Path(sys.prefix) / "bin"))-- hermes_home = _gw().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 _gw().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 = _gw().get_hermes_home()- if home and Path(home).is_dir():- return str(Path(home).resolve())- except Exception:- pass- return str(_gw().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 = _gw().load_gateway_config()- return _gw().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 _append_node_dir_for_service(path_entries: list[str], hermes_root: Path | None = None) -> None:- """Append the Node dir a service unit should use: managed ``<hermes_root>/node`` (profile-scoped)- first — a unit survives reboots, so baking a shell-PATH Node is permanent breakage — else PATH lookup."""- 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 _service_venv_dir() -> str:- """VIRTUAL_ENV baked into service definitions: detected venv, else ``_gw().PROJECT_ROOT/venv``."""- detected_venv = _gw()._detect_venv_dir()- return str(detected_venv) if detected_venv else str(_gw().PROJECT_ROOT / "venv")---def generate_systemd_unit(system: bool = False, run_as_user: str | None = None) -> str:- python_path = _gw().get_python_path()- working_dir = _gw()._stable_service_working_dir()- venv_dir = _gw()._service_venv_dir()-- path_entries = _gw()._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).- _gw()._append_node_dir_for_service(path_entries)-- # TimeoutStopSec must cover the full stop budget (cron drain + cleanup) or systemd SIGKILLs mid-drain.- restart_timeout = _gw().resolve_systemd_timeout_stop_sec(_gw()._get_restart_drain_timeout(), _gw()._get_cron_drain_timeout())-- if system:- username, group_name, home_dir, uid = _gw()._system_service_identity(run_as_user)- hermes_home = _gw()._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 = _gw()._profile_arg(hermes_home, default_root=target_root)- except ValueError:- profile_arg = _gw()._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 = _gw()._remap_path_for_user(python_path, home_dir)- working_dir = str(hermes_home) if hermes_home else _gw()._remap_path_for_user(working_dir, home_dir)- venv_dir = _gw()._remap_path_for_user(venv_dir, home_dir)- path_entries = [_gw()._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] = []- _gw()._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'- ) + _gw()._ld_library_path_line(system=True, target_home_dir=home_dir)- wanted_by = "multi-user.target"- else:- hermes_home = str(_gw().get_hermes_home().resolve())- profile_arg = _gw()._profile_arg(hermes_home)- user_home = Path.home()- identity_lines = ordering_lines = ""- env_lines = _gw()._ld_library_path_line(system=False)- wanted_by = "default.target"-- watchdog_seconds = _gw()._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(_gw()._build_user_local_paths(user_home, path_entries))- path_entries.extend(_gw()._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)- return f"""[Unit]-Description={_gw().SERVICE_DESCRIPTION}-After=network-online.target-Wants=network-online.target-{ordering_lines}StartLimitIntervalSec=0--[Service]-Type={systemd_type}-{systemd_watchdog_directives}{identity_lines}ExecStart={python_path} -m hermes_cli.main{f" {profile_arg}" if profile_arg else ""} gateway run-WorkingDirectory={working_dir}-{env_lines}Environment="PATH={sane_path}"-Environment="VIRTUAL_ENV={venv_dir}"-Environment="HERMES_HOME={hermes_home}"-Environment="HERMES_SUPERVISED_CHILD=1"-Restart=always-RestartSec=5-RestartForceExitStatus={_gw().GATEWAY_SERVICE_RESTART_EXIT_CODE}-SuccessExitStatus={_gw().GATEWAY_SERVICE_RESTART_EXIT_CODE}-RestartPreventExitStatus={_gw().GATEWAY_FATAL_CONFIG_EXIT_CODE}-KillMode=mixed-KillSignal=SIGTERM-ExecReload=/bin/kill -USR1 $MAINPID-ExecStop=-{python_path} -m gateway.systemd_stop_mark-ExecStopPost=-{python_path} -m gateway.cgroup_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",- _gw()._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).- _gw()._sync_hermes_home_from_systemd_unit(system=system)-- unit_path = _gw().get_systemd_unit_path(system=system)- if not unit_path.exists():- return False-- installed = unit_path.read_text(encoding="utf-8-sig")- expected_user = _gw()._read_systemd_user_from_unit(unit_path) if system else None- expected = _gw().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: _gw()._normalize_service_definition(_gw()._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 = _gw()._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 refresh_systemd_unit_if_needed(system: bool = False) -> bool:- """Rewrite the installed systemd unit when the generated definition has changed."""- unit_path = _gw().get_systemd_unit_path(system=system)- if not unit_path.exists():- return False-- # _gw().systemd_unit_is_current is the HERMES_HOME-sync chokepoint; its env mutation persists for the regenerate below.- if _gw().systemd_unit_is_current(system=system):- return False-- expected_user = _gw()._read_systemd_user_from_unit(unit_path) if system else None- new_unit = _gw().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 _gw()._refuse_temp_home_service_write(new_unit, "systemd unit"):- return False-- unit_path.write_text(new_unit, encoding="utf-8")- _gw()._run_systemctl(["daemon-reload"], system=system, check=True, timeout=30)- print(f"↻ Updated gateway {_gw()._service_scope_label(system)} service definition to match the current Hermes install")- return Truediff --git a/hermes_cli/memory_setup.py b/hermes_cli/memory_setup.pyindex c95e0e612cd..6405d7e3874 100644--- a/hermes_cli/memory_setup.py+++ b/hermes_cli/memory_setup.py@@ -85,12 +85,10 @@ def prepare_memory_provider_dependencies(provider_name: str) -> tuple[dict, strif not inputs:return meta, Nonepm.sync_venv(explicit=True, **inputs)- from pm.environments import selected_venv, site_packages+ from pm.environments import running_from_selected_environmentfrom pm.paths import repo_root- selected = site_packages(selected_venv(repo_root())).resolve()- active = {Path(entry).resolve() for entry in sys.path}- return meta, "installed" if selected in active else "restart_required"+ return meta, "installed" if running_from_selected_environment(repo_root()) else "restart_required"def _install_dependencies(provider_name: str) -> None:diff --git a/pm/environment.py b/pm/environment.pyindex 008383d18a6..12acb387339 100644--- a/pm/environment.py+++ b/pm/environment.py@@ -35,6 +35,23 @@ _RESOLVER_MARKERS = ()+class ResolutionConflict(InstallError):+ """uv's resolver proved the union has no valid solution."""+++def classify_uv_failure(stage: str, returncode: int, output: str) -> InstallError:+ """Turn a failed `uv <stage>` into the right classified error.++ Resolver-conflict output → ResolutionConflict; anything else (fetch,+ build, tooling) → plain InstallError with the tail of the output.+ """+ cause = f"uv {stage} exited {returncode}: {output.strip()[-600:]}"+ lowered = output.lower()+ if any(marker in lowered for marker in _RESOLVER_MARKERS):+ return ResolutionConflict("venv", cause)+ return InstallError("venv", cause)++def prune_site_pth(venv_dir: Path) -> None:"""Drop .pth files that must never execute inside a shipped payload.@@ -219,8 +236,6 @@ class PythonEnvironment:raise InstallError("venv", f"uv venv failed: {result.stderr[-600:]}")def lock(self, source: Path, *, upgrade: bool = False, timeout: int = 1800) -> None:- from pm.workspace import classify_uv_failure-command = ["lock", "--python", str(self.python)]if upgrade:command.append("--upgrade")@@ -229,8 +244,6 @@ class PythonEnvironment:raise classify_uv_failure("lock", result.returncode, result.stderr or result.stdout)def check_lock(self, source: Path) -> None:- from pm.workspace import classify_uv_failure-result = self._run(["lock", "--check", "--python", str(self.python)],cwd=source, timeout=1800)if result.returncode:@@ -245,8 +258,6 @@ class PythonEnvironment:``frozen=False`` is reserved for the caller-owned generated workspace,never the original project's lock. Seed/replay policy belongs to PM."""- from pm.workspace import classify_uv_failure-if only_groups and (not groups or extras or all_extras):raise ValueError("group-only builds require groups and cannot select extras")if not frozen:@@ -276,8 +287,6 @@ class PythonEnvironment:def export_requirements(self, source: Path, out: Path, *, extras: Sequence[str] = (),timeout: int = 1800) -> None:- from pm.workspace import classify_uv_failure-command = ["export", "--frozen", "--python", str(self.python), "--no-default-groups","--no-emit-project", "--no-hashes", "--no-annotate", "--no-header","--format", "requirements-txt", "--output-file", str(out)]@@ -298,8 +307,6 @@ class PythonEnvironment:def _install_requirements_file(self, requirements: Path, *, wheelhouse: Path | None = None,timeout: int = 1800) -> None:- from pm.workspace import classify_uv_failure-command = ["pip", "install", "--no-config", "--python", str(self.executable),"--requirements", str(requirements)]if wheelhouse is not None:diff --git a/pm/workspace.py b/pm/workspace.pyindex 5cadda0848e..ce39fab66d4 100644--- a/pm/workspace.py+++ b/pm/workspace.py@@ -27,26 +27,10 @@ def _member_ignored(directory, names):return [name for name in names if name in _MEMBER_EXCLUDE or name.endswith(".egg-info")]-class ResolutionConflict(InstallError):- """uv's resolver proved the union has no valid solution."""---# Markers uv prints ONLY when the resolver itself proves no solution-# exists (its conflict report: "Because ...", "no solution found").-from pm.environment import _RESOLVER_MARKERS # noqa: E402 — defined beside the uv runner---def classify_uv_failure(stage: str, returncode: int, output: str) -> InstallError:- """Turn a failed `uv <stage>` into the right classified error.-- Resolver-conflict output → ResolutionConflict; anything else (fetch,- build, tooling) → plain InstallError with the tail of the output.- """- cause = f"uv {stage} exited {returncode}: {output.strip()[-600:]}"- lowered = output.lower()- if any(marker in lowered for marker in _RESOLVER_MARKERS):- return ResolutionConflict("venv", cause)- return InstallError("venv", cause)+# The uv failure classifier lives beside the uv runner (stdlib-only imports): the bootstrap+# runner streams uv output from a pre-3.11 system python where this module's tomllib import+# cannot load. Workspace callers keep reaching it from here.+from pm.environment import ResolutionConflict, classify_uv_failure # noqa: E402,F401def member_sources(plugin_dirs) -> dict[Path, Path]:diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1index 07195318766..4b3cd669313 100644--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@ -1552,7 +1552,7 @@ try {# same channel credentials as the remote host it becomes a competing# long-poll consumer (e.g. Telegram rejects one of the two getUpdates# callers).- $gatewayArg = @('--gateway')+ $gatewayArg = @("--gateway")if ($NoGateway) {$gatewayArg = @()Write-HandoffLog "update requested without --gateway (remote-served Desktop)"diff --git a/scripts/run_tests.sh b/scripts/run_tests.shindex 4137437dc42..88c58ba8c0c 100755--- a/scripts/run_tests.sh+++ b/scripts/run_tests.sh@@ -133,7 +133,8 @@ for _tool_var in INCLUDE LIB LIBPATH VSINSTALLDIR VCINSTALLDIR VCToolsInstallDirWindowsLibPath UCRTVersion UniversalCRTSdkDir VSCMD_ARG_HOST_ARCH VSCMD_ARG_TGT_ARCH VSCMD_VER \DevEnvDir ExtensionSdkDir Platform CARGO_HOME RUSTUP_HOME RUSTUP_TOOLCHAIN \CARGO_TARGET_AARCH64_PC_WINDOWS_MSVC_LINKER CC_aarch64_pc_windows_msvc CC CXX AR \- VCPKG_ROOT OPENSSL_DIR OPENSSL_STATIC OPENSSL_LIB_DIR OPENSSL_INCLUDE_DIR; do+ VCPKG_ROOT OPENSSL_DIR OPENSSL_STATIC OPENSSL_LIB_DIR OPENSSL_INCLUDE_DIR \+ DISTUTILS_USE_SDK MSSdk; doif [ -n "${!_tool_var:-}" ]; thenWIN_ENV+=("$_tool_var=${!_tool_var}")fidiff --git a/scripts/windows-build-deps.ps1 b/scripts/windows-build-deps.ps1index 51d33853477..258a47e8dcb 100644--- a/scripts/windows-build-deps.ps1+++ b/scripts/windows-build-deps.ps1@@ -119,6 +119,11 @@ function Initialize-HermesArm64BuildTools {$linker = (Get-Command link.exe -ErrorAction Stop).Sourceif ($linker -notlike '*\MSVC\*') { throw "MSVC link.exe is shadowed by $linker" }$env:CARGO_TARGET_AARCH64_PC_WINDOWS_MSVC_LINKER = $linker+ # setuptools' MSVC detection ignores an already-primed developer environment and asks+ # vswhere (via ProgramFiles(x86)) unless both of these are set; hermetic test runners+ # (`env -i`) carry INCLUDE/LIB but not the discovery variables vswhere needs.+ $env:DISTUTILS_USE_SDK = '1'+ $env:MSSdk = '1'# Child builds isolate HOME/USERPROFILE. Keep Rust anchored to the homes# used here, including caller-selected locations.diff --git a/tests-js/scripts/desktop-chat-smoke.ts b/tests-js/scripts/desktop-chat-smoke.tsindex 2ea3c796930..4d70111c925 100644--- a/tests-js/scripts/desktop-chat-smoke.ts+++ b/tests-js/scripts/desktop-chat-smoke.ts@@ -121,7 +121,9 @@ export async function waitForChatReady(page: Page, timeoutMs = 120_000): Promise/** What the composer actually contains, for a failure that explains itself. */async function composerDiagnostics(root: Locator): Promise<string> {try {- if (await root.count() === 0) return '(no [data-slot="composer-root"] in the DOM)'+ if (await root.count() === 0) {+ return '(no [data-slot="composer-root"] in the DOM)'+ }return (await root.first().evaluate((el: Element): string => el.outerHTML.slice(0, 1500)))} catch (error) {return `(diagnostics unavailable: ${(error as Error).message})`diff --git a/tests-js/scripts/desktop-smoke-process.ts b/tests-js/scripts/desktop-smoke-process.tsindex 4ccdb79bd11..85e72ce4a32 100644--- a/tests-js/scripts/desktop-smoke-process.ts+++ b/tests-js/scripts/desktop-smoke-process.ts@@ -176,7 +176,9 @@ export function assertBackendOrigin(backend: NativeProcess, root: string, originreturn new RegExp(`(?:^|[\\s"'])${escaped}(?:[/\\\\]|[\\s"']|$)`, process.platform === 'win32' ? 'i' : '').test(command)})const sameTree = (value?: string): boolean => {- if (value === undefined) return false+ if (value === undefined) {+ return false+ }// An unreadable path is no evidence, not a crash: a process cwd can be gone.try { return fs.realpathSync(value) === fs.realpathSync(root) } catch { return false }}diff --git a/tests-js/scripts/mock-provider-config.ts b/tests-js/scripts/mock-provider-config.tsindex 9773fa64aec..f604772290a 100644--- a/tests-js/scripts/mock-provider-config.ts+++ b/tests-js/scripts/mock-provider-config.ts@@ -104,9 +104,13 @@ export function writeEnvFile(hermesHome: string, apiKey = 'e2e-mock-key', mockUr}// Drop the prior file's trailing blank lines BEFORE appending: trimEnd() runs// after the appended keys, so it cannot reach a blank line that they now follow.- while (kept.length > 0 && kept[kept.length - 1].trim() === '') kept.pop()+ while (kept.length > 0 && kept[kept.length - 1].trim() === '') {+ kept.pop()+ }for (const [key, line] of reps) {- if (!seen.has(key)) kept.push(line)+ if (!seen.has(key)) {+ kept.push(line)+ }}fs.writeFileSync(envPath, `${kept.join('\n').trimEnd()}\n`, { mode: 0o600 })}diff --git a/tests/acp_adapter/test_session_reasoning_config.py b/tests/acp_adapter/test_session_reasoning_config.pyindex 1ba5c2fa9bb..cb030ad019a 100644--- a/tests/acp_adapter/test_session_reasoning_config.py+++ b/tests/acp_adapter/test_session_reasoning_config.py@@ -11,7 +11,7 @@ import osfrom pathlib import Pathimport pytest-import yaml+import hermes_yaml as yamlfrom acp_adapter.session import SessionManagerdiff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.pyindex 6aab6f565fd..85f46cdafa9 100644--- a/tests/agent/test_auxiliary_client.py+++ b/tests/agent/test_auxiliary_client.py@@ -5073,7 +5073,7 @@ class TestNoProgressTimeoutTaskConfigGating:CodexAuxiliaryClient path (both the first-output and between-output deadlines derive from``guard.no_progress_timeout``); other tasks keep the 60s default; a non-positive valueis rejected with a warning and falls back to the default."""- import yaml+ import hermes_yaml as yamlfrom agent import auxiliary_client as auxhome = tmp_path / ".hermes"diff --git a/tests/agent/test_auxiliary_unavailable_nous_reason.py b/tests/agent/test_auxiliary_unavailable_nous_reason.pyindex e305441946e..b8bd5a09c9f 100644--- a/tests/agent/test_auxiliary_unavailable_nous_reason.py+++ b/tests/agent/test_auxiliary_unavailable_nous_reason.py@@ -5,7 +5,7 @@ back; the failure must still reach the operator (one WARNING) and the goal-loop"""import logging-import yaml+import hermes_yaml as yamlimport agent.auxiliary_unavailable as unavailablefrom hermes_cli.auth_constants import AuthErrordiff --git a/tests/agent/test_bedrock_context_cache.py b/tests/agent/test_bedrock_context_cache.pyindex 5321f482bd5..94a73a51b98 100644--- a/tests/agent/test_bedrock_context_cache.py+++ b/tests/agent/test_bedrock_context_cache.py@@ -14,7 +14,7 @@ from types import SimpleNamespacefrom unittest.mock import Mockimport pytest-import yaml+import hermes_yaml as yamlfrom agent import bedrock_adapter as bafrom agent import model_metadata as mmdiff --git a/tests/agent/test_missing_provider_credentials_hint.py b/tests/agent/test_missing_provider_credentials_hint.pyindex eb393e2c80d..6c49418e9bb 100644--- a/tests/agent/test_missing_provider_credentials_hint.py+++ b/tests/agent/test_missing_provider_credentials_hint.py@@ -5,7 +5,7 @@ Deriving the env var from the provider id (``f"{id.upper()}_API_KEY"``) inventsreads ``DASHSCOPE_API_KEY``. Both the auxiliary ladder and main-agent init share one helper."""import pytest-import yaml+import hermes_yaml as yamlfrom agent.auxiliary_unavailable import missing_provider_credentials_messagefrom hermes_cli.auth import PROVIDER_REGISTRYdiff --git a/tests/agent/test_warning_presentation.py b/tests/agent/test_warning_presentation.pyindex 664714e59ca..1ce1b3d7bf2 100644--- a/tests/agent/test_warning_presentation.py+++ b/tests/agent/test_warning_presentation.py@@ -16,7 +16,7 @@ class Emitter(StatusOutputMixin):@pytest.mark.parametrize("setting", [None, False, True, "typo", [], {}])def test_warning_policy_at_real_presentation_boundary(tmp_path, monkeypatch, setting):- import yaml+ import hermes_yaml as yamlmonkeypatch.setenv("HERMES_HOME", str(tmp_path))config = {} if setting is None else {"display": {"suppress_warning_notifications": setting}}(tmp_path / "config.yaml").write_text(yaml.safe_dump(config))@@ -84,7 +84,7 @@ def test_direct_print_diagnostics_preserve_content_and_muted_turn_has_no_prints(def test_operator_callbacks_keep_diagnostics_and_logs(tmp_path, monkeypatch, caplog, suppress):import loggingfrom types import SimpleNamespace- import yaml+ import hermes_yaml as yamlmonkeypatch.setenv("HERMES_HOME", str(tmp_path))(tmp_path / "config.yaml").write_text(yaml.safe_dump({} if suppress is None else {"display": {"suppress_warning_notifications": suppress}}))@@ -116,7 +116,7 @@ def test_operator_callbacks_keep_diagnostics_and_logs(tmp_path, monkeypatch, cap@pytest.mark.parametrize("suppress", [None, False, True])def test_entitlement_guidance_is_classified_at_direct_print(tmp_path, monkeypatch, suppress):- import yaml+ import hermes_yaml as yamlfrom agent import conversation_loopmonkeypatch.setenv("HERMES_HOME", str(tmp_path))(tmp_path / "config.yaml").write_text(yaml.safe_dump(@@ -132,7 +132,7 @@ def test_entitlement_guidance_is_classified_at_direct_print(tmp_path, monkeypatc@pytest.mark.parametrize("suppress", [None, False, True])def test_missing_key_banner_is_classified_without_hiding_initialization(tmp_path, monkeypatch, capsys, suppress):from agent import agent_init- import yaml+ import hermes_yaml as yamlmonkeypatch.setenv("HERMES_HOME", str(tmp_path))(tmp_path / "config.yaml").write_text(yaml.safe_dump({} if suppress is None else {"display": {"suppress_warning_notifications": suppress}}))diff --git a/tests/conftest.py b/tests/conftest.pyindex 106cc70bb33..640ab2856af 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -317,6 +317,10 @@ _HERMES_BEHAVIORAL_VARS = frozenset({"HERMES_TUI_PROVIDER","HERMES_MANAGED","HERMES_MANAGED_DIR",+ # A Nix-wrapped `hermes` on the developer's host exports the store's read-only plugins+ # tree; tests must discover the checkout's plugins/ (get_bundled_plugins_dir), not a+ # different release's.+ "HERMES_BUNDLED_PLUGINS","HERMES_DEV","HERMES_CONTAINER","HERMES_EPHEMERAL_SYSTEM_PROMPT",diff --git a/tests/gateway/test_adapter_connect_classification.py b/tests/gateway/test_adapter_connect_classification.pyindex ae6a5d1b2a3..5e0d35e29ff 100644--- a/tests/gateway/test_adapter_connect_classification.py+++ b/tests/gateway/test_adapter_connect_classification.py@@ -278,7 +278,7 @@ class TestEmailConnectClassification:def _set_attention_after(value) -> None:"""Write ``agent.reconnect_attention_after`` into the test's isolated HERMES_HOME config."""- import yaml+ import hermes_yaml as yamlfrom hermes_constants import get_hermes_home(get_hermes_home() / "config.yaml").write_text(yaml.safe_dump({"agent": {"reconnect_attention_after": value}}), encoding="utf-8")diff --git a/tests/gateway/test_cron_delivery_housekeeping.py b/tests/gateway/test_cron_delivery_housekeeping.pyindex 84b9c81d3a9..25212efc4be 100644--- a/tests/gateway/test_cron_delivery_housekeeping.py+++ b/tests/gateway/test_cron_delivery_housekeeping.py@@ -171,7 +171,7 @@ def test_primary_drain_delivers_credentialless_satellite_queue_row_through_primaimport threadingfrom unittest.mock import patch- import yaml+ import hermes_yaml as yamlfrom cron import delivery_queuefrom gateway.config import Platformdiff --git a/tests/gateway/test_multiplex_process_memo_scope.py b/tests/gateway/test_multiplex_process_memo_scope.pyindex 96a3a91530b..356e5af6354 100644--- a/tests/gateway/test_multiplex_process_memo_scope.py+++ b/tests/gateway/test_multiplex_process_memo_scope.py@@ -8,7 +8,7 @@ from pathlib import Pathfrom types import SimpleNamespaceimport pytest-import yaml+import hermes_yaml as yamlfrom hermes_constants import reset_hermes_home_override, set_hermes_home_overridediff --git a/tests/gateway/test_reconnect_attention_profile_scope.py b/tests/gateway/test_reconnect_attention_profile_scope.pyindex 4cb55a1e919..008e7a9f6ba 100644--- a/tests/gateway/test_reconnect_attention_profile_scope.py+++ b/tests/gateway/test_reconnect_attention_profile_scope.py@@ -8,7 +8,7 @@ import asyncioimport timeimport pytest-import yaml+import hermes_yaml as yamlimport gateway.run as gateway_runfrom gateway.config import Platformdiff --git a/tests/gateway/test_session_stall_watchdog.py b/tests/gateway/test_session_stall_watchdog.pyindex 4b512b1a7fa..64e909e7706 100644--- a/tests/gateway/test_session_stall_watchdog.py+++ b/tests/gateway/test_session_stall_watchdog.py@@ -535,7 +535,7 @@ async def test_check_session_stalls_bounds_wedged_send(monkeypatch):@pytest.mark.asyncio@pytest.mark.parametrize("setting", [None, False, True])async def test_stall_policy_owner_latch_and_source_log_conservation(tmp_path, monkeypatch, caplog, setting):- import yaml+ import hermes_yaml as yamlfrom gateway.profile_routing import ProfileRouteRejectedowner, launch = tmp_path / "owner", tmp_path / "launch"owner.mkdir(); launch.mkdir()diff --git a/tests/hermes_cli/test_backup_import_deleted_holder.py b/tests/hermes_cli/test_backup_import_deleted_holder.pyindex 2a3e3eb6408..5c85fbc63a9 100644--- a/tests/hermes_cli/test_backup_import_deleted_holder.py+++ b/tests/hermes_cli/test_backup_import_deleted_holder.py@@ -17,7 +17,7 @@ import zipfileimport pytest-from hermes_cli import backup as backup_mod+from hermes_cli import backup_restore as backup_modpytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="/proc holder scan is Linux-only"diff --git a/tests/hermes_cli/test_config_migration_45_connections.py b/tests/hermes_cli/test_config_migration_45_connections.pyindex 273e11eddae..bc2dc468f3f 100644--- a/tests/hermes_cli/test_config_migration_45_connections.py+++ b/tests/hermes_cli/test_config_migration_45_connections.py@@ -11,7 +11,7 @@ import osfrom unittest.mock import patchimport pytest-import yaml+import hermes_yaml as yamlclass TestConnectionsToolsetMigration:diff --git a/tests/hermes_cli/test_config_migration_nested_guards.py b/tests/hermes_cli/test_config_migration_nested_guards.pyindex ac52aaff06c..9b2466af5b1 100644--- a/tests/hermes_cli/test_config_migration_nested_guards.py+++ b/tests/hermes_cli/test_config_migration_nested_guards.py@@ -11,7 +11,7 @@ import osfrom unittest.mock import patchimport pytest-import yaml+import hermes_yaml as yamldef _write_config(tmp_path, config):diff --git a/tests/hermes_cli/test_doctor.py b/tests/hermes_cli/test_doctor.pyindex f75fbc8eeeb..747e8a91761 100644--- a/tests/hermes_cli/test_doctor.py+++ b/tests/hermes_cli/test_doctor.py@@ -1948,7 +1948,7 @@ def test_docker_daemon_probe_uses_version_not_info(monkeypatch):def test_doctor_reports_auxiliary_blocks_that_do_not_resolve(tmp_path, monkeypatch):"""A routed auxiliary.<task> block that the runtime resolver rejects is a doctor finding, not asilent fall-back to the main model (#116055); a resolvable one is not flagged."""- import yaml+ import hermes_yaml as yamlfrom hermes_cli import doctor_configmonkeypatch.setenv("OPENAI_API_KEY", "sk-test")diff --git a/tests/hermes_cli/test_enable_no_capabilities.py b/tests/hermes_cli/test_enable_no_capabilities.pyindex f536aae3c42..7aa06d5cd8c 100644--- a/tests/hermes_cli/test_enable_no_capabilities.py+++ b/tests/hermes_cli/test_enable_no_capabilities.py@@ -2,7 +2,7 @@from unittest.mock import MagicMockimport pytest-import yaml+import hermes_yaml as yaml@pytest.mark.parametrize(diff --git a/tests/hermes_cli/test_local_residency_admission.py b/tests/hermes_cli/test_local_residency_admission.pyindex 2d5654aaa4d..dcf5ffc68cf 100644--- a/tests/hermes_cli/test_local_residency_admission.py+++ b/tests/hermes_cli/test_local_residency_admission.py@@ -85,11 +85,8 @@ def test_boot_hands_the_router_the_derived_cap(tmp_path, monkeypatch, configuredmonkeypatch.setattr(bs, "_SUPERVISOR", None)monkeypatch.setattr(bs, "_generate_presets", lambda mdir, preset_path: None)monkeypatch.setattr(bs, "_detect_gpu_vendor", lambda: None)- monkeypatch.setattr(binaries, "installed_tags", lambda: ["build-1"])- monkeypatch.setattr(binaries, "default_tag", lambda: "build-1")- monkeypatch.setattr(binaries, "select_backend", lambda vendor: "cpu")- monkeypatch.setattr(binaries, "ensure_runtime_installed",- lambda tag, backend: tmp_path / "install")+ monkeypatch.setattr(binaries, "installed_engine",+ lambda backend="auto", **k: binaries.Engine("cpu", "build-1", tmp_path / "install" / "llama-server"))monkeypatch.setattr(endpoint, "_state_endpoint", lambda: None)captured: dict = {}diff --git a/tests/hermes_cli/test_local_runtime_child_env.py b/tests/hermes_cli/test_local_runtime_child_env.pyindex 3e52488fc33..2a8eda188e4 100644--- a/tests/hermes_cli/test_local_runtime_child_env.py+++ b/tests/hermes_cli/test_local_runtime_child_env.py@@ -23,13 +23,12 @@ def test_supervisor_spawns_llama_server_without_credentials_but_keeps_runtime_enmonkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")monkeypatch.setenv("OMP_NUM_THREADS", "4")monkeypatch.setattr(supervisor, "runtimes_root", lambda: tmp_path / "runtime")- monkeypatch.setattr(supervisor, "server_binary", lambda _: tmp_path / "engine" / "llama-server")monkeypatch.setattr(supervisor, "_direct_io_args", lambda exe: [])spawns = []monkeypatch.setattr(supervisor, "spawn_server", lambda argv, **kwargs: (spawns.append(kwargs) or SimpleNamespace(pid=123, poll=lambda: 0), None,))- sup = supervisor.LlamaServerSupervisor(tmp_path / "engine", tmp_path / "models", port=19002)+ sup = supervisor.LlamaServerSupervisor(tmp_path / "engine" / "llama-server", tmp_path / "models", port=19002)monkeypatch.setattr(sup, "_write_state", lambda: None)try:sup._spawn()diff --git a/tests/hermes_cli/test_moa_set_models_preserves_extra_keys.py b/tests/hermes_cli/test_moa_set_models_preserves_extra_keys.pyindex 4c7aa6dd44d..70af2f77082 100644--- a/tests/hermes_cli/test_moa_set_models_preserves_extra_keys.py+++ b/tests/hermes_cli/test_moa_set_models_preserves_extra_keys.py@@ -91,7 +91,7 @@ def test_moa_save_writes_only_the_moa_section(tmp_path, monkeypatch):out-of-band (or was simply stale) rewrote ``fallback_providers`` too. Real config pipeline,temp HERMES_HOME."""- import yaml+ import hermes_yaml as yamlfrom hermes_cli.config import get_config_path, load_config, read_raw_confighome = tmp_path / ".hermes"diff --git a/tests/hermes_cli/test_plugin_install_manifest_version.py b/tests/hermes_cli/test_plugin_install_manifest_version.pyindex 938762f406c..252fe830c4d 100644--- a/tests/hermes_cli/test_plugin_install_manifest_version.py+++ b/tests/hermes_cli/test_plugin_install_manifest_version.py@@ -12,7 +12,7 @@ import subprocessfrom pathlib import Pathimport pytest-import yaml+import hermes_yaml as yamlfrom hermes_cli.plugins import SUPPORTED_MANIFEST_VERSIONdiff --git a/tests/hermes_cli/test_pool_missing_endpoint.py b/tests/hermes_cli/test_pool_missing_endpoint.pyindex 0b876028fd1..b1700524e1a 100644--- a/tests/hermes_cli/test_pool_missing_endpoint.py+++ b/tests/hermes_cli/test_pool_missing_endpoint.py@@ -1,6 +1,6 @@"""Endpoint-less manual credentials resolve through the public runtime ladder."""import pytest-import yaml+import hermes_yaml as yamlfrom hermes_cli.auth import PROVIDER_REGISTRY, write_credential_poolfrom hermes_cli.runtime_provider import resolve_runtime_providerdiff --git a/tests/hermes_cli/test_provider_profile_identity.py b/tests/hermes_cli/test_provider_profile_identity.pyindex 8df8bc5262b..8e41c436847 100644--- a/tests/hermes_cli/test_provider_profile_identity.py+++ b/tests/hermes_cli/test_provider_profile_identity.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport sysimport pytest-import yaml+import hermes_yaml as yamlfrom hermes_cli import auth as auth_modfrom hermes_cli.model_switch import switch_modeldiff --git a/tests/hermes_cli/test_set_config_value.py b/tests/hermes_cli/test_set_config_value.pyindex e334daa1761..9ed179200af 100644--- a/tests/hermes_cli/test_set_config_value.py+++ b/tests/hermes_cli/test_set_config_value.py@@ -6,7 +6,7 @@ import osfrom unittest.mock import patchimport pytest-import yaml+import hermes_yaml as yamlfrom hermes_cli.config import (config_command,diff --git a/tests/hermes_cli/test_update_apply_shallow_count.py b/tests/hermes_cli/test_update_apply_shallow_count.pyindex 16659ea3cdc..5937df7acf1 100644--- a/tests/hermes_cli/test_update_apply_shallow_count.py+++ b/tests/hermes_cli/test_update_apply_shallow_count.py@@ -22,6 +22,7 @@ def test_apply_plan_counts_supplied_git_results(monkeypatch, tmp_path, shallow,monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)responses = {("status", "--porcelain"): "",+ ("status", "--porcelain", "-z"): "",("rev-list", "HEAD..origin/main", "--count"): str(raw_count),("rev-parse", "--is-shallow-repository"): "true" if shallow else "false",("rev-parse", "HEAD"): SHA_A,diff --git a/tests/hermes_cli/test_update_import_guard.py b/tests/hermes_cli/test_update_import_guard.pyindex 29bd5f7e0c9..b69756062b0 100644--- a/tests/hermes_cli/test_update_import_guard.py+++ b/tests/hermes_cli/test_update_import_guard.py@@ -304,9 +304,6 @@ def test_import_guard_rejects_module_satisfied_only_by_inherited_pythonpath(monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",))- monkeypatch.setattr(- update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",)- )monkeypatch.setenv("PYTHONPATH", str(stale))ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)@@ -327,9 +324,6 @@ def test_import_guard_accepts_candidate_with_foreign_pythonpath(monkeypatch, tmpmonkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",))- monkeypatch.setattr(- update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",)- )monkeypatch.setenv("PYTHONPATH", str(stale))assert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)diff --git a/tests/hermes_cli/test_vault_sources_shape.py b/tests/hermes_cli/test_vault_sources_shape.pyindex 9727a9b01f8..fadcf45faed 100644--- a/tests/hermes_cli/test_vault_sources_shape.py+++ b/tests/hermes_cli/test_vault_sources_shape.py@@ -5,7 +5,7 @@ coerced to a dict before the opt-out is written."""from types import SimpleNamespace-import yaml+import hermes_yaml as yamlfrom agent.vault_store import VaultStorefrom hermes_cli.vault import _cmd_sources, vault_commanddiff --git a/tests/hermes_cli/test_warning_callback_conservation.py b/tests/hermes_cli/test_warning_callback_conservation.pyindex fb6d7a7c841..eb168cd64c5 100644--- a/tests/hermes_cli/test_warning_callback_conservation.py+++ b/tests/hermes_cli/test_warning_callback_conservation.py@@ -2,7 +2,7 @@from types import SimpleNamespaceimport pytest-import yaml+import hermes_yaml as yamlfrom agent.status_output import StatusOutputMixinfrom hermes_cli.cli_stream_mixin import CLIStreamMixindiff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 6bab31da1f1..78d263af97d 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -946,6 +946,9 @@ class TestWebServerEndpoints:pm, "sync_venv",lambda extras=None, explicit=False: installed.append(tuple(extras or ())),)+ # The dashboard process is not the environment the sync just built; activation is a+ # boot decision, so the row must tell the user to restart.+ monkeypatch.setattr("pm.environments.running_from_selected_environment", lambda root: False)# Any direct pip/uv subprocess from the memory-provider pip path is# a regression; external-dep checks may still run subprocess, so onlydiff --git a/tests/hermes_cli/test_windows_update_restart_reconciliation.py b/tests/hermes_cli/test_windows_update_restart_reconciliation.pyindex e6c63c55d53..edfa08ac06c 100644--- a/tests/hermes_cli/test_windows_update_restart_reconciliation.py+++ b/tests/hermes_cli/test_windows_update_restart_reconciliation.py@@ -208,48 +208,6 @@ def test_merge_helper_reads_token_keys_into_restart_outcome(monkeypatch):# #115563: symmetric resume-failure handling + atexit double-fire# ----------------------------------------------------------------------------def test_already_up_to_date_path_demotes_on_windows_resume_failure(monkeypatch):- """The pull path treats a Windows resume failure as a warning (outcome.incomplete = True,- update continues); the 'Already up to date' path called _resume_windows_gateways_after_update- bare, so the identical RuntimeError killed the run instead (#115563). It must now route- through the same _resume_windows_gateways_and_merge_outcome contract and demote- current_checkout_complete, landing on the same 'partial' + exit(1) path a failed repair- already uses — not an unhandled exception."""- from hermes_cli import update_cmd-- class _Plan:- auto_stash_ref = None- parked_branch_switched = False- switch_block_reason = ""- upstream_checked = True-- monkeypatch.setattr(update_cmd, "_invalidate_update_cache", lambda: None)- monkeypatch.setattr(update_cmd, "_repair_current_checkout", lambda **_kw: True)- monkeypatch.setattr(update_cmd, "_apply_pending_fleet_restart_catchup", lambda **_kw: None)-- finalized = []- monkeypatch.setattr(update_cmd, "_finalize_receipt", lambda status, *_a: finalized.append(status))-- def _fail_resume(_token):- raise RuntimeError("Windows gateway relaunch after update was not verified alive")-- monkeypatch.setattr(hm, "_resume_windows_gateways_after_update", _fail_resume)-- with patch("builtins.print"):- with pytest.raises(SystemExit) as exc_info:- update_cmd._finish_already_up_to_date(- git_cmd="git", branch="main", current_branch="main", _plan=_Plan(),- assume_yes=True, gateway_mode=False, gw_input_fn=None,- pre_update_snapshot_id=None, had_desktop_app_before_update=False,- active_lazy_features=None, active_tool_dependencies=None,- _windows_gateway_resume={"resume_needed": True},- )-- # Demoted to the existing partial-repair contract, not an unhandled RuntimeError.- assert exc_info.value.code == 1- assert finalized == ["partial"]--def test_resume_unregisters_its_own_atexit_fallback_before_running(monkeypatch):"""Every foreground call site registers this same function via atexit as a dead-processsafety net. Once execution actually reaches here it must disarm that fallback immediately@@ -271,4 +229,3 @@ def test_resume_unregisters_its_own_atexit_fallback_before_running(monkeypatch):assert calls == [update_cmd_windows._resume_windows_gateways_after_update]assert token["resume_needed"] is False-diff --git a/tests/home_io_guard.py b/tests/home_io_guard.pyindex 1a03190b73f..830c581021f 100644--- a/tests/home_io_guard.py+++ b/tests/home_io_guard.py@@ -13,6 +13,11 @@ import threading_INTERPRETER_PREFIXES = tuple({Path(p).resolve() for p in (sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix)+} | {+ # A PM-activated developer shell runs sys.prefix's python against a dependency generation+ # whose site-packages sits under the (real) Hermes home; third-party imports from it are the+ # interpreter's installation, not Hermes state.+ Path(p).resolve() for p in sys.path if p and Path(p).name in ("site-packages", "dist-packages")})diff --git a/tests/plugins/image_gen/test_openai_provider.py b/tests/plugins/image_gen/test_openai_provider.pyindex c479f0d642c..6170d54d466 100644--- a/tests/plugins/image_gen/test_openai_provider.py+++ b/tests/plugins/image_gen/test_openai_provider.py@@ -112,7 +112,7 @@ class TestEndpointConfig:#13798); the project header is blanked (#60748); custom endpoints bypass system proxies (#64888)."""def test_config_base_url_and_key_env_reach_client_and_availability(self, monkeypatch, tmp_path):- import yaml+ import hermes_yaml as yamlmonkeypatch.delenv("OPENAI_API_KEY", raising=False)monkeypatch.delenv("OPENAI_BASE_URL", raising=False)monkeypatch.setenv("IMAGE_GATEWAY_TOKEN", "gateway-token")@@ -134,7 +134,7 @@ class TestEndpointConfig:"""A non-catalog ``image_gen.openai.model`` reaches the gateway verbatim as ``model`` and no``quality`` is sent (gateways reject unknown enum values); a stale top-level ``image_gen.model``from another provider never passes through (#97928)."""- import yaml+ import hermes_yaml as yamlmonkeypatch.setenv("OPENAI_API_KEY", "k")monkeypatch.delenv("OPENAI_IMAGE_MODEL", raising=False)(tmp_path / "config.yaml").write_text(yaml.safe_dump({"image_gen": {@@ -152,7 +152,7 @@ class TestEndpointConfig:def test_named_custom_endpoint_supplies_base_url_and_key(self, monkeypatch, tmp_path):"""``image_gen.openai.provider: <name>`` inherits that ``providers:`` entry's base_url andkey_env when ``base_url``/``key_env`` are unset; explicit values still win (#83080)."""- import yaml+ import hermes_yaml as yamlfor key in ("OPENAI_API_KEY", "OPENAI_BASE_URL"):monkeypatch.delenv(key, raising=False)monkeypatch.setenv("MY_GW_KEY", "gw-token")@@ -175,7 +175,7 @@ class TestEndpointConfig:``generate()`` must hand ``openai.OpenAI`` a client with no ``HTTPProxy`` mount, while a plain``httpx.Client()`` under the same conditions (control) does pick the proxy up (#64888)."""import httpx- import yaml+ import hermes_yaml as yamlfor key in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy","NO_PROXY", "no_proxy"):monkeypatch.delenv(key, raising=False)diff --git a/tests/plugins/memory/test_holographic_save_config.py b/tests/plugins/memory/test_holographic_save_config.pyindex cf6e4735518..b00a3a31e5d 100644--- a/tests/plugins/memory/test_holographic_save_config.py+++ b/tests/plugins/memory/test_holographic_save_config.py@@ -6,7 +6,7 @@ sections survive a provider save, and a managed install refuses the write."""from __future__ import annotations-import yaml+import hermes_yaml as yamlfrom plugins.memory.holographic import HolographicMemoryProviderdiff --git a/tests/pm/test_windows_build_deps.py b/tests/pm/test_windows_build_deps.pyindex 9e92f4d4a10..1f31dabbf1f 100644--- a/tests/pm/test_windows_build_deps.py+++ b/tests/pm/test_windows_build_deps.py@@ -69,6 +69,13 @@ function Initialize-HermesArm64BuildTools {}''', encoding="utf-8")env = dict(os.environ)+ # The runner job env may already carry the toolchain variables the fixture sets (a prior+ # workflow step exported them); the delta filter then rightly skips them. This test is about+ # the protocol, so start from a parent that does not have them.+ for name in ("INCLUDE", "LIB", "WINDOWSSDKDIR", "OPENSSL_DIR", "OPENSSL_STATIC",+ "CC_AARCH64_PC_WINDOWS_MSVC", "GITHUB_FIXTURE", "RUNNER_FIXTURE", "NODE_OPTIONS"):+ for key in [k for k in env if k.upper() == name]:+ del env[key]env.update(CARGO_HOME=str(tmp_path / "caller cargo"), RUSTUP_HOME=str(tmp_path / "caller rustup"),RUSTUP_TOOLCHAIN="caller-toolchain", UNCHANGED_BUILD_SENTINEL="inherited")state = tmp_path / "state with spaces"diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py b/tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.pyindex 62467333e96..71f454e8253 100644--- a/tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py+++ b/tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py@@ -56,7 +56,7 @@ def test_gateway_flag_is_conditional_not_inline() -> None:assert re.search(r"if \(\$NoGateway\)\s*\{\s*\n\s*\$gatewayArg = @\(\)", source), ("-NoGateway must empty $gatewayArg before the update argv is assembled.")- assert "$gatewayArg + @(\"--force\"" in source, (+ assert "+ @('update', '--yes') + $gatewayArg +" in source, ("The update argv must be assembled from $gatewayArg so -NoGateway ""actually removes --gateway from the invocation.")diff --git a/tests/skills/test_scrollcraft_skill.py b/tests/skills/test_scrollcraft_skill.pyindex 6a88660ba55..b42d2403c61 100644--- a/tests/skills/test_scrollcraft_skill.py+++ b/tests/skills/test_scrollcraft_skill.py@@ -3,7 +3,7 @@import refrom pathlib import Path-import yaml+import hermes_yaml as yamlSKILL_DIR = Path(__file__).resolve().parents[2] / "optional-skills/web-development/scrollcraft"SKILL_MD = SKILL_DIR / "SKILL.md"diff --git a/tests/test_managed_runtime_resolution.py b/tests/test_managed_runtime_resolution.pyindex 9aa009fa9da..2b88650a773 100644--- a/tests/test_managed_runtime_resolution.py+++ b/tests/test_managed_runtime_resolution.py@@ -65,7 +65,7 @@ _ALLOWED: dict[tuple[str, str], str] = {"can only run what is on that subshell's PATH, which local.py populates ""with the managed dirs — so PATH is the correct question to ask here."),- ("hermes_cli/gateway_service_unit.py", "node"): (+ ("hermes_cli/gateway.py", "node"): ("Fallback rung of _append_node_dir_for_service(), after the managed ""dirs from iter_hermes_node_dirs() are already appended."),diff --git a/tests/test_node_bootstrap_bash.py b/tests/test_node_bootstrap_bash.pydeleted file mode 100644index 737bde53b7d..00000000000--- a/tests/test_node_bootstrap_bash.py+++ /dev/null@@ -1,42 +0,0 @@-"""The node-bootstrap spawns must use ``_find_bash``, never a bare ``"bash"`` argv: on Windows-``CreateProcess`` resolves the bare name to System32's WSL launcher (#116818)."""--from __future__ import annotations--import subprocess--import pytest--import hermes_constants-from hermes_cli import main_tui_launch-from tools.environments import local---def _drive_node_bootstrap():- return hermes_constants._run_node_bootstrap("ensure_node", timeout=5)---def _drive_tui_node():- return main_tui_launch._ensure_tui_node()--[email protected]("drive", [_drive_node_bootstrap, _drive_tui_node], ids=["node_bootstrap", "tui_node"])-def test_node_bootstrap_spawns_resolved_bash(monkeypatch, tmp_path, drive):- fixture_bash = str(tmp_path / "git" / "bin" / "bash.exe")- monkeypatch.setattr(local, "_find_bash", lambda: fixture_bash)- monkeypatch.setattr(main_tui_launch.shutil, "which", lambda name: None) # force the bootstrap path- monkeypatch.delenv("HERMES_SKIP_NODE_BOOTSTRAP", raising=False)- monkeypatch.setattr(hermes_constants, "_NODE_BOOTSTRAP_SCRIPT", tmp_path / "node-bootstrap.sh")- (tmp_path / "node-bootstrap.sh").write_text("", encoding="utf-8")- argvs = []-- def fake_run(argv, **kwargs):- argvs.append(list(argv))- return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")-- monkeypatch.setattr(subprocess, "run", fake_run)- monkeypatch.setattr(main_tui_launch.subprocess, "run", fake_run)-- drive()-- assert [argv[0] for argv in argvs] == [fixture_bash]diff --git a/tests/tools/test_env_passthrough.py b/tests/tools/test_env_passthrough.pyindex 9e202fd2d0d..7602a4fc09f 100644--- a/tests/tools/test_env_passthrough.py+++ b/tests/tools/test_env_passthrough.py@@ -380,7 +380,7 @@ class TestTerminalIntegration:case variants of provider credentials on the same filter."""config = {"terminal": {"env_passthrough": ["openai_api_key", "MY_OWN_KEY"]}}config_path = tmp_path / "config.yaml"- config_path.write_text(yaml.dump(config), encoding="utf-8")+ config_path.write_text(yaml.safe_dump(config), encoding="utf-8")monkeypatch.setenv("HERMES_HOME", str(tmp_path))_ep_mod._config_passthrough.clear()diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.pyindex 4047b9df8dd..e73cb644b9c 100644--- a/tests/tools/test_local_env_blocklist.py+++ b/tests/tools/test_local_env_blocklist.py@@ -13,6 +13,21 @@ import pytestfrom tests.tools._child_env_fixtures import child_env, observe_child, observe_terminal # noqa: F401from tools.environments import localfrom tools.environments import local_pythonpath as pp+from tools.environments.local_env_policy import _HERMES_PROVIDER_ENV_BLOCKLIST+++def _running_venv_site_packages() -> Path:+ """Independently construct the host-native venv site-packages path."""+ if sys.platform == "win32":+ return Path(sys.prefix) / "Lib" / "site-packages"+ return Path(sys.prefix) / "lib" / f"python{sys.version_info[0]}.{sys.version_info[1]}" / "site-packages"+++def _physical_repo_root(tmp_path: Path) -> Path:+ """Create the physical repo checkout directory for junction tests."""+ physical_root = tmp_path / "physical-home" / "hermes-agent"+ physical_root.mkdir(parents=True)+ return physical_root# Expectations come from independent provider/config declarations and literaldiff --git a/tests/tools/test_multiplex_tool_cache_scope.py b/tests/tools/test_multiplex_tool_cache_scope.pyindex a2d086db01f..8ad94b4fc87 100644--- a/tests/tools/test_multiplex_tool_cache_scope.py+++ b/tests/tools/test_multiplex_tool_cache_scope.py@@ -9,7 +9,7 @@ import threadingfrom pathlib import Pathimport pytest-import yaml+import hermes_yaml as yamlfrom agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scopefrom hermes_constants import reset_hermes_home_override, set_hermes_home_overridediff --git a/tests/tools/test_multiplex_turn_parity.py b/tests/tools/test_multiplex_turn_parity.pyindex dca02ce74a2..f10fec067b0 100644--- a/tests/tools/test_multiplex_turn_parity.py+++ b/tests/tools/test_multiplex_turn_parity.py@@ -12,7 +12,7 @@ from __future__ import annotationsfrom pathlib import Pathimport pytest-import yaml+import hermes_yaml as yamlfrom hermes_constants import reset_hermes_home_override, set_hermes_home_overridediff --git a/tests/tui_gateway/test_config_set_session_profile_scope.py b/tests/tui_gateway/test_config_set_session_profile_scope.pyindex 67c7a213e4e..e26e5995c2c 100644--- a/tests/tui_gateway/test_config_set_session_profile_scope.py+++ b/tests/tui_gateway/test_config_set_session_profile_scope.py@@ -11,7 +11,7 @@ from pathlib import Pathfrom unittest.mock import patchimport pytest-import yaml+import hermes_yaml as yamlimport tui_gateway.server as serverdiff --git a/tests/tui_gateway/test_foreground_notification_snapshot.py b/tests/tui_gateway/test_foreground_notification_snapshot.pyindex 047fcd88a25..21e64026b78 100644--- a/tests/tui_gateway/test_foreground_notification_snapshot.py+++ b/tests/tui_gateway/test_foreground_notification_snapshot.py@@ -3,7 +3,7 @@ import threadingfrom types import SimpleNamespaceimport pytest-import yaml+import hermes_yaml as yamlfrom agent.status_output import StatusOutputMixinfrom hermes_cli.cli_stream_mixin import CLIStreamMixinfrom tui_gateway import serverdiff --git a/tests/tui_gateway/test_warning_callback_conservation.py b/tests/tui_gateway/test_warning_callback_conservation.pyindex 79b1a80932e..1804e9f9a54 100644--- a/tests/tui_gateway/test_warning_callback_conservation.py+++ b/tests/tui_gateway/test_warning_callback_conservation.py@@ -4,7 +4,7 @@ import queuefrom types import SimpleNamespaceimport pytest-import yaml+import hermes_yaml as yamlfrom agent.status_output import StatusOutputMixinfrom tui_gateway import serverdiff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex d8e8bbdb8e8..6fa9a516554 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -35,6 +35,14 @@ _BROWSER_PASSTHROUGH_KEYS: tuple[str, ...] = ()+def warm_agent_browser_npx_cache(timeout: float = 60.0) -> bool:+ """Frozen old-updater surface (tests/compat/old_updater_surface.json): a pre-PM ``hermes update``+ still running mid-swap imports this from the NEW tree. Nothing is warmed — PM owns the browser+ runtime — and the permanent definition must live here, not behind the revert-scheduled compat+ pointer."""+ return False++def _build_browser_env() -> dict:"""Credential-scrubbed env for an agent-browser subprocess (deferred import: testharnesses stub the ``tools`` package). The passthrough keys are re-added from the active