The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cli): delegate Python setup and sync to PM
ethernet9aac9f9fe8b1
diff --git a/hermes_cli/dingtalk_auth.py b/hermes_cli/dingtalk_auth.pyindex 9874b0be125..03308f8a579 100644--- a/hermes_cli/dingtalk_auth.py+++ b/hermes_cli/dingtalk_auth.py@@ -100,16 +100,15 @@ def wait_for_registration_success(def _ensure_qrcode_installed() -> bool:- """Try to import qrcode; if missing, auto-install it via pip/uv."""+ """Enable DingTalk dependencies; only render QR codes importable in this process."""with contextlib.suppress(ImportError):import qrcode # noqa: F401return True- import subprocess- from hermes_cli.tools_config import _pip_install- with contextlib.suppress(subprocess.SubprocessError, ImportError, OSError):- if _pip_install(["-q", "qrcode"], timeout=120).returncode == 0:- import qrcode # noqa: F401,F811- return True+ import pm+ with contextlib.suppress(pm.InstallError, OSError, ValueError):+ pm.sync_venv(["dingtalk"], explicit=True)+ # PM selects a new generation for the next launch, never this process.+ # The authorization link works without qrcode, so no restart is required here.return False@@ -146,7 +145,7 @@ def dingtalk_qr_auth() -> Optional[Tuple[str, str]]:return Noneurl = reg["verification_uri_complete"]if not _ensure_qrcode_installed():- print_warning(" qrcode library install failed, will show link only.")+ print_warning(" QR rendering is unavailable in this process; using the authorization link.")print()print_info(" Please scan the QR code below with DingTalk to authorize:")print()diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex b7fb177f0fa..74aa6cf3c14 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -2601,9 +2601,10 @@ def get_python_path() -> str:from hermes_constants import venv_python_pathexcept ImportError:# Update-boundary: a gateway restarted mid-update can hold a stale hermes_constants- # without this symbol; reload through the runtime repair owner.- from hermes_cli.runtime_repair import _reload_hermes_constants- venv_python_path = _reload_hermes_constants().venv_python_path+ # without this symbol; reload its definitions from the updated checkout.+ import importlib+ import hermes_constants+ venv_python_path = importlib.reload(hermes_constants).venv_python_pathvenv_python = venv_python_path(venv, windows=is_windows())if venv_python.exists():diff --git a/hermes_cli/macos_tcc_anchor.py b/hermes_cli/macos_tcc_anchor.pyindex 4ffc9f5f5a9..1e4fec635ec 100644--- a/hermes_cli/macos_tcc_anchor.py+++ b/hermes_cli/macos_tcc_anchor.py@@ -24,7 +24,6 @@ import tempfilefrom pathlib import Pathfrom hermes_constants import venv_python_path-from hermes_cli.runtime_repair import _RUNTIME_DIR_NAMEfrom utils import atomic_write_textlogger = logging.getLogger(__name__)@@ -32,14 +31,86 @@ logger = logging.getLogger(__name__)_MARKER_NAME = ".tcc-anchor-source"_STORE_COMMON_MARKERS = ("cpython-", "-macos-")-# The runtime-store marker is derived from runtime_repair so a rename of the-# repair-generation directory cannot silently stop the anchor from matching.-_STORE_ROOT_MARKERS = ("/uv/python/", f"/{_RUNTIME_DIR_NAME}/python/")+# Recognize both historical interpreter locations during upgrades.+_STORE_ROOT_MARKERS = ("/uv/python/", "/.hermes-runtime/python/")+_MACOS_MANAGED_PYTHON_IDENTIFIER = "com.nousresearch.hermes.managed-python"_ALIAS_NAMES = ("python3", f"python3.{sys.version_info.minor}")_STORE_BIN_NAMES = (f"python3.{sys.version_info.minor}", "python3", "python")+def _macos_sign_managed_python(python: Path) -> bool:+ """Give a newly downloaded managed Python a stable macOS code identity.++ python-build-standalone binaries are ad-hoc signed, which leaves macOS+ TCC with a cdhash-only identity that changes whenever Hermes provisions a+ new runtime generation. An identifier-pinned designated requirement+ gives those generations a stable identity even when no Developer ID+ certificate is available locally.++ Signing is deliberately best effort. An unavailable or incompatible ``codesign``+ must not prevent a bootable interpreter from being anchored.+ """+ if platform.system() != "Darwin":+ return False++ codesign = shutil.which("codesign")+ if not codesign:+ logger.info(+ "macOS codesign is unavailable; using the downloaded Python signature"+ )+ return False++ requirement = (+ "=designated => identifier "+ f'"{_MACOS_MANAGED_PYTHON_IDENTIFIER}"'+ )+ try:+ signed = subprocess.run(+ [+ codesign,+ "--force",+ "--deep",+ "--sign",+ "-",+ "--timestamp=none",+ "--identifier",+ _MACOS_MANAGED_PYTHON_IDENTIFIER,+ "--requirements",+ requirement,+ str(python),+ ],+ check=False,+ capture_output=True,+ text=True,+ )+ if signed.returncode != 0:+ logger.warning(+ "could not stably sign managed Python %s: %s",+ python,+ (signed.stderr or signed.stdout or "codesign failed").strip(),+ )+ return False++ verified = subprocess.run(+ [codesign, "--verify", "--deep", "--strict", str(python)],+ check=False,+ capture_output=True,+ text=True,+ )+ if verified.returncode != 0:+ logger.warning(+ "macOS signature verification failed for managed Python %s: %s",+ python,+ (verified.stderr or verified.stdout or "verification failed").strip(),+ )+ return False+ return True+ except Exception as exc:+ logger.warning("could not sign managed Python %s: %s", python, exc)+ return False++class _BootGateFailed(Exception):"""Staged copy refused to boot; the live venv must stay untouched."""@@ -292,8 +363,6 @@ def _install_anchor(venv_dir: Path, source_file: Path) -> None:tmp_path = _stage_copy(venv_bin, ".python-tcc-", source_file)try:try:- from hermes_cli.runtime_repair import _macos_sign_managed_python-_macos_sign_managed_python(tmp_path)except Exception: # pragma: no cover - never block the anchorlogger.debug("anchor copy signing skipped", exc_info=True)diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex a3549c213ea..f1a5dbd0a49 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2029,7 +2029,7 @@ def select_provider_and_model(args=None):_FROZEN_UPDATER_SURFACE: dict[str, tuple[str, ...]] = {"hermes_cli.update_cmd": ("_assess_parked_branch_switch",- "_capture_active_lazy_features", "_capture_active_tool_dependencies",+ "_capture_active_lazy_features","_cold_start_windows_gateway_after_update", "_detect_venv_python_processes", "_discard_stashed_changes","_filter_non_gateway_concurrent_instances", "_fleet_probe_expected_runtimes","_get_origin_url", "_handoff_reapable_backend_pids", "_ledger_manual_serve_holders",@@ -2456,12 +2456,7 @@ def _dashboard_prepare_runtime(args, headless_backend) -> bool:import uvicorn # noqa: F401except ImportError as e:print("Web UI dependencies not installed (need fastapi + uvicorn).")- print(- f"Re-install the package into this interpreter so metadata updates apply:\n"- f" cd {PROJECT_ROOT}\n"- f" {sys.executable} -m pip install -e .\n"- "If `pip` is missing in this venv, use: uv pip install -e ."- )+ print("Run `hermes pm install`, then restart Hermes to activate the dependencies.")print(f"Import error: {e}")sys.exit(1)diff --git a/hermes_cli/runtime_repair.py b/hermes_cli/runtime_repair.pydeleted file mode 100644index c095fd542f7..00000000000--- a/hermes_cli/runtime_repair.py+++ /dev/null@@ -1,1186 +0,0 @@-"""Managed Python runtime repair (checkout venv surgery).--The Python backing a CHECKOUT install is shared by every Hermes profile-because the checkout's ``venv`` is shared. A vulnerable interpreter is-never reinstalled in place: we provision a new immutable Python generation-into the install's runtime dir, build and smoke-test a relocatable sibling-venv, then cut over with same-filesystem renames. The old venv remains-available for synchronous rollback and is parked for cleanup after the-updating process releases it.--Sealed trees never reach this module — their interpreter is a build-artifact (pm's ``sealed()`` payloads ship a staged python and refuse-runtime installs).--uv itself is NOT this module's business: the pinned uv is realized through-``pm`` (``pm/lock.json`` + the pm store), like every other managed tool.-This module was previously ``hermes_cli.managed_uv`` and carried its own-uv acquisition; that half predated the package manager and is retired.-"""--from __future__ import annotations--import importlib-import json-import logging-import os-import platform-import shutil-import subprocess-import sys-import time-import uuid-from dataclasses import dataclass-from pathlib import Path--from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo, probe_sqlite_runtime--logger = logging.getLogger(__name__)--_PROJECT_ROOT = Path(__file__).resolve().parents[1]-_VENV_NAME = "venv"-_ALT_VENV_NAME = ".venv"-_RUNTIME_DIR_NAME = ".hermes-runtime"-_MACOS_MANAGED_PYTHON_IDENTIFIER = "com.nousresearch.hermes.managed-python"-_REPAIR_LOCK_NAME = "runtime-repair.lock"--# ----------------------------------------------------------------------------# Public helpers-# ------------------------------------------------------------------------------def _runtime_dir(project_root: Path) -> Path:- """The checkout-scoped scratch dir for repair artifacts.-- Deliberately NOT the pm store: the pm store is machine-wide and holds- immutable published entries, while generations, candidate venvs, and- the repair lock are private to one checkout and its cutover.- """- return Path(project_root) / _RUNTIME_DIR_NAME---def managed_python_install_dir(project_root: Path | None = None) -> Path:- """Return the checkout-scoped Python store shared by all profiles."""- root = Path(project_root) if project_root is not None else _PROJECT_ROOT- return _runtime_dir(root) / "python"---def managed_python_env(- project_root: Path | None = None,- *,- install_dir: Path | None = None,- base_env: dict[str, str] | None = None,-) -> dict[str, str]:- """Return a sanitized environment for Hermes-private uv Python commands.-- Builds on pm's ``uv_env`` sanitization (which strips every ``UV_*``- override and active-venv leakage — the interpreter-hijack class), then- pins uv's managed-Python behavior to the private install dir.- """- from pm.packages import uv_env-- target = (- Path(install_dir)- if install_dir is not None- else managed_python_install_dir(project_root)- )- env = uv_env(dict(os.environ if base_env is None else base_env))- for key in (- "CONDA_DEFAULT_ENV",- "CONDA_PREFIX",- "PYTHONHOME",- "PYTHONPATH",- ):- env.pop(key, None)- env.update({- "UV_MANAGED_PYTHON": "1",- "UV_NO_CONFIG": "1",- "UV_PYTHON_INSTALL_BIN": "0",- "UV_PYTHON_INSTALL_DIR": str(target),- "UV_PYTHON_INSTALL_REGISTRY": "0",- })- return env---@dataclass(frozen=True)-class RuntimeRepairResult:- """Outcome of a managed-runtime repair attempt."""-- status: str- detail: str = ""- sqlite_before: str = ""- sqlite_after: str = ""- backup_venv: Path | None = None-- @property- def repaired(self) -> bool:- return self.status == "repaired"---@dataclass(frozen=True)-class _RepairLock:- path: Path- fd: int---def _report_runtime_repair_failure(repair: RuntimeRepairResult) -> None:- if repair.backup_venv is None:- print(- " ℹ Managed Python runtime was not replaced; "- f"the existing venv is unchanged ({repair.detail})."- )- print(- " Sessions stay protected meanwhile: Hermes keeps databases "- "out of WAL mode on this SQLite build. The next `hermes update` "- "will retry."- )- return- print(f" ✗ Managed Python runtime cutover needs manual recovery: {repair.detail}")- print(f" Previous venv: {repair.backup_venv}")---def _macos_sign_managed_python(python: Path) -> bool:- """Give a newly downloaded managed Python a stable macOS code identity.-- python-build-standalone binaries are ad-hoc signed, which leaves macOS- TCC with a cdhash-only identity that changes whenever Hermes provisions a- new runtime generation. An identifier-pinned designated requirement- gives those generations a stable identity even when no Developer ID- certificate is available locally.-- Signing is deliberately best effort. Runtime repair exists to remove a- security vulnerability, so an unavailable or incompatible ``codesign``- must not prevent the fixed interpreter from being installed.- """- if platform.system() != "Darwin":- return False-- codesign = shutil.which("codesign")- if not codesign:- logger.info(- "macOS codesign is unavailable; using the downloaded Python signature"- )- return False-- requirement = (- "=designated => identifier "- f'"{_MACOS_MANAGED_PYTHON_IDENTIFIER}"'- )- try:- signed = subprocess.run(- [- codesign,- "--force",- "--deep",- "--sign",- "-",- "--timestamp=none",- "--identifier",- _MACOS_MANAGED_PYTHON_IDENTIFIER,- "--requirements",- requirement,- str(python),- ],- check=False,- capture_output=True,- text=True,- )- if signed.returncode != 0:- logger.warning(- "could not stably sign managed Python %s: %s",- python,- (signed.stderr or signed.stdout or "codesign failed").strip(),- )- return False-- verified = subprocess.run(- [codesign, "--verify", "--deep", "--strict", str(python)],- check=False,- capture_output=True,- text=True,- )- if verified.returncode != 0:- logger.warning(- "macOS signature verification failed for managed Python %s: %s",- python,- (verified.stderr or verified.stdout or "verification failed").strip(),- )- return False- return True- except Exception as exc:- logger.warning("could not sign managed Python %s: %s", python, exc)- return False---# ----------------------------------------------------------------------------# Managed Python runtime repair-# ------------------------------------------------------------------------------def _reload_hermes_constants():- """Re-execute ``hermes_constants`` from disk and return the fresh module.-- ``hermes update`` imports ``hermes_constants`` from the OLD checkout,- ``git pull`` then replaces that file, and this freshly-pulled module runs- its lazy imports against the module object Python already cached in- ``sys.modules`` — the pre-upgrade one. A symbol added by the update is- absent there while the file named in the resulting ``ImportError`` plainly- contains it, which is what made this read as a contradiction:-- cannot import name 'venv_python_path' from 'hermes_constants'- (~/.hermes/hermes-agent/hermes_constants.py)-- Reloading picks up the definitions actually on disk, so callers keep using- the shared helper instead of hand-rolling a second copy of its logic.- """- import hermes_constants-- return importlib.reload(hermes_constants)---def _venv_python(venv_dir: Path) -> Path:- windows = platform.system() == "Windows"- try:- from hermes_constants import venv_python_path- except ImportError:- venv_python_path = _reload_hermes_constants().venv_python_path- return venv_python_path(venv_dir, windows=windows)---def _remove_tree(path: Path, *, boundary: Path) -> None:- """Best-effort removal constrained to a known runtime boundary."""- try:- path.resolve().relative_to(boundary.resolve())- except (OSError, ValueError):- return- shutil.rmtree(path, ignore_errors=True)---def _make_world_traversable(path: Path) -> None:- """Keep root/FHS-managed runtimes executable by non-root callers."""- try:- path.chmod(path.stat().st_mode | 0o755)- except OSError:- pass---def _runtime_request(info: SQLiteRuntimeInfo) -> str:- """Pin the candidate to the current CPython minor line (e.g. ``3.11``).-- Requesting the exact patch can never repair some installs: for a given- patch, python-build-standalone may have no artifact with fixed SQLite at- all (e.g. every published 3.11.14 build links SQLite 3.50.4; the fix- only exists from 3.11.15). A newer patch on the same minor is what- ``uv python install`` would resolve for a fresh install, stays inside- ``requires-python``, and the locked ``uv sync`` + import smoke tests gate- compatibility before any cutover.- """- return ".".join(str(part) for part in info.python_version[:2])---# Cap on how many newer patches we'll try, newest-first, before giving up.-# Bounded because each attempt is a real download+install+probe+delete cycle;-# in practice the fix is almost always in the very next patch or two.-_MAX_PATCH_RETRIES = 5---def _list_available_patches(- uv_bin: str, minor: str, *, cwd: Path, env: dict-) -> list[tuple[int, int, int]]:- """Return known patch versions for ``minor`` (e.g. "3.11"), newest first.-- Queries ``uv python list --all-versions`` rather than trusting the bare- minor-line request to resolve to the newest patch (issue #71250: on some- hosts/uv versions, the resolved candidate for a bare "3.11" request can- be an older cached/indexed patch that still links a vulnerable SQLite,- even when a newer non-vulnerable patch is available). Returns [] on any- failure (network, parse) -- callers fall back to the original bare-minor- request in that case, preserving prior behavior.- """- try:- result = subprocess.run(- [- uv_bin, "python", "list", minor,- "--all-versions", "--only-downloads",- "--output-format", "json", "--no-config",- ],- cwd=cwd,- env=env,- capture_output=True,- text=True,- check=False,- timeout=15,- )- if result.returncode != 0 or not result.stdout.strip():- return []- entries = json.loads(result.stdout)- versions: list[tuple[int, int, int]] = []- for entry in entries:- if not isinstance(entry, dict):- continue- # Only default/cpython builds -- skip pypy/graalpy/freethreaded- # variants, which aren't what this repair path wants.- if entry.get("implementation") not in (None, "cpython"):- continue- if entry.get("variant") not in (None, "default"):- continue- parts = entry.get("version_parts") or {}- try:- versions.append(- (int(parts["major"]), int(parts["minor"]), int(parts["patch"]))- )- except (KeyError, TypeError, ValueError):- continue- # Deduplicate (list --all-versions can repeat a version across- # platforms/arches if filtering above didn't fully narrow it) and- # sort newest-first.- return sorted(set(versions), reverse=True)- except Exception:- return []---def _attempt_install_generation(- uv_bin: str,- request: str,- *,- project_root: Path,- python_root: Path,- current: SQLiteRuntimeInfo,- allow_minor_upgrade: bool = False,- tried_versions: set[tuple[int, int, int]] | None = None,-) -> tuple[Path, Path, SQLiteRuntimeInfo] | None:- """One install+probe attempt for a specific version request (bare minor- like "3.11", or an explicit patch like "3.11.15"). Each attempt gets its- own generation directory so a rejected candidate's files are fully- cleaned up before the next attempt, matching --reinstall semantics.- Returns None (and cleans up) on any failure, including a vulnerable- or off-line candidate.-- When *tried_versions* is given, the probed candidate's version is- recorded in it so callers looping over explicit patches can skip a- version a bare-minor request already resolved to (and rejected) --- retrying it explicitly would spend a full download+install+probe+delete- cycle to reach a certain rejection.- """- token = f"{int(time.time())}-{os.getpid()}-{uuid.uuid4().hex[:8]}"- generation = python_root / f"generation-{token}"- generation.mkdir(parents=True, exist_ok=False)- _make_world_traversable(generation)-- env = managed_python_env(project_root, install_dir=generation)- install = subprocess.run(- [- uv_bin,- "python",- "install",- request,- "--reinstall",- "--no-bin",- "--no-registry",- "--no-config",- ],- cwd=project_root,- env=env,- capture_output=True,- text=True,- check=False,- )- if install.returncode != 0:- logger.warning(- "private Python install failed for %s (rc=%d): %s",- request,- install.returncode,- (install.stderr or install.stdout or "").strip(),- )- _remove_tree(generation, boundary=python_root)- return None-- found = subprocess.run(- [- uv_bin,- "python",- "find",- request,- "--managed-python",- "--no-config",- ],- cwd=project_root,- env=env,- capture_output=True,- text=True,- check=False,- )- if found.returncode != 0 or not found.stdout.strip():- logger.warning(- "private Python lookup failed for %s (rc=%d): %s",- request,- found.returncode,- (found.stderr or "").strip(),- )- _remove_tree(generation, boundary=python_root)- return None-- python = Path(found.stdout.strip().splitlines()[-1])- try:- python.resolve().relative_to(generation.resolve())- except (OSError, ValueError):- logger.warning("uv resolved Python outside the Hermes generation: %s", python)- _remove_tree(generation, boundary=python_root)- return None-- candidate = probe_sqlite_runtime(python)- if candidate is None:- logger.warning("could not probe candidate Python runtime: %s", python)- _remove_tree(generation, boundary=python_root)- return None- if tried_versions is not None:- tried_versions.add(candidate.python_version[:3])- if allow_minor_upgrade:- # When falling forward to a higher minor line (e.g. 3.11 → 3.12),- # only reject downgrades — allow the minor to differ.- if candidate.python_version < current.python_version:- logger.warning(- "candidate Python downgraded from %s: %s",- ".".join(str(p) for p in current.python_version),- candidate.python_version,- )- _remove_tree(generation, boundary=python_root)- return None- elif candidate.python_version[:2] != current.python_version[:2] or (- candidate.python_version < current.python_version- ):- logger.warning(- "candidate Python drifted off the %s minor line or downgraded: %s",- ".".join(str(p) for p in current.python_version[:2]),- candidate.python_version,- )- _remove_tree(generation, boundary=python_root)- return None- if candidate.wal_reset_vulnerable:- logger.warning(- "candidate Python still links vulnerable SQLite %s (%s)",- candidate.sqlite_version_string,- candidate.sqlite_source_id,- )- _remove_tree(generation, boundary=python_root)- return None- return generation, python, candidate---def _install_safe_python_generation(- uv_bin: str,- *,- project_root: Path,- current: SQLiteRuntimeInfo,-) -> tuple[Path, Path, SQLiteRuntimeInfo] | None:- runtime_root = _runtime_dir(project_root)- python_root = managed_python_install_dir(project_root)- _make_world_traversable(runtime_root)- _make_world_traversable(python_root)-- request = _runtime_request(current)- print(f" → Provisioning a private Python {request} runtime with fixed SQLite...")- tried_versions = {current.python_version[:3]}-- result = _attempt_install_generation(- uv_bin, request, project_root=project_root,- python_root=python_root, current=current,- tried_versions=tried_versions,- )- if result is not None:- return result-- # The bare minor-line request resolved to a still-vulnerable (or- # otherwise rejected) candidate. Rather than giving up immediately,- # query which patches on this minor line uv actually knows about and- # retry with explicit newer versions, newest-first -- this handles the- # case where the default resolution for a bare request picks an older- # cached/indexed patch even though a newer, non-vulnerable one is- # available (issue #71250).- env_for_list = managed_python_env(project_root, install_dir=python_root)- patches = _list_available_patches(- uv_bin, request, cwd=project_root, env=env_for_list- )- attempts = 0- for version_tuple in patches:- if attempts >= _MAX_PATCH_RETRIES:- break- if version_tuple in tried_versions:- continue- # Only NEWER patches can carry the SQLite fix. A patch at or below the- # installed one is either the version we already know is vulnerable or- # an older build that cannot contain a later fix, and the downgrade- # guard in _attempt_install_generation rejects it anyway -- so trying- # it spends a full download+install+probe+delete cycle to reach a- # certain rejection. This matters on a uv whose download catalog is- # stale: in #71250 the newest indexed 3.11 was 3.11.14, exactly the- # installed version, so without this skip the loop burned all five- # retries walking backwards (3.11.13 -> 3.11.9) before failing.- if version_tuple <= current.python_version[:3]:- continue- tried_versions.add(version_tuple)- explicit_request = ".".join(str(p) for p in version_tuple)- print(f" → Retrying with explicit patch {explicit_request}...")- attempts += 1- result = _attempt_install_generation(- uv_bin, explicit_request, project_root=project_root,- python_root=python_root, current=current,- )- if result is not None:- return result-- # All patches on the current minor line are vulnerable or rejected.- # Fall forward to the next supported minor (e.g. 3.14 → 3.15 when the- # ceiling rises) so the user isn't stuck on every `hermes update` with- # no path to a fixed runtime (issue #76106). The requires-python- # constraint (>=3.14,<3.15) and the downstream import smoke-test gate- # compatibility; we only need to stay inside that window.- cur_major, cur_minor = current.python_version[:2]- fb_tried: set[tuple[int, int, int]] = set(tried_versions)- for next_minor in range(cur_minor + 1, 15): # up to 3.14 (<3.15 ceiling)- next_request = f"{cur_major}.{next_minor}"- print(- f" → No fixed {cur_major}.{cur_minor} build available; "- f"trying {next_request} as fallback..."- )- result = _attempt_install_generation(- uv_bin, next_request, project_root=project_root,- python_root=python_root, current=current,- allow_minor_upgrade=True,- tried_versions=fb_tried,- )- if result is not None:- return result- # Also try explicit patches on this minor line, skipping whatever- # version the bare request above already resolved to (retrying it- # explicitly would spend a full download+install+probe+delete cycle- # to reach a certain rejection).- env_for_list = managed_python_env(project_root, install_dir=python_root)- fb_patches = _list_available_patches(- uv_bin, next_request, cwd=project_root, env=env_for_list- )- fb_attempts = 0- for version_tuple in fb_patches:- if fb_attempts >= _MAX_PATCH_RETRIES:- break- if version_tuple in fb_tried:- continue- fb_tried.add(version_tuple)- explicit = ".".join(str(p) for p in version_tuple)- print(f" → Retrying with explicit patch {explicit}...")- fb_attempts += 1- result = _attempt_install_generation(- uv_bin, explicit, project_root=project_root,- python_root=python_root, current=current,- allow_minor_upgrade=True,- )- if result is not None:- return result- return None---def _smoke_candidate_venv(venv_dir: Path) -> tuple[bool, str, SQLiteRuntimeInfo | None]:- """Exercise the candidate interpreter and imports through its real path."""- python = _venv_python(venv_dir)- info = probe_sqlite_runtime(python)- if info is None:- return False, f"could not execute {python}", None- if info.wal_reset_vulnerable:- return (- False,- f"candidate still links vulnerable SQLite {info.sqlite_version_string}",- info,- )-- check = (- "import dotenv, fastapi, openai, prompt_toolkit, pydantic, rich, uvicorn, yaml\n"- "import hermes_state\n"- )- env = dict(os.environ)- for key in (- "CONDA_DEFAULT_ENV",- "CONDA_PREFIX",- "PYTHONHOME",- "PYTHONPATH",- "UV_PROJECT_ENVIRONMENT",- "UV_PYTHON",- "VIRTUAL_ENV",- ):- env.pop(key, None)- try:- result = subprocess.run(- [str(python), "-I", "-c", check],- cwd=venv_dir.parent,- env=env,- capture_output=True,- text=True,- timeout=90,- check=False,- )- except (OSError, subprocess.TimeoutExpired) as exc:- return False, str(exc), info- if result.returncode != 0:- detail = (result.stderr or result.stdout or "core import smoke failed").strip()- last_line = detail.splitlines()[-1] if detail else "core import smoke failed"- return False, last_line, info- return True, "", info---def _stage_candidate_venv(- uv_bin: str,- *,- project_root: Path,- generation: Path,- python: Path,-) -> Path | None:- runtime_root = _runtime_dir(project_root)- token = f"{int(time.time())}-{os.getpid()}-{uuid.uuid4().hex[:8]}"- candidate = runtime_root / f"venv-candidate-{token}"- env = managed_python_env(- project_root,- install_dir=generation,- )- env.update({- "UV_PROJECT_ENVIRONMENT": str(candidate),- "UV_PYTHON": str(python),- "UV_PYTHON_DOWNLOADS": "never",- "VIRTUAL_ENV": str(candidate),- })-- print(" → Building a relocatable replacement environment...")- created = subprocess.run(- [- uv_bin,- "venv",- str(candidate),- "--python",- str(python),- "--managed-python",- "--no-python-downloads",- "--relocatable",- "--no-config",- ],- cwd=project_root,- env=env,- capture_output=True,- text=True,- check=False,- )- if created.returncode != 0:- logger.warning(- "candidate venv creation failed (rc=%d): %s",- created.returncode,- (created.stderr or created.stdout or "").strip(),- )- _remove_tree(candidate, boundary=runtime_root)- return None-- if not (project_root / "uv.lock").is_file():- logger.warning("candidate dependency sync refused: uv.lock is missing")- _remove_tree(candidate, boundary=runtime_root)- return None- # Locked sync must see project [tool.uv] exclude-newer; --no-config /- # UV_NO_CONFIG drops it and uv 0.12+ refuses --locked.- sync_env = dict(env)- sync_env.pop("UV_NO_CONFIG", None)- synced = subprocess.run(- [- uv_bin,- "sync",- "--extra",- "all",- "--locked",- "--python",- str(_venv_python(candidate)),- ],- cwd=project_root,- env=sync_env,- stderr=subprocess.STDOUT,- check=False,- )- if synced.returncode != 0:- logger.warning("candidate dependency sync failed (rc=%d)", synced.returncode)- _remove_tree(candidate, boundary=runtime_root)- return None-- healthy, detail, _ = _smoke_candidate_venv(candidate)- if not healthy:- logger.warning("candidate venv smoke failed: %s", detail)- _remove_tree(candidate, boundary=runtime_root)- return None- return candidate---def _rename_with_retry(source: Path, destination: Path) -> None:- last_error: OSError | None = None- for delay in (0.0, 0.1, 0.25, 0.5, 1.0):- if delay:- time.sleep(delay)- try:- source.rename(destination)- return- except OSError as exc:- last_error = exc- if last_error is not None:- raise last_error---def _cut_over_candidate(- candidate: Path,- *,- project_root: Path,- live: Path | None = None,-) -> tuple[bool, Path | None, SQLiteRuntimeInfo | None, str]:- live = live if live is not None else project_root / _VENV_NAME- runtime_root = _runtime_dir(project_root)- token = f"{int(time.time())}-{os.getpid()}-{uuid.uuid4().hex[:8]}"- backup = live.with_name(f"{live.name}.stale.runtime-{token}")- rejected = runtime_root / f"venv-rejected-{token}"-- try:- try:- _rename_with_retry(live, backup)- except OSError as exc:- return False, None, None, f"could not park the existing venv: {exc}"-- try:- _rename_with_retry(candidate, live)- except OSError as promote_error:- try:- _rename_with_retry(backup, live)- except OSError as rollback_error:- return (- False,- backup,- None,- "could not promote the replacement venv "- f"({promote_error}); rollback failed ({rollback_error})",- )- return (- False,- None,- None,- f"could not promote the replacement venv: {promote_error}",- )-- try:- healthy, detail, info = _smoke_candidate_venv(live)- except Exception as exc:- healthy, detail, info = False, f"candidate smoke raised: {exc}", None- if healthy:- return True, backup, info, ""-- try:- _rename_with_retry(live, rejected)- _rename_with_retry(backup, live)- except OSError as exc:- return (- False,- backup,- info,- "post-cutover smoke failed "- f"({detail}); rollback failed ({exc}); rejected venv: {rejected}",- )- _remove_tree(rejected, boundary=runtime_root)- return False, None, info, f"post-cutover smoke failed: {detail}"- except BaseException:- if not live.exists() and backup.exists():- try:- _rename_with_retry(backup, live)- except OSError as exc:- logger.error(- "interrupted runtime cutover could not restore %s from %s: %s",- live,- backup,- exc,- )- raise---def _acquire_repair_lock(runtime_root: Path) -> _RepairLock | None:- """Acquire an OS-held install lock that is released on process exit."""- runtime_root.mkdir(parents=True, exist_ok=True)- _make_world_traversable(runtime_root)- path = runtime_root / _REPAIR_LOCK_NAME- try:- fd = os.open(path, os.O_CREAT | os.O_RDWR, 0o600)- except OSError:- return None-- try:- if os.name == "nt":- import msvcrt-- if os.fstat(fd).st_size == 0:- os.write(fd, b"\0")- os.lseek(fd, 0, os.SEEK_SET)- msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)- else:- import fcntl-- fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)- except (ImportError, OSError):- os.close(fd)- return None- return _RepairLock(path=path, fd=fd)---def _release_repair_lock(lock: _RepairLock) -> None:- try:- if os.name == "nt":- import msvcrt-- os.lseek(lock.fd, 0, os.SEEK_SET)- msvcrt.locking(lock.fd, msvcrt.LK_UNLCK, 1)- else:- import fcntl-- fcntl.flock(lock.fd, fcntl.LOCK_UN)- except (ImportError, OSError):- pass- finally:- try:- os.close(lock.fd)- except OSError:- pass---def _windows_runtime_holders() -> tuple[bool, str]:- if platform.system() != "Windows":- return False, ""- try:- from hermes_cli.update_cmd_windows import _detect_venv_python_processes- holders = _detect_venv_python_processes()- except Exception as exc:- return True, f"could not verify Windows venv holders: {exc}"- if holders:- pids = ", ".join(str(item[0]) for item in holders[:6])- return True, f"other Hermes processes still hold the venv (PID {pids})"- return False, ""---def _windows_runtime_self_lock(live: Path) -> tuple[bool, str]:- """Detect the one holder the generic scan above is blind to: THIS process.-- ``_detect_venv_python_processes`` excludes the calling process and its- ancestors on purpose — a CLI ``hermes update`` itself runs from the- venv python — which is correct for the dependency-sync path, where only- a *loaded* ``.pyd`` image blocks the rewrite and a fresh child process- dodges it. For the whole-venv park rename that exemption is fatal:- Windows keeps the image of any executable a running process was started- from mapped until that process exits, so a directory containing the- updater's own ``python.exe`` (or a waiting ``hermes.exe`` launcher- ancestor) can never be renamed from inside the updater. The retry loop- in ``_cut_over_candidate`` cannot help against that — the lock is- structural, not transient (#93032).-- No-op off Windows: POSIX renames work fine while this process maps- files from the renamed tree (open FDs and mmaps keep inodes alive).- """- if platform.system() != "Windows":- return False, ""- try:- live_res = str(live.resolve()).lower().rstrip(os.sep) + os.sep- except OSError:- live_res = str(live).lower().rstrip(os.sep) + os.sep-- def _under_live(path_value: str | None) -> bool:- if not path_value:- return False- try:- resolved = str(Path(path_value).resolve()).lower()- except (OSError, ValueError):- resolved = str(path_value).lower()- return resolved.startswith(live_res)-- try:- exe = sys.executable- except Exception:- exe = None- if _under_live(exe):- return True, (- f"the updater itself runs from the live venv it must replace "- f"({exe}); Windows cannot rename a directory while a process "- "executes from inside it"- )- # Belt-and-braces: the venv\Scripts\hermes.exe launcher stays mapped- # while it waits for this child, so an ancestor started from the venv- # blocks the rename too.- try:- import psutil-- try:- parents = psutil.Process().parents()- except Exception:- parents = []- for anc in parents:- try:- anc_exe = anc.exe()- except Exception:- continue- if _under_live(anc_exe):- return True, (- f"ancestor process PID {anc.pid} runs from the live venv "- f"({anc_exe}); Windows cannot rename a directory while a "- "process executes from inside it"- )- except Exception:- pass- return False, ""---def _default_live_venv(root: Path) -> Path:- """Return the venv that runtime repair should target for *root*.-- Managed installs create ``<checkout>/venv``, but uv-default and dev- checkouts use ``<checkout>/.venv``. Historically only ``venv`` was- probed, so a ``.venv`` install linking a vulnerable SQLite returned- ``not-applicable`` on every ``hermes update`` and stayed on- journal_mode=DELETE forever — even though the WAL fallback warning- promises that ``hermes update`` repairs the runtime (issue class:- 2,600x slower ``state.db`` appends under DELETE).-- ``venv`` wins when it holds an interpreter (managed layout takes- precedence); otherwise fall back to ``.venv`` when that one does.- When neither has an interpreter, return the ``venv`` path so the- caller's existing ``not-applicable`` handling fires unchanged.- """- primary = root / _VENV_NAME- if _venv_python(primary).is_file():- return primary- fallback = root / _ALT_VENV_NAME- if _venv_python(fallback).is_file():- return fallback- return primary---def _sweep_stale_runtime_backups(- live: Path,- *,- root: Path,- keep: Path | None = None,- min_age_seconds: float = 3600.0,-) -> None:- """Remove leftover ``venv.stale.runtime-*`` backups next to *live*.-- A successful runtime repair parks the previous venv as- ``<live>.stale.runtime-<token>``; historically nothing ever reclaimed- those, so each repair leaked a full venv (~1 GB) at the project root- forever (issue #73109). On POSIX, deleting the tree is safe even while- an older process still maps files from it — open FDs and mmaps keep- their inodes alive; the directory entry is what goes away.-- ``min_age_seconds`` guards against racing a concurrent repair in- another process: a backup parked seconds ago may still be that- repair's rollback path, so only clearly-old markers are swept.- ``keep`` exempts the backup the current repair just created.- Best-effort: never raises.- """- try:- candidates = list(live.parent.glob(f"{live.name}.stale.runtime-*"))- except OSError:- return- now = time.time()- for candidate in candidates:- if keep is not None and candidate == keep:- continue- try:- age = now - candidate.stat().st_mtime- except OSError:- continue- if age < min_age_seconds:- continue- _remove_tree(candidate, boundary=root)---def repair_vulnerable_runtime(- *,- project_root: Path | None = None,- venv_dir: Path | None = None,-) -> RuntimeRepairResult:- """Replace a vulnerable install venv without mutating it in place.-- Every failure before cutover leaves the live venv untouched. Rename or- post-cutover smoke failures restore the parked venv synchronously.-- uv is resolved internally — the pinned binary via ``pm`` (its version- lives in ``pm/lock.json``; the bytes live in the pm store). There is- no foreign-uv path: the lockfile names exactly one uv, and a repair- that ran on someone else's uv would provision an interpreter outside- the catalog the pin promises. A stale python-build-standalone catalog- is fixed by bumping the uv pin — ``hermes update`` pulls the new- lockfile before repair runs, so pm has already realized the bumped- binary by the time this module asks for it.- """- root = Path(project_root) if project_root is not None else _PROJECT_ROOT- live = Path(venv_dir) if venv_dir is not None else _default_live_venv(root)- live_python = _venv_python(live)- if not (root / "pyproject.toml").is_file() or not live_python.is_file():- return RuntimeRepairResult("not-applicable")-- from pm.client import uv as pm_uv-- uv_bin, _uv_env = pm_uv()- if not uv_bin:- return RuntimeRepairResult(- "skipped", "pinned uv unavailable (pm could not realize it)"- )-- current = probe_sqlite_runtime(live_python)- if current is None:- return RuntimeRepairResult(- "skipped",- f"could not probe live interpreter {live_python}",- )- if not current.wal_reset_vulnerable:- # The runtime is already fixed — any venv.stale.runtime-* markers- # next to the live venv are leftovers from a past repair (or from- # a build predating the post-repair cleanup) and will never be- # rolled back to. Sweep them so they don't leak ~1 GB each- # forever (issue #73109). Age-gated to avoid racing an in-flight- # repair in a sibling process.- _sweep_stale_runtime_backups(live, root=root)- return RuntimeRepairResult(- "safe",- sqlite_before=current.sqlite_version_string,- sqlite_after=current.sqlite_version_string,- )-- blocked, detail = _windows_runtime_holders()- if blocked:- print(f" ⚠ SQLite runtime repair deferred: {detail}")- return RuntimeRepairResult(- "skipped",- detail,- sqlite_before=current.sqlite_version_string,- )-- self_locked, self_detail = _windows_runtime_self_lock(live)- if self_locked:- # Structural, not transient: this process maps the live venv's own- # executable, so the park rename fails the same way on every run and- # no number of retries converges. Defer BEFORE provisioning — a- # candidate staged for a cutover that can never run only leaks an- # incomplete generation (#93032).- print(f" ⚠ SQLite runtime repair deferred: {self_detail}.")- print(- " Retrying `hermes update` from inside this venv cannot help: "- "the mapped executable is released only when this process exits."- )- print(- " To complete the repair, run the updater from an interpreter "- "that lives outside this venv, e.g.:"- )- print(f" cd {root}")- print(" <system Python> -m hermes_cli.main update")- return RuntimeRepairResult(- "skipped",- self_detail,- sqlite_before=current.sqlite_version_string,- )-- runtime_root = _runtime_dir(root)- lock = _acquire_repair_lock(runtime_root)- if lock is None:- detail = "another runtime repair is already in progress"- print(f" ⚠ SQLite runtime repair deferred: {detail}")- return RuntimeRepairResult(- "skipped",- detail,- sqlite_before=current.sqlite_version_string,- )-- generation: Path | None = None- candidate: Path | None = None- try:- # Re-probe under the install-scoped lock: another updater may have- # completed the repair while this process was entering the path.- current = probe_sqlite_runtime(live_python)- if current is None:- return RuntimeRepairResult("skipped", "live interpreter probe failed")- if not current.wal_reset_vulnerable:- return RuntimeRepairResult(- "safe",- sqlite_before=current.sqlite_version_string,- sqlite_after=current.sqlite_version_string,- )-- print(- " ⚠ Hermes venv links SQLite "- f"{current.sqlite_version_string}, which has the WAL-reset bug."- )- provisioned = _install_safe_python_generation(- uv_bin,- project_root=root,- current=current,- )- if provisioned is None:- return RuntimeRepairResult(- "failed",- "could not provision a fixed private Python runtime",- sqlite_before=current.sqlite_version_string,- )- generation, python, candidate_info = provisioned-- candidate = _stage_candidate_venv(- uv_bin,- project_root=root,- generation=generation,- python=python,- )- if candidate is None:- _remove_tree(generation, boundary=managed_python_install_dir(root))- return RuntimeRepairResult(- "failed",- "replacement environment did not pass dependency and import smoke tests",- sqlite_before=current.sqlite_version_string,- sqlite_after=candidate_info.sqlite_version_string,- )-- cut_over, backup, final_info, cutover_detail = _cut_over_candidate(- candidate,- project_root=root,- live=live,- )- if not cut_over:- if backup is None:- _remove_tree(candidate, boundary=runtime_root)- _remove_tree(generation, boundary=managed_python_install_dir(root))- return RuntimeRepairResult(- "failed",- cutover_detail,- sqlite_before=current.sqlite_version_string,- sqlite_after=(- final_info.sqlite_version_string if final_info is not None else ""- ),- backup_venv=backup,- )-- final_version = (- final_info.sqlite_version_string- if final_info is not None- else candidate_info.sqlite_version_string- )- print(- " ✓ Managed Python runtime repaired "- f"(SQLite {current.sqlite_version_string} → {final_version})"- )- if backup is not None and backup.exists():- _remove_tree(backup, boundary=root)- return RuntimeRepairResult(- "repaired",- sqlite_before=current.sqlite_version_string,- sqlite_after=final_version,- backup_venv=backup,- )- finally:- _release_repair_lock(lock)---# ----------------------------------------------------------------------------# Legacy stub-# ------------------------------------------------------------------------------def rebuild_venv(uv_bin: str, venv_dir: Path, python_version: str = "3.14") -> bool:- return True # dont remove me. ask ethernetdiff --git a/hermes_cli/setup_terminal.py b/hermes_cli/setup_terminal.pyindex f80658ae74d..400a99d5ba9 100644--- a/hermes_cli/setup_terminal.py+++ b/hermes_cli/setup_terminal.py@@ -98,22 +98,21 @@ def _existing_secret_keeps(env_var: str, label: str, question: str) -> bool:return not _setup.prompt_yes_no(question, False)-def _ensure_sdk(package: str, manual_hint: str, *, show_stderr: bool = False, install=None) -> None:- """Import *package*; if missing, install it (default: the venv pip ladder)."""+def _ensure_sdk(extra: str) -> None:+ """Enable a declared SDK extra without mutating the running interpreter."""+ import pm+try:- __import__(package)+ __import__(extra)except ImportError:- _setup.print_info(f"Installing {package} SDK...")- if install is None:- from hermes_cli.tools_config import _pip_install- install = lambda pkg: _pip_install([pkg]) # noqa: E731- result = install(package)- if result.returncode == 0:- _setup.print_success(f"{package} SDK installed")+ _setup.print_info(f"Installing {extra} SDK...")+ try:+ pm.sync_venv([extra], explicit=True)+ except (pm.InstallError, OSError, ValueError) as exc:+ _setup.print_warning(f"Install failed: {exc}")+ _setup.print_info("Retry with: hermes setup terminal")else:- _setup.print_warning(f"Install failed — run manually: {manual_hint}")- if show_stderr and result.stderr:- _setup.print_info(f" Error: {result.stderr.strip().splitlines()[-1]}")+ _setup.print_success(f"{extra} SDK installed. Restart Hermes to use it.")def _report_binary(found: str | None, missing: str, install_hint: str, found_prefix: str = "Found: ") -> None:@@ -186,7 +185,7 @@ def _setup_backend_modal(config: dict) -> None:returnconfig["terminal"]["modal_mode"] = "direct"_setup.print_info("Requires a Modal account: https://modal.com")- _ensure_sdk("modal", "uv pip install modal")+ _ensure_sdk("modal")_setup._info(None, "Modal authentication:", " Get your token at: https://modal.com/settings")if _existing_secret_keeps("MODAL_TOKEN_ID", "Modal token", " Update Modal credentials?"):return@@ -199,7 +198,7 @@ def _setup_backend_daytona(config: dict) -> None:_setup._info("Persistent cloud development environments.","Each session gets a dedicated sandbox with filesystem persistence.","Sign up at: https://daytona.io")- _ensure_sdk("daytona", "uv pip install daytona", show_stderr=True)+ _ensure_sdk("daytona")print()had_key = bool(_setup.get_env_value("DAYTONA_API_KEY"))if not _existing_secret_keeps("DAYTONA_API_KEY", "Daytona API key", " Update API key?"):@@ -211,8 +210,8 @@ def _setup_backend_daytona(config: dict) -> None:def _setup_backend_vercel(config: dict) -> None:_setup.print_success("Terminal backend: Vercel Sandbox")_setup._info("Cloud microVM sandboxes with snapshot-backed filesystem persistence.",- "Requires the optional SDK: pip install 'hermes-agent[vercel]'")- _ensure_sdk("vercel", "pip install 'hermes-agent[vercel]'", show_stderr=True)+ "Requires the optional Vercel SDK (installed through Hermes PM).")+ _ensure_sdk("vercel")_prompt_vercel_sandbox_settings(config)diff --git a/hermes_cli/setup_tts.py b/hermes_cli/setup_tts.pyindex 8c5cca8d4b9..6fd668e085d 100644--- a/hermes_cli/setup_tts.py+++ b/hermes_cli/setup_tts.py@@ -12,22 +12,18 @@ from hermes_cli import nous_subscriptionlogger = logging.getLogger("hermes_cli.setup")-def _pip_install_tts_package(name: str, pip_args: list, manual_cmd: str) -> bool:- """Install a local TTS engine through the canonical uv → pip → ensurepip- ladder so pip-less venvs (Ubuntu 25.10 ``python -m venv``, ``uv venv``) work."""- from hermes_cli.tools_config import _pip_install+def _install_tts_extra(extra: str) -> bool:+ """Record the engine in PM's dependency union; activate it on next launch."""+ import pm+try:- result = _pip_install(pip_args, timeout=300)- if result.returncode == 0:- _setup.print_success(f"{name} installed successfully")- return True- err = (result.stderr or "").strip()- reason = err[:300] if err else "install failed"- except Exception as e:- reason = e- _setup.print_error(f"Failed to install {name}: {reason}")- _setup.print_info(f"Try manually: {manual_cmd}")- return False+ pm.sync_venv([extra], explicit=True)+ except (pm.InstallError, OSError, ValueError) as exc:+ _setup.print_error(f"Failed to install {extra}: {exc}")+ _setup.print_info("Retry with: hermes setup tts")+ return False+ _setup.print_success(f"{extra} installed. Restart Hermes to use it.")+ return True# sys.platform -> (manual install hint, install command); anything else uses "linux".@@ -40,6 +36,11 @@ _ESPEAK_INSTALL = {def _install_neutts_deps() -> bool:"""Install NeuTTS dependencies with user approval. Returns True on success."""+ from pm.extras import extra_supported++ if not extra_supported("neutts"):+ _setup.print_error("NeuTTS is not supported by this Python/platform.")+ return Falseif not (shutil.which("espeak-ng") or shutil.which("espeak")):hint, install_cmd = _ESPEAK_INSTALL.get(sys.platform, _ESPEAK_INSTALL["linux"])print()@@ -59,15 +60,13 @@ def _install_neutts_deps() -> bool:_setup._info(None, "Installing neutts Python package...","This will also download the TTS model (~300MB) on first use.", None)- return _pip_install_tts_package("neutts", ["-U", "neutts[all]", "--quiet"], "uv pip install -U 'neutts[all]'")+ return _install_tts_extra("neutts")def _install_kittentts_deps() -> bool:"""Install KittenTTS dependencies with user approval. Returns True on success."""- wheel_url = "https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl"_setup._info(None, "Installing kittentts Python package (~25-80MB model downloaded on first use)...", None)- return _pip_install_tts_package(- "kittentts", ["-U", wheel_url, "soundfile", "--quiet"], f"uv pip install -U '{wheel_url}' soundfile")+ return _install_tts_extra("kittentts")def _xai_oauth_logged_in_for_setup() -> bool:@@ -161,8 +160,15 @@ def _tts_api_key_step(selected: str) -> str:def _tts_local_install_step(selected: str) -> str:- """Offer to install a local TTS engine; fall back to edge if declined/failed."""+ """Offer a local engine install; retain an unsupported explicit selection."""+ from pm.extras import extra_supported+module, name, lines, question, installer = _TTS_LOCAL_PROVIDERS[selected]+ if not extra_supported(selected):+ _setup.print_warning(+ f"{name} is not supported by this Python/platform. "+ "Your provider selection is saved, but speech requires a supported engine.")+ return selectedif _setup._module_installed(module):_setup.print_success(f"{name} is already installed")return selecteddiff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.pyindex 1bb04268a8a..048d2ab13ba 100644--- a/hermes_cli/tools_config.py+++ b/hermes_cli/tools_config.py@@ -17,14 +17,13 @@ from hermes_cli.toolset_scope import (# Re-exports: keep ``hermes_cli.tools_config.X`` callers and test patch targets resolving.from hermes_cli.tools_config_cua import ( # noqa: F401_post_setup_no_window_flags, _cua_driver_cmd, _cua_version_summary, _resolved_cua_driver_cmd, _cua_driver_env,- _cua_driver_contract_status, _cua_driver_install_ready, _pip_install, _cua_install_target_writable,+ _cua_driver_contract_status, _cua_driver_install_ready, _cua_install_target_writable,install_cua_driver, _CUA_INSTALLER_TIMEOUT, _CUA_INSTALLER_DRAIN_GRACE, _CUA_LOCK_STALE_AFTER,_clear_stale_windows_cua_install_lock, _clear_stale_cua_install_lock, _cua_install_lock_held,_cua_release_endpoint_reachable, _repair_cua_driver_autostart_windows, _run_cua_driver_installer)from hermes_cli.tools_config_post_setup import ( # noqa: F401_ensure_browser_use_cli, _run_post_setup, valid_post_setup_keys, run_post_setup_command, _POST_SETUP_INSTALLED,- _post_setup_already_installed, _module_installed, active_restorable_python_tool_dependencies,- restorable_python_tool_dependency, _POST_SETUP_READY)+ _post_setup_already_installed, _module_installed, _POST_SETUP_READY)from hermes_cli.tools_config_providers import ( # noqa: F401_plugin_image_gen_providers, _plugin_video_gen_providers, _plugin_web_search_providers, _plugin_browser_providers,_plugin_tts_providers, web_provider_capabilities, _visible_providers, provider_readiness_status,diff --git a/hermes_cli/tools_config_cua.py b/hermes_cli/tools_config_cua.pyindex 9ec6f6a8074..9e4b8b6a702 100644--- a/hermes_cli/tools_config_cua.py+++ b/hermes_cli/tools_config_cua.py@@ -1,4 +1,4 @@-"""cua-driver installer, lock hygiene and pip-install helper for `hermes tools` /+"""cua-driver installer and lock hygiene for `hermes tools` /`hermes computer-use install`."""from __future__ import annotations@@ -13,7 +13,7 @@ import subprocessimport sysimport timefrom pathlib import Path-from typing import List, Optional+from typing import Optionalfrom hermes_cli.cli_output import (print_info as _print_info, print_success as _print_success, print_warning as _print_warning)@@ -142,54 +142,6 @@ def _cua_driver_install_ready() -> bool:sys.platform != "win32" or _cua_driver_autostart_registered_windows())-def _pip_install(args: List[str], *, timeout: int = 300, capture_output: bool = True):- """Install Python packages: ``uv pip install`` (needs no pip in the venv), then ``python -m- pip``, then ``ensurepip --upgrade`` + retry — the Windows installer creates the venv via- ``uv venv``, which does NOT seed pip, so bare ``-m pip`` failed on fresh installs."""- from hermes_constants import venv_python_path- from hermes_cli.runtime_paths import selected_venv- from pm.paths import repo_root-- venv_root = selected_venv(repo_root())- python = str(venv_python_path(venv_root))- install_flags = _post_setup_no_window_flags(streams_to_console=not capture_output)-- # Resolve uv and its target environment through PM, not ambient PATH.- from pm.client import uv as pm_uv- from pm.package import InstallError-- try:- uv_bin, uv_env = pm_uv(realize=True, venv=venv_root)- except InstallError as exc:- return subprocess.CompletedProcess(args, 1, stdout="", stderr=str(exc))- try: # a failed uv run falls through to pip — it may have failed for a reason pip can handle- result = uv_bin and _run_text([uv_bin, "pip", "install", "--python", str(venv_root), *args], timeout=timeout,- capture_output=capture_output, creationflags=install_flags,- env=uv_env)- if result and result.returncode == 0:- return result- except (subprocess.TimeoutExpired, FileNotFoundError):- pass- pip_cmd = [python, "-m", "pip"]- try:- # Probe for pip; bootstrap via ensurepip if missing (uv venv lacks it).- probe = _run_text(pip_cmd + ["--version"], timeout=15,- creationflags=_post_setup_no_window_flags())- if probe.returncode != 0:- raise FileNotFoundError("pip not in venv")- except (subprocess.TimeoutExpired, FileNotFoundError):- try:- _run_text([python, "-m", "ensurepip", "--upgrade", "--default-pip"],- timeout=120, check=True, creationflags=_post_setup_no_window_flags())- except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:- # Synthesize a result so callers see a clean failure path.- return subprocess.CompletedProcess(- pip_cmd, returncode=1, stdout="",- stderr=f"pip not available and ensurepip failed: {e}")- return _run_text(pip_cmd + ["install", *args], capture_output=capture_output, timeout=timeout,- creationflags=install_flags)--# No pre-install release/asset probe: cua-driver-rs releases are all prereleases, which GitHub's# `/releases/latest` skips (zero binary assets → every non-arm64 host skipped the install), and# re-implementing upstream's tag resolution here would drift. Fresh installs run install.sh directlydiff --git a/hermes_cli/tools_config_post_setup.py b/hermes_cli/tools_config_post_setup.pyindex 7e3dbaf6943..05ff2149b5e 100644--- a/hermes_cli/tools_config_post_setup.py+++ b/hermes_cli/tools_config_post_setup.py@@ -15,7 +15,7 @@ from hermes_cli.cli_output import (print_warning as _print_warning)from hermes_cli.config import get_env_valuefrom hermes_cli.tools_config_cua import (- _cua_driver_install_ready, _pip_install, _post_setup_no_window_flags, _run_text, install_cua_driver,+ _cua_driver_install_ready, _post_setup_no_window_flags, _run_text, install_cua_driver,)logger = logging.getLogger("hermes_cli.tools_config")@@ -32,8 +32,8 @@ def _info_lines(*lines: str) -> None:def _ensure_browser_use_cli(*, verbose_hints: bool = False) -> None:"""Install the Browser Use CLI if it isn't already runnable.Primary driver engine for EVERY browser backend except Camofox (Firefox-based, no CDP surface).- MANAGED-FIRST: a browser-use on the user's PATH does NOT satisfy this check — only the- Hermes-managed ``$HERMES_HOME/bin`` copy does."""+ A browser-use on the user's PATH does not satisfy this check; PM owns the+ selected isolated tool environment."""_print_info(" Ensuring browser-use CLI (managed install)...")try:from tools.browser_use_cli import install_cli@@ -45,8 +45,7 @@ def _ensure_browser_use_cli(*, verbose_hints: bool = False) -> None:else:for line in str(message).splitlines():_print_warning(f" {line[:200]}")- _print_info(" Falling back to zero-install runs via `uvx browser-use`" if shutil.which("uvx")- else " Install manually: uv tool install browser-use (https://docs.astral.sh/uv/)")+ _print_info(" Retry with: hermes tools post-setup browser_use_cli")if verbose_hints:_info_lines("Local Chrome needs remote debugging: chrome://inspect/#remote-debugging","Cloud browsers: browser-use auth login (or set BROWSER_USE_API_KEY)")@@ -189,35 +188,28 @@ def _post_setup_camofox() -> None:_print_info(" docker run -p 9377:9377 -e CAMOFOX_PORT=9377 jo-inc/camofox-browser")-_KITTENTTS_WHEEL_URL = "https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl"--# pip-only post-setup hooks: module (import probe), label, installing (progress line), args, manual-# (fallback command), on_install (fresh-install notes), always. Also feeds _RESTORABLE_PYTHON_TOOL_DEPENDENCIES.-def _pip_hook(module, label, installing, args, manual, on_install=(), always=()) -> dict:- return {"module": module, "label": label, "installing": installing, "args": args, "manual": manual,+# The hook key is the UI provider identifier; extra names belong to pyproject.toml.+def _python_hook(module, extra, label, installing, on_install=(), always=()) -> dict:+ return {"module": module, "extra": extra, "label": label, "installing": installing,"on_install": on_install, "always": always}-_PIP_POST_SETUP_HOOKS: dict = {- "faster_whisper": _pip_hook(- "faster_whisper", "faster-whisper", "Installing faster-whisper (model ~150MB downloads on first use)...",- ["-U", "faster-whisper", "--quiet"], "uv pip install -U faster-whisper",+_PYTHON_POST_SETUP_HOOKS: dict = {+ "faster_whisper": _python_hook(+ "faster_whisper", "stt-whisper", "faster-whisper", "Installing faster-whisper (model ~150MB downloads on first use)...",on_install=("Model sizes: tiny, base (default), small, medium, large-v3",- "Change via stt.local.model in ~/.hermes/config.yaml")),- "kittentts": _pip_hook(- "kittentts", "kittentts", "Installing kittentts (~25-80MB model, CPU-only)...",- ["-U", _KITTENTTS_WHEEL_URL, "soundfile", "--quiet"], f"uv pip install -U '{_KITTENTTS_WHEEL_URL}' soundfile",+ "Change via stt.local.model in config.yaml")),+ "kittentts": _python_hook(+ "kittentts", "kittentts", "kittentts", "Installing kittentts (~25-80MB model, CPU-only)...",on_install=("Voices: Jasper, Bella, Luna, Bruno, Rosie, Hugo, Kiki, Leo","Models: KittenML/kitten-tts-nano-0.8-int8 (25MB), micro (41MB), mini (80MB)")),- "piper": _pip_hook(- "piper", "piper-tts", "Installing piper-tts (~14MB wheel, voices downloaded on first use)...",- ["-U", "piper-tts", "--quiet"], "uv pip install -U piper-tts",+ "piper": _python_hook(+ "piper", "piper", "piper-tts", "Installing piper-tts (~14MB wheel, voices downloaded on first use)...",always=("Default voice: en_US-lessac-medium (downloaded on first TTS call)","Full voice list: https://github.com/OHF-Voice/piper1-gpl/blob/main/docs/VOICES.md",- "Switch voices by setting tts.piper.voice in ~/.hermes/config.yaml")),- "ddgs": _pip_hook(- "ddgs", "ddgs", "Installing ddgs (DuckDuckGo search package)...", ["-U", "ddgs", "--quiet"],- "uv pip install -U ddgs",+ "Switch voices by setting tts.piper.voice in config.yaml")),+ "ddgs": _python_hook(+ "ddgs", "ddgs", "ddgs", "Installing ddgs (DuckDuckGo search package)...",always=("No API key required. DuckDuckGo enforces server-side rate limits.","Pair with an extract provider if you also need web_extract."))}@@ -230,8 +222,10 @@ def _importable(module: str) -> bool:return False-def _post_setup_pip(spec: dict) -> None:- """Run one ``_PIP_POST_SETUP_HOOKS`` entry."""+def _post_setup_python(spec: dict) -> None:+ """Enable one Python provider through the application dependency transaction."""+ import pm+label = spec["label"]lines = list(spec["always"])if _importable(spec["module"]):@@ -239,16 +233,12 @@ def _post_setup_pip(spec: dict) -> None:else:_print_info(f" {spec['installing']}")try:- result = _pip_install(spec["args"], timeout=300)- except subprocess.TimeoutExpired:- _print_warning(f" {label} install timed out (>5min)")- _info_lines(f"Run manually: {spec['manual']}")+ pm.sync_venv([spec["extra"]], explicit=True)+ except (pm.InstallError, OSError, ValueError) as exc:+ _print_warning(f" {label} install failed: {exc}")+ _info_lines("Retry with: hermes tools")return- if result.returncode != 0:- _print_warning(f" {label} install failed:")- _info_lines(f" {(result.stderr or '').strip()[:300]}", f"Run manually: {spec['manual']}")- return- _print_success(f" {label} installed")+ _print_success(f" {label} installed. Restart Hermes to use it.")lines = list(spec["on_install"]) + lines_info_lines(*lines)@@ -282,11 +272,14 @@ def _post_setup_langfuse() -> None:_print_success(" langfuse SDK already installed")else:_print_info(" Installing langfuse SDK...")- result = _pip_install(["langfuse", "--quiet"], timeout=120)- if result.returncode == 0:- _print_success(" langfuse SDK installed")- else:- _print_warning(" langfuse SDK install failed — run manually: uv pip install langfuse")+ import pm+ try:+ pm.sync_venv(["langfuse"], explicit=True)+ except (pm.InstallError, OSError, ValueError) as exc:+ _print_warning(f" langfuse SDK install failed: {exc}")+ _info_lines("Retry with: hermes tools")+ return+ _print_success(" langfuse SDK installed. Restart Hermes to use it.")# The bundled observability/langfuse plugin is opt-in (standalone plugins don't load until enabled).try:from hermes_cli.plugins_cmd import _get_enabled_set, _save_enabled_set@@ -361,7 +354,7 @@ _POST_SETUP_HOOKS: dict = {"spotify": _post_setup_spotify,"langfuse": _post_setup_langfuse,"xai_grok": _post_setup_xai_grok,- **{key: (lambda spec=spec: _post_setup_pip(spec)) for key, spec in _PIP_POST_SETUP_HOOKS.items()},+ **{key: (lambda spec=spec: _post_setup_python(spec)) for key, spec in _PYTHON_POST_SETUP_HOOKS.items()},}@@ -437,27 +430,6 @@ def _module_installed(module_name: str) -> bool:return False-# Python deps installed via ``hermes tools`` aren't in the managed runtime's locked ``all`` sync, so a-# runtime replacement snapshots this static allowlist before the old site-packages disappears and-# restores it afterward. Derived from the pip hooks (minus ``--quiet``) so install args can't drift.-_RESTORABLE_PYTHON_TOOL_DEPENDENCIES: dict[str, tuple[str, tuple[str, ...]]] = {- **{key: (spec["module"], tuple(a for a in spec["args"] if a != "--quiet"))- for key, spec in _PIP_POST_SETUP_HOOKS.items()},- "langfuse": ("langfuse", ("langfuse",))}---def active_restorable_python_tool_dependencies() -> list[str]:- """Return ``hermes tools`` Python dependencies present in this runtime."""- return [- name for name, (module_name, _install_args) in _RESTORABLE_PYTHON_TOOL_DEPENDENCIES.items()- if _module_installed(module_name)]---def restorable_python_tool_dependency(name: str) -> tuple[str, tuple[str, ...]] | None:- """Return the import probe and pip arguments for an allowlisted tool."""- return _RESTORABLE_PYTHON_TOOL_DEPENDENCIES.get(name)--def _agent_browser_installed() -> bool:"""True when everything ``_run_post_setup("agent_browser")`` installs is present: the agent-browser CLI*and* the Chromium build it drives (or the Lightpanda engine, which needs no Chromium), so "Run@@ -497,7 +469,8 @@ def _cloud_agent_browser_installed() -> bool:# installed-checks the hooks perform. ``xai_grok`` is absent — a credential bootstrap handled as an# auth check. Late-bound lambdas so tests can monkeypatch the underlying predicates._POST_SETUP_READY: dict = {- **{key: (lambda m=module: _module_installed(m)) for key, (module, _args) in _RESTORABLE_PYTHON_TOOL_DEPENDENCIES.items()},+ **{key: (lambda m=spec["module"]: _module_installed(m)) for key, spec in _PYTHON_POST_SETUP_HOOKS.items()},+ "langfuse": lambda: _module_installed("langfuse"),"agent_browser": lambda: _agent_browser_installed(),"browserbase": lambda: _cloud_agent_browser_installed(),"camofox": lambda: _camofox_installed(),diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 8f75cb809b2..5bcae4fc673 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -75,7 +75,7 @@ from hermes_cli.update_cmd_config import ( # noqa: F401from hermes_cli.update_cmd_deps import ( # noqa: F401_INSTALL_DEFINING_FILES, _UPDATE_CRITICAL_MODULES,_capture_active_lazy_features,- _capture_active_tool_dependencies, _critical_module_import_failures,+ _critical_module_import_failures,_desktop_app_present,_editable_install_is_current,_npm_bin_exists,@@ -1014,7 +1014,7 @@ def _print_update_check_result(behind: int | None, compare_branch: str) -> None:def _repair_venv_on_current_checkout(*, assume_yes, gateway_mode, pre_update_snapshot_id, desktop_dir,- had_desktop_app_before_update, active_lazy_features, active_tool_dependencies,+ had_desktop_app_before_update, active_lazy_features,_windows_gateway_resume) -> bool:"""Stage a replacement dependency environment; keep the marker on failure."""_write_update_incomplete_marker()@@ -1052,20 +1052,10 @@ def _repair_venv_on_current_checkout(def _repair_current_checkout(*, assume_yes, gateway_mode, pre_update_snapshot_id, desktop_dir,- had_desktop_app_before_update, active_lazy_features, active_tool_dependencies,+ had_desktop_app_before_update, active_lazy_features,upstream_checked, _windows_gateway_resume) -> bool:"""Already-up-to-date path: keep the managed runtime current, repair a broken venv.Returns whether the checkout can be reported complete."""- # "No new commits" does not mean the venv is safe: pm owns the uv pin now — a pin bump- # realizes a NEW entry on the next ensure. The update command is the one caller that- # must SEE realization failures, so use the raising API, not the None-swallowing uv().- import pm-- try:- pm.ensure("uv")- except pm.InstallError as e:- print(f"⚠ Managed uv unavailable: {e}")-# A current checkout does NOT imply a healthy install: a previous dependency sync may# have failed partway (classic on Windows: a running gateway/desktop backend keeps .pyd# locked and the installer dies with access-denied, stranding the venv between@@ -1088,7 +1078,6 @@ def _repair_current_checkout(pre_update_snapshot_id=pre_update_snapshot_id, desktop_dir=desktop_dir,had_desktop_app_before_update=had_desktop_app_before_update,active_lazy_features=active_lazy_features,- active_tool_dependencies=active_tool_dependencies,_windows_gateway_resume=_windows_gateway_resume)return _repair_node_deps_on_current_checkout(_print_verified_update_completion, assume_yes=assume_yes, gateway_mode=gateway_mode,@@ -1363,7 +1352,6 @@ class _UpdateOptions:"""Resolved ``hermes update`` inputs (flags, config, pre-update snapshots)."""active_lazy_features: object- active_tool_dependencies: objectpre_update_version: objectgw_input_fn: objectassume_yes: bool@@ -1377,7 +1365,6 @@ def _resolve_update_options(args, gateway_mode: bool) -> _UpdateOptions:# Snapshot before a managed-runtime refresh can replace site-packages, while the old# environment can still prove which optional backends were active.active_lazy_features = _m()._capture_active_lazy_features()- active_tool_dependencies = _m()._capture_active_tool_dependencies()# Captured before any pull so the completion line can report the transition.# Snapshot the pre-update version before files are replaced so the completion line can report the@@ -1406,7 +1393,7 @@ def _resolve_update_options(args, gateway_mode: bool) -> _UpdateOptions:discard_local_changes = _mode == "discard"return _UpdateOptions(active_lazy_features=active_lazy_features,- active_tool_dependencies=active_tool_dependencies, pre_update_version=pre_update_version,+ pre_update_version=pre_update_version,gw_input_fn=gw_input_fn, assume_yes=assume_yes, keep_stash=keep_stash,switch_branch=switch_branch, discard_local_changes=discard_local_changes)@@ -1578,7 +1565,7 @@ def _finalize_receipt(status: str, debug_message: str) -> None:def _finish_already_up_to_date(git_cmd, branch: str, current_branch: str, _plan, *, assume_yes: bool, gateway_mode: bool,gw_input_fn, pre_update_snapshot_id, desktop_dir, had_desktop_app_before_update: bool,- active_lazy_features, active_tool_dependencies, _windows_gateway_resume) -> None:+ active_lazy_features, _windows_gateway_resume) -> None:""""Already up to date" path: restore stash/branch, repair the checkout, catch up the fleet.``sys.exit(1)`` when the repair is incomplete (after gateway exit code + partial receipt)."""_invalidate_update_cache()@@ -1605,7 +1592,7 @@ def _finish_already_up_to_date(pre_update_snapshot_id=pre_update_snapshot_id, desktop_dir=desktop_dir,had_desktop_app_before_update=had_desktop_app_before_update,active_lazy_features=active_lazy_features,- active_tool_dependencies=active_tool_dependencies, upstream_checked=_plan.upstream_checked,+ upstream_checked=_plan.upstream_checked,_windows_gateway_resume=_windows_gateway_resume)_m()._resume_windows_gateways_after_update(_windows_gateway_resume)# A prior pull may still owe the fleet a restart; catch up here too, BEFORE the exit@@ -1651,7 +1638,6 @@ def _apply_pulled_update(# consumes its outcome instead of recomputing it.node_failures, desktop_build_ok = _sync_python_dependencies_after_pull(git_cmd, branch, pre_pull_sha, active_lazy_features=opts.active_lazy_features,- active_tool_dependencies=opts.active_tool_dependencies,_windows_gateway_resume=_windows_gateway_resume, desktop_dir=desktop_dir,had_desktop_app_before_update=had_desktop_app_before_update)@@ -1795,7 +1781,6 @@ def _cmd_update_impl(args, gateway_mode: bool):pre_update_snapshot_id=pre_update_snapshot_id, desktop_dir=desktop_dir,had_desktop_app_before_update=had_desktop_app_before_update,active_lazy_features=opts.active_lazy_features,- active_tool_dependencies=opts.active_tool_dependencies,_windows_gateway_resume=_windows_gateway_resume)returndiff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex b1d67966a1c..92b49598560 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -156,18 +156,6 @@ def _capture_active_lazy_features() -> list[str]:return []-def _capture_active_tool_dependencies() -> list[str]:- """Snapshot Python dependencies installed explicitly through ``hermes tools``."""- try:- from hermes_cli import tools_config- return tools_config.active_restorable_python_tool_dependencies()- except Exception as exc:- logger.debug("Could not snapshot active Hermes Tools dependencies: %s", exc)- return []----def _refresh_active_lazy_features(features: list[str] | None = None) -> bool:"""Re-sync the venv's enabled extras against the (possibly new) uv.lock.@@ -647,7 +635,7 @@ def _refuse_update_if_venv_foreign_owned(project_root) -> None:def _sync_python_dependencies_after_pull(- git_cmd, branch, pre_pull_sha, *, active_lazy_features, active_tool_dependencies,+ git_cmd, branch, pre_pull_sha, *, active_lazy_features,_windows_gateway_resume, desktop_dir, had_desktop_app_before_update):"""Reinstall Python deps for the pulled checkout (PM flow). Order matters: ownership preflight ->core marker -> ``pm.sync_venv(["all"], explicit=True)`` (stages + commits a fresh generationdiff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex c6b09130a07..db014642b23 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -317,7 +317,7 @@ def _download_and_swap_zip(branch: str, zip_url: str) -> None:shutil.rmtree(tmp_dir, ignore_errors=True)-def _reinstall_python_deps_after_zip(active_tool_dependencies) -> None:+def _reinstall_python_deps_after_zip() -> None:"""Reinstall Python deps via the PM sync authority (pm.sync_venv, no pip fallback).The PM sync stages a fresh generation environment and commits the selection — the live@@ -328,13 +328,6 @@ def _reinstall_python_deps_after_zip(active_tool_dependencies) -> None:import pm- # Same raising-uv realize the current-checkout repair path uses: the update command- # must SEE realization failures rather than silently fall back.- try:- pm.ensure("uv")- except pm.InstallError as e:- print(f"⚠ Managed uv unavailable: {e}")-try:pm.sync_venv(["all"], explicit=True)except pm.InstallError as _sync_err:@@ -366,7 +359,6 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False,)from hermes_cli.update_cmd_maint import _print_bundled_skills_sync_reportfrom hermes_cli.update_cmd_maint import _sweep_bytecode_after_update- active_tool_dependencies = _m()._capture_active_tool_dependencies()pre_update_version = _read_project_version() # snapshot before files are replaced, for the completion line# The static archive would silently ignore --branch — the exact silent-divergence bug it exists to# prevent. Refuse rather than lie.@@ -387,7 +379,7 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False,_download_and_swap_zip(branch, f"https://github.com/NousResearch/hermes-agent/archive/{ref}.zip")_sweep_bytecode_after_update(branch)print("→ Updating Python dependencies...")- _reinstall_python_deps_after_zip(active_tool_dependencies)+ _reinstall_python_deps_after_zip()# Verify the tree imports (catches the parse-OK-but-skewed tree an interrupted copy leaves). Runs# *after* the dep reinstall so a genuinely-new third-party requirement isn't misreported as a partial# copy. No SHA to roll back to — surface a concrete recovery step instead of success over a bricked install.diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.pyindex 5b119fee167..192f920f1c8 100644--- a/hermes_cli/venv_sync.py+++ b/hermes_cli/venv_sync.py@@ -1,103 +1,22 @@-"""Sync the install's Python environment to its tree — and nothing else.+"""Pre-venv entry point for PM's dependency transaction.-One of the two separately-invocable, stdlib-only-at-import halves of-"make this install runnable":--* ``pm`` — pinned tools and the venv ledger (facts.json), shape-universal.-* THIS module — the pre-venv entry point, whose meaning depends on the- install shape:-- - **checkout** (git clone + venv): make the venv match- ``pyproject.toml``/``uv.lock``. For the tree this module runs FROM,- the work is delegated to :func:`pm.sync_venv` — pm owns the extras- ledger and records the result in facts.json, so update and fresh- clone converge on one authority. For a foreign ``--project-root``- (installer bootstrapping a clone it has not exec'd into yet), uv is- driven directly with pm's pinned binary and sanitized env.- - **sealed** (desktop bundle, nix, docker): the interpreter tree is a- build artifact — syncing it is not possible and not meaningful.- Exit 0 with ``{"state": "sealed"}``, cleanly.--Stdlib-only at import is a hard contract: this runs on freshly-cloned-trees where the venv does not exist yet, and after tree swaps where the-venv is not trustworthy — exactly the moments a third-party import-would explode. ``pm`` is first-party code and is imported at sync time,-not when this module is imported.--PM decides whether this checkout needs a sync from its recorded inputs-and selected environment. A foreign bootstrap root retains its separate-lockfile-digest stamp until execution moves into that checkout.--Invocation:-- python -m hermes_cli.venv_sync # sync if stale- python -m hermes_cli.venv_sync --check # report, change nothing- python -m hermes_cli.venv_sync --json # machine-readable--Exit 0: current/synced/sealed. Exit 1: a sync was needed and failed.+Stdlib-only at import: installers call this before dependencies exist.+All checkout roots use PM's selected generation and facts; sealed payloads+remain build-owned. ``--check`` is passive and never provisions tools."""-from __future__ import annotationsimport argparse-import hashlibimport json-import os-import subprocess-import sysfrom pathlib import Pathfrom hermes_cli.steward import UPDATE_MECHANISMS-STAMP_NAME = "venv-sync.json"-STAMP_SCHEMA = 1-def _project_root() -> Path:return Path(__file__).resolve().parents[1]-def _runtime_dir(project_root: Path) -> Path:- """Where per-install runtime state lives for ``project_root``.-- Mirrors pm.paths.store_root()'s ladder (HERMES_RUNTIME_DIR, then the- install stamp's runtimeDir) but stays stdlib-local and falls back to- ``<root>/.hermes-runtime`` instead of the machine-global tool store:- the venv-sync stamp is per-install, and two checkouts sharing the- default store must not share a currency claim.- """- env = os.environ.get("HERMES_RUNTIME_DIR")- if env:- return Path(env)- try:- data = json.loads(- (project_root / "install-stamp.json").read_text(encoding="utf-8-sig")- )- stamped = data.get("runtimeDir") if isinstance(data, dict) else None- if stamped:- return Path(stamped)- except (OSError, ValueError):- pass- return project_root / ".hermes-runtime"---def _stamp_path(project_root: Path) -> Path:- return _runtime_dir(project_root) / "cache" / STAMP_NAME---def _lock_digest(project_root: Path) -> str | None:- """Hash the manifest and lock inputs for a foreign-root bootstrap."""- h = hashlib.sha256()- found = False- for name in ("uv.lock", "pyproject.toml"):- try:- h.update((project_root / name).read_bytes())- found = True- except OSError:- h.update(b"-")- return h.hexdigest() if found else None--def _is_sealed(project_root: Path) -> bool:"""A sealed tree ships its interpreter; only checkouts own a venv.@@ -130,115 +49,25 @@ def _is_sealed(project_root: Path) -> bool:return True-def _managed_uv() -> tuple:- """(uv binary path, sanitized env) from pm, or (None, None).-- ``pm.ensure.uv`` IS the resolution: facts from the store the pins- point at, env sanitized against interpreter hijack (#83914). pm is- stdlib-only first-party code, so the lazy import costs nothing and- keeps this module's bare-import surface stdlib-pure.- """- try:- from pm.client import uv as pm_uv-- uv_bin, env = pm_uv(realize=True)- except Exception:- return None, None- return uv_bin, env---def read_stamp(project_root: Path) -> dict:- try:- data = json.loads(_stamp_path(project_root).read_text(encoding="utf-8-sig"))- return data if isinstance(data, dict) else {}- except (OSError, ValueError):- return {}---def write_stamp(project_root: Path, digest: str) -> None:- path = _stamp_path(project_root)- path.parent.mkdir(parents=True, exist_ok=True)- tmp = path.with_suffix(".tmp")- tmp.write_text(- json.dumps(- {- "schemaVersion": STAMP_SCHEMA,- "lockDigest": digest,- "python": sys.version.split()[0],- }- ),- encoding="utf-8",- )- os.replace(tmp, path)---def _sync_foreign(root: Path) -> dict:- """Bootstrap a foreign checkout with PM's pinned uv and environment."""- uv, env = _managed_uv()- if uv is None:- return {- "ok": False,- "detail": "managed uv not provisioned (run `hermes pm install`)",- }- env = dict(env)- env["UV_PROJECT_ENVIRONMENT"] = str(root / "venv")- # A stale VIRTUAL_ENV from the calling shell would win over the- # project environment and sync the WRONG venv.- env.pop("VIRTUAL_ENV", None)- cmd = [str(uv), "sync"]- if (root / "uv.lock").is_file():- cmd.append("--frozen")- proc = subprocess.run(cmd, cwd=str(root), env=env)- if proc.returncode != 0:- return {"ok": False, "detail": f"uv sync exited {proc.returncode}"}- return {"ok": True, "detail": None}--def sync(project_root: Path | None = None, *, check: bool = False) -> dict:"""Report or sync dependencies. A malformed install stamp is a build error."""- root = Path(project_root) if project_root else _project_root()-+ root = Path(project_root) if project_root is not None else _project_root()if _is_sealed(root):return {"state": "sealed", "ok": True}-+ if not (root / "pyproject.toml").is_file():+ return {"state": "failed", "ok": False, "detail": f"no pyproject.toml under {root}"}try:- from pm import paths as pm_paths-- if Path(pm_paths.repo_root()).resolve() == root.resolve():- from pm import sync_venv- from pm.ensure import venv_is_current-- if venv_is_current():- return {"state": "current", "ok": True}- if check:- return {"state": "would-sync", "ok": True}- sync_venv(explicit=True)- return {"state": "synced", "ok": True}+ import pm++ if pm.venv_is_current(project_root=root):+ return {"state": "current", "ok": True}+ if check:+ return {"state": "would-sync", "ok": True}+ pm.sync_venv(explicit=True, project_root=root)+ return {"state": "synced", "ok": True}except Exception as exc:return {"state": "failed", "ok": False, "detail": str(exc)}- digest = _lock_digest(root)- if digest is None:- return {- "state": "failed",- "ok": False,- "detail": f"no pyproject.toml or uv.lock under {root}",- }-- if read_stamp(root).get("lockDigest") == digest:- return {"state": "current", "ok": True}-- if check:- return {"state": "would-sync", "ok": True}-- result = _sync_foreign(root)- if not result["ok"]:- # No stamp write: the next run must try again, not skip.- return {"state": "failed", "ok": False, "detail": result["detail"]}-- write_stamp(root, digest)- return {"state": "synced", "ok": True}-def main(argv: list | None = None) -> int:parser = argparse.ArgumentParser(prog="hermes_cli.venv_sync")diff --git a/tests/hermes_cli/conftest.py b/tests/hermes_cli/conftest.pyindex 50b31fd4705..2fd01e555dd 100644--- a/tests/hermes_cli/conftest.py+++ b/tests/hermes_cli/conftest.py@@ -60,30 +60,6 @@ def _suppress_concurrent_hermes_gate(request, monkeypatch):)-def patch_pm_uv_to_shutil_which():- """Make pm.uv follow shutil.which mocking; update-flow test modules that- stub uv availability via shutil.which patches apply this autouse=True."""- import os- import shutil- from unittest.mock import patch-- def _fake_pm_uv(*, venv=None, realize=True):- env = dict(os.environ)- if venv is not None:- env["VIRTUAL_ENV"] = str(venv)- return shutil.which("uv"), env-- with patch("pm.uv", side_effect=_fake_pm_uv):- yield---def isolated_update_uv(patch_pm_uv_to_shutil_which):- """Make pm.uv follow shutil.which mocking in tests."""- yield--@pytest.fixturedef isolated_update_processes():"""Keep cmd_update's gateway auto-restart phase off this machine's gateways.@@ -103,6 +79,7 @@ def isolated_update_processes():patch("hermes_cli.main._fleet_probe_expected_runtimes", return_value=False), \patch("os.kill"), \patch("pm.sync_venv"), \+ patch("pm.client.sync_venv"), \patch("hermes_cli.update_inventory.collect_runtime_inventory",return_value=SimpleNamespace(runtimes=[], to_dict=lambda: {}),diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.pyindex 8926aba6a68..36123e3f4dc 100644--- a/tests/hermes_cli/test_cmd_update.py+++ b/tests/hermes_cli/test_cmd_update.py@@ -54,16 +54,8 @@ def mock_args():return SimpleNamespace()-# ----------------------------------------------------------------------------# Managed-uv compatibility for tests that patch shutil.which-# ----------------------------------------------------------------------------# The production code resolves uv through ``pm.uv()`` instead of-# ``shutil.which("uv")``. Many tests in this file patch ``shutil.which``-# to control whether uv is "available" — this autouse fixture makes-# pm.uv delegate to the patched ``shutil.which`` so the existing test-# setup keeps working without per-test changes.pytestmark = pytest.mark.usefixtures(- "isolated_update_uv", "isolated_update_processes", "isolated_update_checkout",+ "isolated_update_processes", "isolated_update_checkout",)class TestCmdUpdateNpmLockfileCache:@@ -146,56 +138,6 @@ class TestCmdUpdateNpmLockfileCache:assert cache_roots == [shared_root, shared_root]-class TestUpdateManagedPythonEnvIsolation:- """Regression for the uv-env isolation fix (third-party UV_PYTHON_INSTALL_DIR- must not hijack the update's pip install).-- The update path builds uv_env via pm.packages.uv_env(): every UV_* user- override and active-venv leak (VIRTUAL_ENV, PYTHONPATH, ...) is STRIPPED- rather than re-pinned — pm passes --python explicitly, so no ambient- variable may steer which interpreter or install dir uv picks- (interpreter-hijack class, #83914). UV_NO_CONFIG=1 is the one pin.- """-- def test_managed_env_drops_third_party_uv_overrides(self):- from pm.packages import uv_env-- poisoned = {- "UV_PYTHON_INSTALL_DIR": r"C:\WorkBuddy\python",- "UV_PYTHON": r"C:\WorkBuddy\python\python.exe",- "UV_SYSTEM_PYTHON": "1",- "UV_NO_MANAGED_PYTHON": "1",- "VIRTUAL_ENV": r"C:\Some\Other\venv",- "PYTHONPATH": r"C:\Some\site-packages",- "PATH": r"C:\Windows",- }- env = uv_env(poisoned)-- # Every hijack vector is gone, not overridden.- assert "WorkBuddy" not in env.get("UV_PYTHON_INSTALL_DIR", "")- assert env.get("UV_PYTHON") is None- assert env.get("UV_SYSTEM_PYTHON") is None- assert env.get("UV_NO_MANAGED_PYTHON") is None- assert env.get("VIRTUAL_ENV") is None- assert env.get("PYTHONPATH") is None- # The one pin: user/system uv config must not apply.- assert env.get("UV_NO_CONFIG") == "1"- # Non-UV env passes through untouched.- assert env.get("PATH") == r"C:\Windows"-- def test_update_uv_env_points_venv_after_repoint(self):- """The update path re-points VIRTUAL_ENV at this install's venv and- re-enables uv config discovery for the project sync."""- from pm.packages import uv_env-- env = uv_env()- env["VIRTUAL_ENV"] = str(PROJECT_ROOT / "venv")- env.pop("UV_NO_CONFIG", None)-- assert env["VIRTUAL_ENV"] == str(PROJECT_ROOT / "venv")- assert env.get("UV_NO_CONFIG") is None--class TestCmdUpdateBranchFallback:"""cmd_update falls back to main when current branch has no remote counterpart."""@@ -1164,7 +1106,6 @@ class TestNodeRuntimeNpmResolution:),patch("subprocess.run", side_effect=fail_git_fetch),patch("urllib.request.urlretrieve", side_effect=write_source_zip),- patch("pm.uv", return_value=("uv", dict(os.environ))),patch("tools.skills_sync.sync_skills",return_value={diff --git a/tests/hermes_cli/test_dingtalk_auth.py b/tests/hermes_cli/test_dingtalk_auth.pyindex d3c3b2382b8..a101fe3a35c 100644--- a/tests/hermes_cli/test_dingtalk_auth.py+++ b/tests/hermes_cli/test_dingtalk_auth.py@@ -167,3 +167,31 @@ class TestConfigOverrides:assert mod.REGISTRATION_BASE_URL == "https://oapi.dingtalk.com"[email protected]("succeeds", [True, False])+def test_missing_qrcode_enables_dingtalk_without_switching_the_live_process(monkeypatch, succeeds):+ import pm+ from hermes_cli import dingtalk_auth++ monkeypatch.setitem(sys.modules, "qrcode", None)+ calls = []+ def sync(extras, *, explicit):+ calls.append((extras, explicit))+ if not succeeds:+ raise pm.InstallError("venv", "offline")++ monkeypatch.setattr(pm, "sync_venv", sync)+ assert dingtalk_auth._ensure_qrcode_installed() is False+ assert calls == [(["dingtalk"], True)]+ assert dingtalk_auth.render_qr_to_terminal("https://example.com") is False+ assert sys.modules["qrcode"] is None+++def test_available_qrcode_does_not_install(monkeypatch):+ import pm+ from hermes_cli import dingtalk_auth++ monkeypatch.setitem(sys.modules, "qrcode", MagicMock())+ def forbidden(*args, **kwargs):+ raise AssertionError("installed dependency must not trigger a transaction")+ monkeypatch.setattr(pm, "sync_venv", forbidden)+ assert dingtalk_auth._ensure_qrcode_installed() is Truediff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.pyindex bb56e544493..b61be2c352b 100644--- a/tests/hermes_cli/test_gateway.py+++ b/tests/hermes_cli/test_gateway.py@@ -1331,3 +1331,16 @@ def test_service_commands_refuse_on_sealed_apt_termux(assert exc.value.code == 1out = capsys.readouterr().outassert "Termux" in out+++def test_python_path_reloads_constants_when_update_added_the_helper(tmp_path, monkeypatch):+ import hermes_constants+ from hermes_cli import gateway++ venv = tmp_path / "environment"+ python = hermes_constants.venv_python_path(venv)+ python.parent.mkdir(parents=True)+ python.touch()+ monkeypatch.setattr(gateway, "_detect_venv_dir", lambda: venv)+ monkeypatch.delattr(hermes_constants, "venv_python_path")+ assert gateway.get_python_path() == str(python)diff --git a/tests/hermes_cli/test_install_cua_driver.py b/tests/hermes_cli/test_install_cua_driver.pyindex e65fb870814..a05dd5f9476 100644--- a/tests/hermes_cli/test_install_cua_driver.py+++ b/tests/hermes_cli/test_install_cua_driver.py@@ -30,63 +30,6 @@ from unittest.mock import patchimport pytest-def test_pip_install_drives_pm_uv_with_composed_env(tmp_path, monkeypatch):- """``tools_config_cua._pip_install`` drives uv through ``pm.ensure.uv`` with- ``realize=True, venv=<live venv root>`` and hands the bridge's COMPOSED env- (not a hand-built map) to the subprocess boundary. When pm cannot supply uv,- it degrades to the pre-existing pip ladder."""- import importlib- import subprocess- from hermes_constants import venv_python_path- from hermes_cli import tools_config_cua as cua-- pm_ensure = importlib.import_module("pm.ensure")- selected = tmp_path / "selected-venv"- monkeypatch.setattr("hermes_cli.runtime_paths.selected_venv", lambda root: selected)-- stub_uv = tmp_path / "uv-stub.exe"- stub_uv.write_text("")- composed_env = {"VIRTUAL_ENV": str(selected), "UV_PYTHON": "pm-base-python"}- seen = {}-- def fake_run_text(cmd, **kwargs):- seen["cmd"] = list(cmd)- seen["env"] = kwargs.get("env")- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")-- monkeypatch.setattr(cua, "_run_text", fake_run_text)-- calls = []-- def fake_pm_uv(*, realize, venv):- calls.append({"realize": realize, "venv": venv})- return str(stub_uv), dict(composed_env)-- monkeypatch.setattr(pm_ensure, "uv", fake_pm_uv)- result = cua._pip_install(["cua-driver"])- assert result.returncode == 0- assert calls == [{"realize": True, "venv": selected}]- assert seen["cmd"] == [str(stub_uv), "pip", "install", "--python", str(selected), "cua-driver"]- assert seen["env"] == composed_env-- # uv unavailable: probe --version succeeds via the stub, install goes to pip.- monkeypatch.setattr(pm_ensure, "uv", lambda **kw: (None, {}))- result = cua._pip_install(["cua-driver"])- assert result.returncode == 0- assert seen["cmd"] == [str(venv_python_path(selected)), "-m", "pip", "install", "cua-driver"]-- # A PM policy/provisioning failure must be reported, not bypassed via pip.- from pm.package import InstallError- def refuse_uv(**kwargs):- raise InstallError("python", "not installed and lazy installs are disabled")- monkeypatch.setattr(pm_ensure, "uv", refuse_uv)- seen.clear()- result = cua._pip_install(["cua-driver"])- assert result.returncode != 0- assert "lazy installs are disabled" in result.stderr- assert not seen--def _runtime_manifest(version="0.20.0", *, omit=None):omit = set(omit or ())required = {diff --git a/tests/hermes_cli/test_lazy_refresh_venv_repair.py b/tests/hermes_cli/test_lazy_refresh_venv_repair.pyindex 3458aa4834d..e5fb5f9562d 100644--- a/tests/hermes_cli/test_lazy_refresh_venv_repair.py+++ b/tests/hermes_cli/test_lazy_refresh_venv_repair.py@@ -11,7 +11,7 @@ import pytestdef test_refresh_failure_reports_pm_error(monkeypatch, capsys):import importlib- ensure = importlib.import_module("pm.ensure")+ ensure = importlib.import_module("pm.client")def fail(*args, **kwargs):raise RuntimeError("resolution failed")monkeypatch.setattr(ensure, "sync_venv", fail)@@ -21,32 +21,19 @@ def test_refresh_failure_reports_pm_error(monkeypatch, capsys):def test_refresh_uses_pre_rebuild_snapshot_when_provided(monkeypatch):import importlib- ensure = importlib.import_module("pm.ensure")+ ensure = importlib.import_module("pm.client")calls = []monkeypatch.setattr(ensure, "sync_venv", lambda extras, **kwargs: calls.append((extras, kwargs)))assert m._refresh_active_lazy_features(["telegram"]) is Trueassert calls == [(["telegram"], {"explicit": True})]-def test_capture_active_tool_dependencies_uses_tools_status_probes(monkeypatch):- from hermes_cli import tools_config_post_setup-- monkeypatch.setattr(- tools_config_post_setup,- "_module_installed",- lambda module: module in {"langfuse", "ddgs"},- )-- assert m._capture_active_tool_dependencies() == ["ddgs", "langfuse"]--def test_cmd_update_repairs_before_refreshing_dependency_inputs(tmp_path, monkeypatch):"""The current-checkout repair must bypass PM's matching-stamp shortcut."""from hermes_cli import update_cmd(tmp_path / ".git").mkdir()snapshot = ["platform.telegram"]- tool_snapshot = ["langfuse"]refresh_calls = []class SyncReached(Exception):@@ -65,9 +52,6 @@ def test_cmd_update_repairs_before_refreshing_dependency_inputs(tmp_path, monkeymonkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)monkeypatch.setattr(m, "_capture_active_lazy_features", lambda: snapshot.copy())- monkeypatch.setattr(- m, "_capture_active_tool_dependencies", lambda: tool_snapshot.copy()- )monkeypatch.setattr(m, "_is_windows", lambda: False)monkeypatch.setattr(hermes_cli_main_install_repair, "_is_windows", lambda: False)monkeypatch.setattr(m, "_run_pre_update_backup", lambda args: None)@@ -82,18 +66,8 @@ def test_cmd_update_repairs_before_refreshing_dependency_inputs(tmp_path, monkeyupdate_cmd, "_venv_core_imports_healthy", lambda: (False, "broken"))monkeypatch.setattr(update_cmd, "_write_update_incomplete_marker", lambda: None)- # _restore_active_tool_dependencies retired (pm-clean-audit-49945b1402 item 9).monkeypatch.setattr(m.subprocess, "run", fake_run)import pm- from pm.packages import uv_env as _uv_env-- def fake_uv(**kw):- env = _uv_env()- if kw.get("venv"):- env["VIRTUAL_ENV"] = str(kw["venv"])- return "uv", env-- monkeypatch.setattr(pm, "uv", fake_uv)monkeypatch.setattr(pm, "sync_venv", fake_sync_raises)args = SimpleNamespace(diff --git a/tests/hermes_cli/test_macos_tcc_anchor.py b/tests/hermes_cli/test_macos_tcc_anchor.pyindex 267676397a7..21c93e9e5f9 100644--- a/tests/hermes_cli/test_macos_tcc_anchor.py+++ b/tests/hermes_cli/test_macos_tcc_anchor.py@@ -142,10 +142,9 @@ class TestEnsureTccAnchorNonMacos:class TestEnsureTccAnchor:def test_install_signs_the_anchor_copy(self, tmp_path, monkeypatch):signed = []- import hermes_cli.runtime_repair as runtime_repairmonkeypatch.setattr(- runtime_repair, "_macos_sign_managed_python", lambda p: signed.append(Path(p)) or True+ tcc, "_macos_sign_managed_python", lambda p: signed.append(Path(p)) or True)store_bin = _build_store(tmp_path)root = _build_checkout(tmp_path, store_bin=store_bin)@@ -350,12 +349,6 @@ class TestEnsureTccAnchor:assert marker.read_text(encoding="utf-8") == tcc._marker_value(source)assert not list(venv_bin.glob(".tcc-anchor-source.*"))- def test_store_root_marker_tracks_runtime_repair_constant(self):- # The repair-generation store marker must stay derived from- # runtime_repair's directory constant, not drift as a hardcoded string.- from hermes_cli.runtime_repair import _RUNTIME_DIR_NAME-- assert f"/{_RUNTIME_DIR_NAME}/python/" in tcc._STORE_ROOT_MARKERSclass TestBootGate:diff --git a/tests/hermes_cli/test_memory_dependency_admission.py b/tests/hermes_cli/test_memory_dependency_admission.pyindex 678acf7ace6..ad50c917d90 100644--- a/tests/hermes_cli/test_memory_dependency_admission.py+++ b/tests/hermes_cli/test_memory_dependency_admission.py@@ -60,14 +60,9 @@ def test_setup_requires_dependencies_and_keeps_the_existing_union(tmp_path, monkmonkeypatch.setattr(paths, 'repo_root', lambda: core)ensure = importlib.import_module('pm.ensure')monkeypatch.setattr(ensure, 'lazy_installs_allowed', lambda: True)- from pm.packages import uv_env-- monkeypatch.setattr(ensure, 'uv', lambda **kwargs: (- uv, {**uv_env(kwargs.get('base_env')), 'UV_PYTHON': sys.executable,- 'UV_OFFLINE': '1', 'UV_CACHE_DIR': str(tmp_path / 'cache')},- ))- # Keep admission on the real engine with the offline tool fixture.- monkeypatch.setattr("pm.client.sync_venv", ensure.sync_venv)+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))+ # Keep the public client and real engine; only tool acquisition is injected.+ monkeypatch.setattr("pm.client.is_runtime", lambda: True)ensure.sync_venv(explicit=True)original_environment = selected_venv(core)before = {file: file.read_bytes() for file in (config, other_config, paths.runtime_facts_path())}diff --git a/tests/hermes_cli/test_post_setup_gating.py b/tests/hermes_cli/test_post_setup_gating.pyindex 036e872abde..3f5c0aebf72 100644--- a/tests/hermes_cli/test_post_setup_gating.py+++ b/tests/hermes_cli/test_post_setup_gating.py@@ -57,3 +57,39 @@ class TestPostSetupGate:monkeypatch.setitem(tools_config._POST_SETUP_INSTALLED, "cua_driver", _boom)assert tools_config._post_setup_already_installed("cua_driver") is True++import pytest++[email protected]("key,extra", [+ ("faster_whisper", "stt-whisper"), ("kittentts", "kittentts"),+ ("piper", "piper"), ("ddgs", "ddgs"), ("langfuse", "langfuse"),+])[email protected]("succeeds", [True, False])+def test_python_provider_setup_records_extra_and_preserves_failure(key, extra, succeeds, monkeypatch, capsys):+ import pm+ from hermes_cli import tools_config_post_setup as post, plugins_cmd++ calls = []+ enabled = []+ monkeypatch.setattr(post, "_importable", lambda module: False)+ monkeypatch.setattr(plugins_cmd, "_get_enabled_set", lambda: set())+ monkeypatch.setattr(plugins_cmd, "_save_enabled_set", lambda names: enabled.extend(names))++ def sync(extras, *, explicit):+ calls.append((extras, explicit))+ if not succeeds:+ raise pm.InstallError("venv", "resolution refused")++ monkeypatch.setattr(pm, "sync_venv", sync)+ post._run_post_setup(key)+ assert calls == [([extra], True)]+ output = capsys.readouterr().out+ if succeeds:+ assert "Restart Hermes" in output+ if key == "langfuse":+ assert enabled == ["observability/langfuse"]+ else:+ assert "resolution refused" in output+ assert "Retry with: hermes tools" in output+ assert not enableddiff --git a/tests/hermes_cli/test_runtime_repair.py b/tests/hermes_cli/test_runtime_repair.pydeleted file mode 100644index 29e5b2183d2..00000000000--- a/tests/hermes_cli/test_runtime_repair.py+++ /dev/null@@ -1,1065 +0,0 @@-"""Tests for hermes_cli.runtime_repair — the venv/SQLite repair machinery."""--from __future__ import annotations--import sys-from pathlib import Path-from types import SimpleNamespace-from unittest.mock import MagicMock, patch--import pytest--[email protected](autouse=True)-def _pinned_uv_resolves(monkeypatch):- """repair_vulnerable_runtime() resolves uv itself via pm.ensure.uv;- pin it so no test realizes the pm store for real.-- NOTE: the module object must be reached through sys.modules — both the- string form "pm.ensure.uv" and `import pm.ensure as x` resolve through- the `ensure` FUNCTION re-exported by pm/__init__, which shadows the- submodule attribute of the same name on the package.- """- import importlib-- pm_ensure = importlib.import_module("pm.ensure")- monkeypatch.setattr(pm_ensure, "uv", lambda *a, **k: ("uv", {}))---# ----------------------------------------------------------------------------# Helpers-# -----------------------------------------------------------------------------def _runtime_info(- executable: Path,- sqlite_version: tuple[int, int, int],-):- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- return SQLiteRuntimeInfo(- executable=executable,- base_prefix=executable.parent.parent,- python_version=(3, 11, 15),- sqlite_version=sqlite_version,- sqlite_version_string=".".join(str(part) for part in sqlite_version),- sqlite_source_id=f"source-{sqlite_version}",- )---def _make_runtime_install(- tmp_path: Path,- *,- windows: bool = False,-) -> tuple[Path, Path, Path]:- root = tmp_path / "checkout"- root.mkdir()- (root / "pyproject.toml").write_text("[project]\n", encoding="utf-8")- live = root / "venv"- bin_dir = live / ("Scripts" if windows else "bin")- bin_dir.mkdir(parents=True)- python = bin_dir / ("python.exe" if windows else "python")- python.write_text("live interpreter", encoding="utf-8")- sentinel = live / "sentinel"- sentinel.write_text("live", encoding="utf-8")- return root, live, sentinel---class TestManagedPythonStore:- def test_store_is_checkout_scoped_across_profiles(self, tmp_path, monkeypatch):- from hermes_cli.runtime_repair import managed_python_install_dir-- checkout = tmp_path / "checkout"- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profiles" / "alpha"))- alpha = managed_python_install_dir(checkout)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profiles" / "beta"))- beta = managed_python_install_dir(checkout)-- expected = checkout / ".hermes-runtime" / "python"- assert alpha == expected- assert beta == expected-- def test_environment_is_private_and_sanitized(self, tmp_path):- from hermes_cli.runtime_repair import managed_python_env-- checkout = tmp_path / "checkout"- base_env = {- "KEEP_ME": "yes",- "CONDA_DEFAULT_ENV": "poison",- "CONDA_PREFIX": "/poison/conda",- "UV_PROJECT_ENVIRONMENT": "/poison/project",- "UV_NO_MANAGED_PYTHON": "1",- "UV_PYTHON": "/poison/python",- "UV_PYTHON_DOWNLOADS": "never",- "UV_SYSTEM_PYTHON": "1",- "VIRTUAL_ENV": "/poison/venv",- "PYTHONHOME": "/poison/home",- "PYTHONPATH": "/poison/path",- }-- env = managed_python_env(checkout, base_env=base_env)-- assert env["KEEP_ME"] == "yes"- assert env["UV_MANAGED_PYTHON"] == "1"- assert env["UV_NO_CONFIG"] == "1"- assert env["UV_PYTHON_INSTALL_BIN"] == "0"- assert env["UV_PYTHON_INSTALL_REGISTRY"] == "0"- assert env["UV_PYTHON_INSTALL_DIR"] == str(- checkout / ".hermes-runtime" / "python"- )- for key in (- "CONDA_DEFAULT_ENV",- "CONDA_PREFIX",- "UV_PROJECT_ENVIRONMENT",- "UV_NO_MANAGED_PYTHON",- "UV_PYTHON",- "UV_PYTHON_DOWNLOADS",- "UV_SYSTEM_PYTHON",- "VIRTUAL_ENV",- "PYTHONHOME",- "PYTHONPATH",- ):- assert key not in env- assert base_env["PYTHONHOME"] == "/poison/home"--[email protected](sys.platform == "win32",- reason="POSIX-only: fixtures build the bin/ (not Scripts/) venv layout")-class TestRuntimeRepair:- def test_safe_runtime_is_a_noop(self, tmp_path):- from hermes_cli.runtime_repair import repair_vulnerable_runtime-- root, live, sentinel = _make_runtime_install(tmp_path)- current = _runtime_info(live / "bin" / "python", (3, 53, 1))- with patch(- "hermes_cli.runtime_repair.probe_sqlite_runtime",- return_value=current,- ), \- patch(- "hermes_cli.runtime_repair._install_safe_python_generation"- ) as mock_install:- result = repair_vulnerable_runtime(project_root=root)-- assert result.status == "safe"- assert result.sqlite_before == "3.53.1"- assert result.sqlite_after == "3.53.1"- assert sentinel.read_text(encoding="utf-8") == "live"- assert not (root / ".hermes-runtime").exists()- mock_install.assert_not_called()-- def test_stage_candidate_sync_keeps_uv_project_config(self, tmp_path):- from hermes_cli.runtime_repair import _stage_candidate_venv-- root = tmp_path / "checkout"- root.mkdir()- (root / "uv.lock").write_text("# lock\n", encoding="utf-8")- generation = root / ".hermes-runtime" / "python" / "gen"- python = generation / "bin" / "python"- python.parent.mkdir(parents=True)- python.write_text("py", encoding="utf-8")-- calls = []-- def fake_run(argv, **kwargs):- if argv[1] == "sync":- import subprocess- assert kwargs["stderr"] == subprocess.STDOUT- calls.append((list(argv), kwargs.get("env")))- return MagicMock(returncode=0)-- with patch("hermes_cli.runtime_repair.subprocess.run", side_effect=fake_run), \- patch(- "hermes_cli.runtime_repair._smoke_candidate_venv",- return_value=(True, "", None),- ):- candidate = _stage_candidate_venv(- "uv",- project_root=root,- generation=generation,- python=python,- )-- assert candidate is not None- assert len(calls) == 2- venv_argv, venv_env = calls[0]- sync_argv, sync_env = calls[1]- assert venv_argv[:2] == ["uv", "venv"]- assert "--no-config" in venv_argv- assert venv_env.get("UV_NO_CONFIG") == "1"- assert sync_argv[:2] == ["uv", "sync"]- assert "--locked" in sync_argv- assert "--no-config" not in sync_argv- assert "UV_NO_CONFIG" not in sync_env-- def test_failed_candidate_preserves_live_venv(self, tmp_path):- from hermes_cli.runtime_repair import (- _acquire_repair_lock,- _release_repair_lock,- repair_vulnerable_runtime,- )-- root, live, sentinel = _make_runtime_install(tmp_path)- current = _runtime_info(live / "bin" / "python", (3, 50, 4))- generation = root / ".hermes-runtime" / "python" / "generation-test"- candidate_python = generation / "bin" / "python"- candidate_python.parent.mkdir(parents=True)- candidate_python.write_text("candidate interpreter", encoding="utf-8")- fixed = _runtime_info(candidate_python, (3, 53, 1))-- with patch(- "hermes_cli.runtime_repair.probe_sqlite_runtime",- side_effect=[current, current],- ), \- patch(- "hermes_cli.runtime_repair._install_safe_python_generation",- return_value=(generation, candidate_python, fixed),- ), \- patch(- "hermes_cli.runtime_repair._stage_candidate_venv",- return_value=None,- ):- result = repair_vulnerable_runtime(project_root=root)-- assert result.status == "failed"- assert "replacement environment" in result.detail- assert sentinel.read_text(encoding="utf-8") == "live"- assert (live / "bin" / "python").read_text(encoding="utf-8") == (- "live interpreter"- )- assert not generation.exists()- reacquired = _acquire_repair_lock(root / ".hermes-runtime")- assert reacquired is not None- _release_repair_lock(reacquired)-- def test_safe_runtime_sweeps_old_stale_backups(self, tmp_path):- """A fixed runtime reclaims aged venv.stale.runtime-* leftovers- (issue #73109) but leaves fresh ones (possible in-flight repair)."""- import os- import time as _time-- from hermes_cli.runtime_repair import repair_vulnerable_runtime-- root, live, sentinel = _make_runtime_install(tmp_path)- old_backup = root / f"{live.name}.stale.runtime-1-2-aaaa"- (old_backup / "bin").mkdir(parents=True)- (old_backup / "bin" / "python").write_text("old", encoding="utf-8")- stale_mtime = _time.time() - 7200- os.utime(old_backup, (stale_mtime, stale_mtime))-- fresh_backup = root / f"{live.name}.stale.runtime-9-9-bbbb"- (fresh_backup / "bin").mkdir(parents=True)-- current = _runtime_info(live / "bin" / "python", (3, 53, 1))- with patch(- "hermes_cli.runtime_repair.probe_sqlite_runtime",- return_value=current,- ):- result = repair_vulnerable_runtime(project_root=root)-- assert result.status == "safe"- assert not old_backup.exists(), "aged stale backup must be reclaimed"- assert fresh_backup.exists(), "fresh backup may be an in-flight repair"- assert sentinel.read_text(encoding="utf-8") == "live"-- def test_successful_repair_removes_parked_backup(self, tmp_path):- """After a successful cutover the parked venv is removed instead of- leaking ~1 GB at the project root forever (issue #73109)."""- from hermes_cli.runtime_repair import repair_vulnerable_runtime-- root, live, sentinel = _make_runtime_install(tmp_path)- current = _runtime_info(live / "bin" / "python", (3, 50, 4))- generation = root / ".hermes-runtime" / "python" / "generation-test"- candidate_python = generation / "bin" / "python"- candidate_python.parent.mkdir(parents=True)- candidate_python.write_text("candidate interpreter", encoding="utf-8")- fixed = _runtime_info(candidate_python, (3, 53, 1))- candidate_venv = root / ".hermes-runtime" / "venv-candidate"- (candidate_venv / "bin").mkdir(parents=True)- (candidate_venv / "bin" / "python").write_text(- "candidate venv interpreter", encoding="utf-8"- )-- with patch(- "hermes_cli.runtime_repair.probe_sqlite_runtime",- side_effect=[current, current],- ), \- patch(- "hermes_cli.runtime_repair._install_safe_python_generation",- return_value=(generation, candidate_python, fixed),- ), \- patch(- "hermes_cli.runtime_repair._stage_candidate_venv",- return_value=candidate_venv,- ), \- patch(- "hermes_cli.runtime_repair._smoke_candidate_venv",- return_value=(True, "", fixed),- ):- result = repair_vulnerable_runtime(project_root=root)-- assert result.status == "repaired"- assert result.backup_venv is not None- assert not result.backup_venv.exists(), (- "parked venv must be removed after a successful repair"- )- leftovers = list(root.glob(f"{live.name}.stale.runtime-*"))- assert leftovers == [], f"no stale markers may remain: {leftovers}"---class TestRuntimeCutover:- def test_os_lock_blocks_concurrent_repair_and_releases(self, tmp_path):- from hermes_cli.runtime_repair import _acquire_repair_lock, _release_repair_lock-- runtime_root = tmp_path / ".hermes-runtime"- first = _acquire_repair_lock(runtime_root)- assert first is not None- assert _acquire_repair_lock(runtime_root) is None-- _release_repair_lock(first)- second = _acquire_repair_lock(runtime_root)- assert second is not None- _release_repair_lock(second)-- def test_post_swap_smoke_failure_rolls_back_live_venv(self, tmp_path):- from hermes_cli.runtime_repair import _cut_over_candidate-- root, live, sentinel = _make_runtime_install(tmp_path)- runtime_root = root / ".hermes-runtime"- candidate = runtime_root / "venv-candidate-test"- candidate.mkdir(parents=True)- (candidate / "sentinel").write_text("candidate", encoding="utf-8")- rejected_info = _runtime_info(candidate / "bin" / "python", (3, 50, 4))-- with patch(- "hermes_cli.runtime_repair._smoke_candidate_venv",- return_value=(False, "core import smoke failed", rejected_info),- ):- ok, backup, info, detail = _cut_over_candidate(- candidate,- project_root=root,- )-- assert ok is False- assert backup is None- assert info == rejected_info- assert "post-cutover smoke failed" in detail- assert sentinel.read_text(encoding="utf-8") == "live"- assert (live / "bin" / "python").exists() or (- live / "Scripts" / "python.exe"- ).exists()- assert not candidate.exists()- assert not list(runtime_root.glob("venv-rejected-*"))---class TestRuntimeRequestMinorLine:- """The repair must request the CPython minor line, not the exact patch.-- Real-world constraint (verified live, July 2026): every published- python-build-standalone artifact for 3.11.14 links vulnerable SQLite- 3.50.4 — even with --reinstall. The fixed SQLite (3.53.1) only exists- from 3.11.15. An exact-patch pin makes the repair permanently- impossible on such installs.- """-- def test_requests_minor_line(self):- from hermes_cli.runtime_repair import _runtime_request-- info = _runtime_info(Path("/venv/bin/python"), (3, 50, 4))- assert _runtime_request(info) == "3.11"-- @staticmethod- def _run_generation(tmp_path, monkeypatch, current_version, candidate_version):- """Drive _install_safe_python_generation with fakes; return result."""- import hermes_cli.runtime_repair as runtime_repair- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- state = {}-- def fake_run(cmd, **kwargs):- if "install" in cmd:- state["generation"] = Path(kwargs["env"]["UV_PYTHON_INSTALL_DIR"])- return SimpleNamespace(returncode=0, stdout="", stderr="")- # uv python find → a path inside the generation dir- python = state["generation"] / "cpython" / "bin" / "python3"- python.parent.mkdir(parents=True, exist_ok=True)- python.touch()- return SimpleNamespace(returncode=0, stdout=str(python), stderr="")-- def fake_probe(python, **kwargs):- return SQLiteRuntimeInfo(- executable=Path(python),- base_prefix=Path(python).parent.parent,- python_version=candidate_version,- sqlite_version=(3, 53, 1),- sqlite_version_string="3.53.1",- sqlite_source_id="fixed",- )-- current = SQLiteRuntimeInfo(- executable=Path("/venv/bin/python"),- base_prefix=Path("/venv"),- python_version=current_version,- sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4",- sqlite_source_id="old",- )- monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)- monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe)- return runtime_repair._install_safe_python_generation(- "uv", project_root=tmp_path, current=current- )-- def test_accepts_newer_patch_same_minor(self, tmp_path, monkeypatch):- result = self._run_generation(- tmp_path, monkeypatch, (3, 11, 14), (3, 11, 15)- )- assert result is not None- _, _, candidate = result- assert candidate.python_version == (3, 11, 15)---class TestPatchRetryOnVulnerableCandidate:- """Regression tests for issue #71250: when the bare minor-line request- (e.g. "3.11") resolves to a candidate that's still vulnerable -- because- uv's default resolution for that host picked an older cached/indexed- patch even though a newer non-vulnerable one is available -- the- provisioner must query the available patches and retry with explicit- newer versions, rather than giving up after the first attempt.- """-- @staticmethod- def _versioned_probe_run(vulnerable_versions, sqlite_fixed=(3, 53, 1)):- """Build a fake subprocess.run where the install/find/probe cycle- resolves to a DIFFERENT candidate Python version depending on which- exact version string was requested, so retries with explicit- patches can be distinguished from the initial bare-minor attempt."""- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- state = {"requested": None}-- def fake_run(cmd, **kwargs):- if "install" in cmd:- # cmd = [uv, "python", "install", <request>, ...]- state["requested"] = cmd[3]- state["generation"] = Path(kwargs["env"]["UV_PYTHON_INSTALL_DIR"])- return SimpleNamespace(returncode=0, stdout="", stderr="")- if "list" in cmd:- return SimpleNamespace(returncode=0, stdout="", stderr="")- # uv python find → a path inside the generation dir, tagged with- # which request produced it so the probe below can look it up.- python = state["generation"] / "cpython" / "bin" / "python3"- python.parent.mkdir(parents=True, exist_ok=True)- python.write_text(state["requested"] or "")- return SimpleNamespace(returncode=0, stdout=str(python), stderr="")-- def fake_probe(python, **kwargs):- requested = Path(python).read_text()- # Bare minor request ("3.11") always resolves to the FIRST- # (worst-case / already-known-vulnerable) version in the list.- if requested in vulnerable_versions or requested == "3.11":- version = (3, 11, 14) if requested == "3.11" else tuple(- int(p) for p in requested.split(".")- )- return SQLiteRuntimeInfo(- executable=Path(python), base_prefix=Path(python).parent.parent,- python_version=version, sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="vulnerable",- )- version = tuple(int(p) for p in requested.split("."))- return SQLiteRuntimeInfo(- executable=Path(python), base_prefix=Path(python).parent.parent,- python_version=version, sqlite_version=sqlite_fixed,- sqlite_version_string=".".join(str(p) for p in sqlite_fixed),- sqlite_source_id="fixed",- )-- return fake_run, fake_probe-- def _run(self, tmp_path, monkeypatch, *, vulnerable_versions, patch_list):- import hermes_cli.runtime_repair as runtime_repair- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- fake_run, fake_probe = self._versioned_probe_run(vulnerable_versions)- current = SQLiteRuntimeInfo(- executable=Path("/venv/bin/python"), base_prefix=Path("/venv"),- python_version=(3, 11, 14), sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="old",- )- monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)- monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe)- monkeypatch.setattr(- runtime_repair, "_list_available_patches", lambda *a, **kw: patch_list- )- return runtime_repair._install_safe_python_generation(- "uv", project_root=tmp_path, current=current- )-- def test_retries_and_succeeds_with_explicit_newer_patch(self, tmp_path, monkeypatch):- """The exact #71250 scenario: bare '3.11' resolves to vulnerable- 3.11.14, but 3.11.15 (fixed) is available and gets tried explicitly."""- result = self._run(- tmp_path, monkeypatch,- vulnerable_versions={"3.11"},- patch_list=[(3, 11, 15), (3, 11, 14), (3, 11, 13), (3, 11, 12)],- )- assert result is not None, "Must recover via explicit-patch retry"- _, _, candidate = result- assert candidate.python_version == (3, 11, 15)- assert not candidate.wal_reset_vulnerable-- def test_retry_is_bounded_by_max_retries_constant(self, tmp_path, monkeypatch):- """A very long patch list must not result in unbounded retries -- capped at- _MAX_PATCH_RETRIES attempts. After exhausting same-minor retries the- fallback tries the next minor line, which may succeed."""- import hermes_cli.runtime_repair as runtime_repair-- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- current = SQLiteRuntimeInfo(- executable=Path("/venv/bin/python"), base_prefix=Path("/venv"),- python_version=(3, 11, 14), sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="old",- )- # 20 vulnerable patches -- far more than _MAX_PATCH_RETRIES.- huge_patch_list = [(3, 11, v) for v in range(30, 10, -1)]- all_vulnerable = {f"3.11.{v}" for v in range(30, 10, -1)} | {"3.11"}- fake_run2, fake_probe2 = self._versioned_probe_run(all_vulnerable)-- install_calls = []-- def counting_fake_run(cmd, **kwargs):- if "install" in cmd:- install_calls.append(cmd[3])- return fake_run2(cmd, **kwargs)-- monkeypatch.setattr(runtime_repair.subprocess, "run", counting_fake_run)- monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe2)- monkeypatch.setattr(- runtime_repair, "_list_available_patches", lambda *a, **kw: huge_patch_list- )- result = runtime_repair._install_safe_python_generation(- "uv", project_root=tmp_path, current=current- )- # The same-minor retries are bounded, but the minor-line fallback- # (3.11 → 3.12) succeeds because the mock returns a fixed build.- assert result is not None, (- "Minor-line fallback should find a fixed 3.12 build"- )- # 1 initial bare-minor attempt + at most _MAX_PATCH_RETRIES retries.- assert runtime_repair._MAX_PATCH_RETRIES <= 5, (- "sanity: constant should stay small since each attempt is a "- "real download+install+probe cycle"- )- same_minor_explicit = [- call for call in install_calls if call.startswith("3.11.")- ]- assert len(same_minor_explicit) <= runtime_repair._MAX_PATCH_RETRIES, (- f"same-minor explicit retries must be capped: {same_minor_explicit}"- )- assert install_calls[0] == "3.11"- # The run ends the moment the bare next-minor fallback succeeds.- assert install_calls[-1] == "3.12"- assert install_calls.count("3.12") == 1---class TestMinorLineFallForward:- """Regression tests for issue #76106: when EVERY build on the current- minor line (e.g. all of 3.11 on Windows) links a vulnerable SQLite,- the provisioner must fall forward to the next supported minor line- (3.12, then 3.13) -- first via a bare minor request, then via explicit- patches on that line -- instead of leaving the user stuck on every- `hermes update` with no path to a fixed runtime.- """-- @staticmethod- def _mapped_run(resolutions, fixed_versions, install_calls):- """Fake subprocess.run/probe pair driven by explicit tables:-- - *resolutions*: request string -> python_version tuple the probe- reports for that request (bare minors resolve like uv would).- - *fixed_versions*: set of version tuples that link FIXED SQLite;- everything else probes as vulnerable 3.50.4.- - *install_calls*: list collecting each `uv python install` request,- in order, so tests can assert the actual request sequence.- """- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- state: dict = {"requested": None}-- def fake_run(cmd, **kwargs):- if "install" in cmd:- # cmd = [uv, "python", "install", <request>, ...]- state["requested"] = cmd[3]- state["generation"] = Path(kwargs["env"]["UV_PYTHON_INSTALL_DIR"])- install_calls.append(cmd[3])- return SimpleNamespace(returncode=0, stdout="", stderr="")- if "list" in cmd:- return SimpleNamespace(returncode=0, stdout="", stderr="")- # uv python find → a path inside the generation dir, tagged with- # the request that produced it so the probe can look it up.- python = state["generation"] / "cpython" / "bin" / "python3"- python.parent.mkdir(parents=True, exist_ok=True)- python.write_text(state["requested"] or "")- return SimpleNamespace(returncode=0, stdout=str(python), stderr="")-- def fake_probe(python, **kwargs):- requested = Path(python).read_text()- version = resolutions[requested]- if version in fixed_versions:- return SQLiteRuntimeInfo(- executable=Path(python),- base_prefix=Path(python).parent.parent,- python_version=version, sqlite_version=(3, 53, 1),- sqlite_version_string="3.53.1", sqlite_source_id="fixed",- )- return SQLiteRuntimeInfo(- executable=Path(python),- base_prefix=Path(python).parent.parent,- python_version=version, sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="vulnerable",- )-- return fake_run, fake_probe-- @staticmethod- def _current_3_11_14():- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- return SQLiteRuntimeInfo(- executable=Path("/venv/bin/python"), base_prefix=Path("/venv"),- python_version=(3, 11, 14), sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="old",- )-- def test_explicit_patch_fallback_when_bare_next_minor_is_vulnerable(- self, tmp_path, monkeypatch- ):- """The review-gap scenario from #76252: the bare '3.12' request- resolves to a VULNERABLE 3.12 build, but an explicit 3.12 patch- links fixed SQLite -- the `_list_available_patches(..., '3.12', ...)`- fallback branch must run, skip the already-tried bare resolution,- and succeed via the explicit patch."""- import hermes_cli.runtime_repair as runtime_repair-- install_calls = []- fake_run, fake_probe = self._mapped_run(- resolutions={- "3.11": (3, 11, 14), # bare current minor: vulnerable- "3.12": (3, 12, 11), # bare next minor: ALSO vulnerable- "3.12.10": (3, 12, 10), # explicit patch: fixed- },- fixed_versions={(3, 12, 10)},- install_calls=install_calls,- )- patch_lists = {- # No newer 3.11 patch exists (the Windows #76106 reality).- "3.11": [(3, 11, 14), (3, 11, 13)],- # Newest 3.12 is the same build the bare request resolved to.- "3.12": [(3, 12, 11), (3, 12, 10)],- }- monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)- monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe)- monkeypatch.setattr(- runtime_repair, "_list_available_patches",- lambda uv_bin, minor, **kw: patch_lists[minor],- )-- result = runtime_repair._install_safe_python_generation(- "uv", project_root=tmp_path, current=self._current_3_11_14()- )- assert result is not None, (- "Explicit-patch fallback on the next minor line must recover"- )- _, _, candidate = result- assert candidate.python_version == (3, 12, 10)- assert not candidate.wal_reset_vulnerable- # The actual uv-install request sequence: bare current minor, then- # bare next minor, then STRAIGHT to the fixed explicit patch --- # 3.12.11 must NOT be re-requested explicitly, because the bare- # '3.12' attempt already resolved to (and rejected) that build.- assert install_calls == ["3.11", "3.12", "3.12.10"]-- def test_returns_none_with_bounded_attempts_when_all_minors_exhausted(- self, tmp_path, monkeypatch- ):- """When every build on every supported minor line (3.11-3.14) is- vulnerable, the provisioner must give up with None -- and the total- install workload must stay bounded by _MAX_PATCH_RETRIES per line."""- import hermes_cli.runtime_repair as runtime_repair-- install_calls = []- resolutions = {"3.11": (3, 11, 14), "3.12": (3, 12, 30), "3.13": (3, 13, 30), "3.14": (3, 14, 30)}- patch_lists = {}- for minor in (11, 12, 13, 14):- versions = [(3, minor, v) for v in range(30, 10, -1)] # 20 patches- patch_lists[f"3.{minor}"] = versions- for version in versions:- resolutions[".".join(str(p) for p in version)] = version-- fake_run, fake_probe = self._mapped_run(- resolutions=resolutions, fixed_versions=set(),- install_calls=install_calls,- )- monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)- monkeypatch.setattr(runtime_repair, "probe_sqlite_runtime", fake_probe)- monkeypatch.setattr(- runtime_repair, "_list_available_patches",- lambda uv_bin, minor, **kw: patch_lists[minor],- )-- result = runtime_repair._install_safe_python_generation(- "uv", project_root=tmp_path, current=self._current_3_11_14()- )- assert result is None, "Nothing fixed anywhere: must give up cleanly"-- cap = runtime_repair._MAX_PATCH_RETRIES- # Per line: one bare request + at most _MAX_PATCH_RETRIES explicit- # patches; four lines total (3.11, 3.12, 3.13, 3.14) and nothing beyond- # 3.14 (requires-python is <3.15).- assert install_calls.count("3.11") == 1- assert install_calls.count("3.12") == 1- assert install_calls.count("3.13") == 1- assert install_calls.count("3.14") == 1- assert not any(call.startswith("3.15") for call in install_calls)- for minor in (11, 12, 13, 14):- explicit = [- call for call in install_calls- if call.startswith(f"3.{minor}.")- ]- assert len(explicit) <= cap, (- f"3.{minor} explicit retries must be capped at {cap}: {explicit}"- )- assert len(install_calls) <= 4 * (1 + cap)---class TestListAvailablePatches:- """Direct unit tests for _list_available_patches()'s JSON parsing,- against realistic `uv python list --all-versions --output-format json`- output (captured from a real uv 0.11.7 invocation)."""-- SAMPLE_OUTPUT = (- '[{"key":"cpython-3.11.15-linux-x86_64-gnu","version":"3.11.15",'- '"version_parts":{"major":3,"minor":11,"patch":15},"path":null,'- '"symlink":null,"url":"https://example/cpython-3.11.15.tar.gz",'- '"os":"linux","variant":"default","implementation":"cpython",'- '"arch":"x86_64","libc":"gnu"},'- '{"key":"cpython-3.11.14-linux-x86_64-gnu","version":"3.11.14",'- '"version_parts":{"major":3,"minor":11,"patch":14},"path":null,'- '"symlink":null,"url":"https://example/cpython-3.11.14.tar.gz",'- '"os":"linux","variant":"default","implementation":"cpython",'- '"arch":"x86_64","libc":"gnu"},'- '{"key":"pypy-3.11.15-linux-x86_64-gnu","version":"3.11.15",'- '"version_parts":{"major":3,"minor":11,"patch":15},"path":null,'- '"symlink":null,"url":"https://example/pypy-3.11.15.tar.gz",'- '"os":"linux","variant":"default","implementation":"pypy",'- '"arch":"x86_64","libc":"gnu"}]'- )-- def test_parses_and_sorts_newest_first(self, tmp_path, monkeypatch):- import hermes_cli.runtime_repair as runtime_repair-- def fake_run(cmd, **kwargs):- return SimpleNamespace(returncode=0, stdout=self.SAMPLE_OUTPUT, stderr="")-- monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)- result = runtime_repair._list_available_patches(- "uv", "3.11", cwd=tmp_path, env={}- )- assert result == [(3, 11, 15), (3, 11, 14)]-- def test_subprocess_exception_returns_empty_list(self, tmp_path, monkeypatch):- import hermes_cli.runtime_repair as runtime_repair-- def fake_run(cmd, **kwargs):- raise OSError("uv binary not found")-- monkeypatch.setattr(runtime_repair.subprocess, "run", fake_run)- assert runtime_repair._list_available_patches("uv", "3.11", cwd=tmp_path, env={}) == []---class TestPmUvResolution:- """The repair resolves uv through pm — never a foreign uv, never its- own acquisition (the retired managed_uv half)."""-- def test_pm_uv_unavailable_skips_without_touching_the_venv(- self, tmp_path, monkeypatch- ):- from hermes_cli.runtime_repair import repair_vulnerable_runtime-- root, live, sentinel = _make_runtime_install(- tmp_path, windows=sys.platform == "win32"- )- import importlib-- pm_ensure = importlib.import_module("pm.ensure")- monkeypatch.setattr(pm_ensure, "uv", lambda *a, **k: (None, {}))-- result = repair_vulnerable_runtime(project_root=root)-- assert result.status == "skipped"- assert "pinned uv unavailable" in result.detail- assert sentinel.read_text(encoding="utf-8") == "live"---class TestDefaultLiveVenv:- """_default_live_venv() must cover BOTH install layouts (venv/ and .venv/).-- Historically repair hardcoded venv/, so uv-default/.venv checkouts got- 'not-applicable' on every hermes update and stayed on journal_mode=DELETE- (2,600x slower state.db appends) while the WAL warning promised repair.- """-- def _checkout(self, tmp_path, *dirs):- windows = sys.platform == "win32"- root = tmp_path / "checkout"- root.mkdir()- (root / "pyproject.toml").write_text("[project]\n", encoding="utf-8")- for d in dirs:- bin_dir = root / d / ("Scripts" if windows else "bin")- bin_dir.mkdir(parents=True)- (bin_dir / ("python.exe" if windows else "python")).write_text(- "py", encoding="utf-8"- )- return root-- @pytest.mark.platforms("linux")- def test_dot_venv_only_is_targeted(self, tmp_path):- from hermes_cli.runtime_repair import _default_live_venv-- root = self._checkout(tmp_path, ".venv")- assert _default_live_venv(root) == root / ".venv"-- def test_managed_venv_takes_precedence(self, tmp_path):- from hermes_cli.runtime_repair import _default_live_venv-- root = self._checkout(tmp_path, "venv", ".venv")- assert _default_live_venv(root) == root / "venv"-- def test_neither_layout_keeps_not_applicable(self, tmp_path):- from hermes_cli.runtime_repair import (- _default_live_venv,- repair_vulnerable_runtime,- )-- root = self._checkout(tmp_path)- # Neither venv nor .venv has an interpreter -> repair is not applicable.- assert _default_live_venv(root) == root / "venv"- result = repair_vulnerable_runtime(project_root=root)- assert result.status == "not-applicable"---class TestVenvPythonUpdateBoundary:- """``_venv_python`` must survive a hermes_constants predating its symbol.-- ``hermes update`` imports hermes_constants from the OLD checkout, ``git- pull`` replaces that file, and the freshly-pulled runtime_repair then runs its- lazy ``from hermes_constants import venv_python_path`` against the module- object already cached in ``sys.modules``. That cached module has no such- symbol, so the import raises — while naming the NEW file on disk, which- plainly contains it, which is what made the error so confusing:-- cannot import name 'venv_python_path' from 'hermes_constants'- (~/.hermes/hermes-agent/hermes_constants.py)-- It aborted the managed-Python runtime repair on the first update from any- release older than the symbol. Same class as the ``ensure_uv()`` arity skew- documented on ``_UvResult``.- """-- def test_recovers_when_the_cached_module_predates_the_symbol(self, monkeypatch):- import hermes_constants-- from hermes_cli.runtime_repair import _venv_python-- # The stale in-memory module: the symbol the new code wants is absent,- # exactly as on an install that booted the pre-upgrade checkout. The- # file on disk is the current one, so a reload recovers the real helper.- monkeypatch.delattr(hermes_constants, "venv_python_path", raising=False)-- # Host-native: the subject is the reload-recovery seam, not the- # bin/Scripts mapping — assert whatever layout the real host resolves.- expected = Path("/opt/hermes/venv/Scripts/python.exe") \- if sys.platform == "win32" else Path("/opt/hermes/venv/bin/python")- assert _venv_python(Path("/opt/hermes/venv")) == expected-- def test_recovery_uses_the_shared_helper_not_a_second_copy(self, monkeypatch):- """The reload must resolve through hermes_constants, not open-code it.-- Hand-rolling `Scripts`/`bin` here is what #76105 deduped away and what- `test_no_open_coded_venv_layout_remains_in_hermes_cli` bans.- """- import hermes_constants-- from hermes_cli.runtime_repair import _venv_python-- monkeypatch.delattr(hermes_constants, "venv_python_path", raising=False)-- sentinel = Path("/sentinel/from/shared/helper")- real_reload = __import__("importlib").reload-- def _reload_with_marker(module):- fresh = real_reload(module)- monkeypatch.setattr(- fresh, "venv_python_path", lambda *a, **k: sentinel, raising=False- )- return fresh-- monkeypatch.setattr("importlib.reload", _reload_with_marker)- assert _venv_python(Path("/opt/hermes/venv")) == sentinel-- def test_uses_the_real_helper_when_it_is_importable(self, monkeypatch):- """The normal path never reloads — recovery stays a fallback."""- from hermes_cli.runtime_repair import _venv_python-- def _no_reload(module): # pragma: no cover - must not run- raise AssertionError("reload must not run when the import succeeds")-- monkeypatch.setattr("importlib.reload", _no_reload)-- expected = Path("/opt/hermes/venv/Scripts/python.exe") \- if sys.platform == "win32" else Path("/opt/hermes/venv/bin/python")- assert _venv_python(Path("/opt/hermes/venv")) == expected----class TestWindowsRuntimeSelfLock:- """The repair pre-flight must see the ONE holder the generic scan hides:- the updater itself (#93032).-- A CLI ``hermes update`` runs from the venv's own python, and- ``_detect_venv_python_processes`` excludes the calling process and its- ancestors on purpose (correct for the dependency-sync path). For the- whole-venv park rename that exemption is fatal on Windows: a directory- containing an executable mapped by a running process cannot be renamed,- so the cutover retries burn out against a lock that cannot be released- while the updater lives. The repair must detect the self-lock and defer- with honest guidance instead of provisioning a candidate for a doomed- rename.- """-- def _checkout(self, tmp_path):- root, live, sentinel = _make_runtime_install(tmp_path)- # Windows-layout interpreter so sys.executable can point inside the- # live venv on any host (the detector only string-compares paths).- scripts_python = live / "Scripts" / "python.exe"- scripts_python.parent.mkdir(parents=True, exist_ok=True)- scripts_python.write_text("live interpreter", encoding="utf-8")- return root, live, sentinel, scripts_python-- def test_self_lock_defers_repair_before_provisioning(- self, tmp_path, monkeypatch, capsys- ):- """Regression for #93032: pre-fix, the repair walks straight into the- doomed rename (provisioning + cutover) whenever the updater itself- maps the live venv; the park then fails with WinError 5 and the user- gets the misleading 'next update will retry' message forever."""- from hermes_cli import runtime_repair as repair_mod- from hermes_cli.runtime_repair import repair_vulnerable_runtime-- root, live, sentinel, scripts_python = self._checkout(tmp_path)- current = _runtime_info(scripts_python, (3, 50, 4))- monkeypatch.setattr(repair_mod.platform, "system", lambda: "Windows")- monkeypatch.setattr(sys, "executable", str(scripts_python))-- with patch(- "hermes_cli.runtime_repair._windows_runtime_holders",- return_value=(False, ""),- ), \- patch(- "hermes_cli.runtime_repair.probe_sqlite_runtime",- return_value=current,- ), \- patch(- "hermes_cli.runtime_repair._install_safe_python_generation"- ) as mock_install:- result = repair_vulnerable_runtime(project_root=root)-- assert result.status == "skipped"- assert "live venv" in result.detail- assert mock_install.call_count == 0, (- "a self-locked updater must not provision a candidate it can "- "never cut over"- )- assert sentinel.read_text(encoding="utf-8") == "live"- assert not (root / ".hermes-runtime").exists()-- out = capsys.readouterr().out- assert "SQLite runtime repair deferred" in out- assert "will retry" not in out, (- "the structural self-lock must not promise that retrying helps"- )- assert "outside" in out, "the deferral must point at an escape hatch"-- def test_non_self_locked_repair_proceeds(self, tmp_path, monkeypatch):- """The guard must fail OPEN when the updater runs from outside the- venv — an always-firing deferral would recreate the never-converging- loop this fix removes (#86735 class)."""- from hermes_cli import runtime_repair as repair_mod- from hermes_cli.runtime_repair import repair_vulnerable_runtime-- root, live, sentinel, scripts_python = self._checkout(tmp_path)- current = _runtime_info(scripts_python, (3, 50, 4))- monkeypatch.setattr(repair_mod.platform, "system", lambda: "Windows")- monkeypatch.setattr(- sys, "executable", str(tmp_path / "outside" / "python.exe")- )-- with patch(- "hermes_cli.runtime_repair._windows_runtime_holders",- return_value=(False, ""),- ), \- patch(- "hermes_cli.runtime_repair.probe_sqlite_runtime",- return_value=current,- ), \- patch(- "hermes_cli.runtime_repair._install_safe_python_generation",- return_value=None,- ) as mock_install:- result = repair_vulnerable_runtime(project_root=root)-- assert result.status == "failed"- assert "provision" in result.detail- mock_install.assert_called_once()- assert sentinel.read_text(encoding="utf-8") == "live"-- def test_self_lock_is_a_noop_off_windows(self, tmp_path, monkeypatch):- """POSIX renames work while the updater maps the venv, so the guard- must stay Windows-only."""- from hermes_cli import runtime_repair as repair_mod-- root, live, sentinel, scripts_python = self._checkout(tmp_path)- monkeypatch.setattr(repair_mod.platform, "system", lambda: "Linux")- monkeypatch.setattr(sys, "executable", str(scripts_python))-- locked, detail = repair_mod._windows_runtime_self_lock(live)- assert (locked, detail) == (False, "")-- def test_venv_launcher_ancestor_is_a_self_lock(self, tmp_path, monkeypatch):- r"""The venv\Scripts\hermes.exe shim stays mapped while it waits for- this child — an ancestor running from the venv blocks the rename too."""- from hermes_cli import runtime_repair as repair_mod-- root, live, sentinel, scripts_python = self._checkout(tmp_path)- monkeypatch.setattr(repair_mod.platform, "system", lambda: "Windows")- monkeypatch.setattr(- sys, "executable", str(tmp_path / "outside" / "python.exe")- )-- class _FakeProc:- def __init__(self, pid, exe):- self.pid = pid- self._exe = exe-- def exe(self):- return self._exe-- fake_psutil = SimpleNamespace(- Process=lambda: SimpleNamespace(- parents=lambda: [_FakeProc(999, str(scripts_python))],- ),- )- with patch.dict(sys.modules, {"psutil": fake_psutil}):- locked, detail = repair_mod._windows_runtime_self_lock(live)-- assert locked- assert "999" in detaildiff --git a/tests/hermes_cli/test_setup.py b/tests/hermes_cli/test_setup.pyindex fef3348d00f..5f2c45b126a 100644--- a/tests/hermes_cli/test_setup.py+++ b/tests/hermes_cli/test_setup.py@@ -4,8 +4,11 @@ import osimport jsonimport types+import pytest+from hermes_cli.config import load_config, save_config+import hermes_cli.main # bootstrap before per-test filesystem guardsfrom hermes_cli import setup as setup_modfrom hermes_cli.setup import setup_model_provider@@ -250,3 +253,48 @@ def test_vercel_setup_prefills_project_and_team_from_link_file(tmp_path, monkeypassert os.environ["VERCEL_TEAM_ID"] == "linked-team"assert defaults[" Vercel project ID"] == "linked-project"assert defaults[" Vercel team ID"] == "linked-team"++[email protected]("extra", ["neutts", "kittentts", "modal", "daytona", "vercel"])[email protected]("succeeds", [True, False])+def test_python_setup_uses_declared_extras_and_reports_restart(extra, succeeds, monkeypatch, capsys):+ import pm+ from hermes_cli import setup_terminal, setup_tts++ calls = []+ def sync(extras, *, explicit):+ calls.append((extras, explicit))+ if not succeeds:+ raise pm.InstallError("venv", "resolution refused")++ monkeypatch.setattr(pm, "sync_venv", sync)+ monkeypatch.setattr("pm.extras.extra_supported", lambda name: True)+ monkeypatch.setitem(sys.modules, extra, None)+ monkeypatch.setattr(setup_tts.shutil, "which", lambda name: "/usr/bin/espeak-ng")+ if extra in {"neutts", "kittentts"}:+ assert getattr(setup_tts, f"_install_{extra}_deps")() is succeeds+ else:+ setup_terminal._ensure_sdk(extra)+ assert calls == [([extra], True)]+ output = capsys.readouterr().out+ if succeeds:+ assert "Restart Hermes" in output+ assert sys.modules[extra] is None # installing never activates in this process+ else:+ assert "resolution refused" in output+ assert "Retry with: hermes setup" in output+ assert "installed." not in output++[email protected]("extra", ["neutts", "kittentts"])+def test_unsupported_tts_selection_is_retained_without_installing(extra, monkeypatch, capsys):+ from hermes_cli import setup_tts++ monkeypatch.setattr("pm.extras.extra_supported", lambda name: False)+ def forbidden(*args, **kwargs):+ raise AssertionError("unsupported engine must not install system or Python packages")+ monkeypatch.setattr(setup_mod, "prompt_yes_no", forbidden)+ monkeypatch.setattr("pm.sync_venv", forbidden)+ assert setup_tts._tts_local_install_step(extra) == extra+ output = capsys.readouterr().out+ assert "not supported" in output and "selection is saved" in outputdiff --git a/tests/hermes_cli/test_tools_config.py b/tests/hermes_cli/test_tools_config.pyindex 9c1fed07461..eb915ead80b 100644--- a/tests/hermes_cli/test_tools_config.py+++ b/tests/hermes_cli/test_tools_config.py@@ -681,8 +681,7 @@ class TestBrowserUseCliInstalledForAllNonCamofoxBackends:def test_ensure_helper_always_delegates_to_install_cli(self):"""MANAGED-FIRST: a browser-use on PATH must not short-circuit the- helper — install_cli() owns the managed-copy check and provisions- $HERMES_HOME/bin when only side installs exist."""+ helper — install_cli() owns PM's isolated tool environment selection."""with patch("hermes_cli.tools_config_post_setup.shutil.which", return_value="/usr/bin/browser-use"), patch(@@ -694,20 +693,22 @@ class TestBrowserUseCliInstalledForAllNonCamofoxBackends:_ensure_browser_use_cli()install.assert_called_once()- def test_ensure_helper_install_failure_is_non_fatal(self):- """A failed install must warn and fall back, never raise — the- uvx zero-install path and the built-in tools remain available."""+ def test_ensure_helper_install_failure_is_non_fatal(self, capsys):+ """A failed install names the PM retry, never an ambient uv fallback."""from hermes_cli.tools_config import _ensure_browser_use_cliwith patch("hermes_cli.tools_config_post_setup.shutil.which", return_value=None), patch("tools.browser_use_cli.install_cli",- return_value=(False, "`uv tool install browser-use` failed:\nboom"),+ return_value=(False, "PM browser-use install failed:\nboom"),), patch("hermes_cli.tools_config_post_setup._print_warning") as warn:_ensure_browser_use_cli() # must not raiseassert any("failed" in c.args[0] for c in warn.call_args_list)+ output = capsys.readouterr().out+ assert "hermes tools post-setup browser_use_cli" in output+ assert "uvx" not in output and "uv tool" not in outputclass TestImagegenBackendRegistry:diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.pyindex 10c24f024b2..294521de0de 100644--- a/tests/hermes_cli/test_update_autostash.py+++ b/tests/hermes_cli/test_update_autostash.py@@ -10,20 +10,6 @@ from hermes_cli import main as hermes_mainfrom hermes_cli import update_cmd-# ----------------------------------------------------------------------------# Managed-uv compatibility for tests that patch shutil.which-# ----------------------------------------------------------------------------# The production code resolves uv through ``pm.uv()`` instead of-# ``shutil.which("uv")``. Many tests in this file patch ``shutil.which``-# to control whether uv is "available" — this autouse fixture makes-# pm.uv delegate to the patched ``shutil.which`` so the existing test-# setup keeps working without per-test changes.[email protected](autouse=True)-def _patch_managed_uv(request, patch_pm_uv_to_shutil_which):- """Make pm.uv follow shutil.which mocking in tests."""- yield--@pytest.fixture(autouse=True)def _patch_gateway_discovery(monkeypatch):"""Keep cmd_update's gateway auto-restart phase off this machine's gateways.diff --git a/tests/hermes_cli/test_update_parked_branch_guard.py b/tests/hermes_cli/test_update_parked_branch_guard.pyindex 8e269fa3877..bd39c166026 100644--- a/tests/hermes_cli/test_update_parked_branch_guard.py+++ b/tests/hermes_cli/test_update_parked_branch_guard.py@@ -271,7 +271,6 @@ def _patch_update_flow(monkeypatch, repo, run_real_git=True):hermes_main, "_resume_windows_gateways_after_update", lambda *a, **k: None)monkeypatch.setattr(hermes_main, "_capture_active_lazy_features", lambda: [])- monkeypatch.setattr(hermes_main, "_capture_active_tool_dependencies", lambda: [])def test_update_skips_and_warns_on_dirty_parked_branch(@@ -576,11 +575,9 @@ def test_update_up_to_date_path_does_not_repark_merged_branch(class _StopFlow(Exception):pass- import pm-monkeypatch.setattr(- pm,- "ensure",+ update_cmd,+ "_repair_current_checkout",lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),)args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)diff --git a/tests/hermes_cli/test_update_target_identity.py b/tests/hermes_cli/test_update_target_identity.pyindex c5ad01b0efa..c36d9dd9aeb 100644--- a/tests/hermes_cli/test_update_target_identity.py+++ b/tests/hermes_cli/test_update_target_identity.py@@ -58,7 +58,6 @@ def update_tree(tmp_path, monkeypatch):monkeypatch.setattr(cli_main, 'PROJECT_ROOT', clone)monkeypatch.setattr(update_receipt, '_code_identity', lambda **_: {'commit': base})monkeypatch.setattr(cli_main, '_capture_active_lazy_features', lambda: [])- monkeypatch.setattr(cli_main, '_capture_active_tool_dependencies', lambda: [])monkeypatch.setattr(cli_main, '_run_pre_update_backup', lambda *_: None)monkeypatch.setattr(cli_main, '_pause_windows_gateways_for_update', lambda: None)resumed = []diff --git a/tests/hermes_cli/test_update_yes_flag.py b/tests/hermes_cli/test_update_yes_flag.pyindex ae7683ca462..140c60eb81c 100644--- a/tests/hermes_cli/test_update_yes_flag.py+++ b/tests/hermes_cli/test_update_yes_flag.py@@ -17,7 +17,7 @@ import pytestfrom hermes_cli.main import cmd_updatepytestmark = pytest.mark.usefixtures(- "isolated_update_uv", "isolated_update_processes", "isolated_update_checkout",+ "isolated_update_processes", "isolated_update_checkout",)diff --git a/tests/hermes_cli/test_update_zip_sync_failure.py b/tests/hermes_cli/test_update_zip_sync_failure.pyindex 3e8faff3b43..176a3302bdd 100644--- a/tests/hermes_cli/test_update_zip_sync_failure.py+++ b/tests/hermes_cli/test_update_zip_sync_failure.py@@ -2,13 +2,12 @@import pytestimport pm+import hermes_cli.main as mainfrom hermes_cli import update_cmd_zipdef test_zip_dependency_failure_propagates_before_followup_mutations(monkeypatch):- import hermes_cli.main as mainmonkeypatch.setattr(pm, "ensure", lambda *_args, **_kwargs: None)- monkeypatch.setattr(pm, "uv", lambda **_kwargs: ("uv", {}))def fail(*args, **kwargs):raise pm.InstallError("venv", "network unavailable")monkeypatch.setattr(pm, "sync_venv", fail)@@ -16,26 +15,23 @@ def test_zip_dependency_failure_propagates_before_followup_mutations(monkeypatchraise AssertionError("follow-up mutation after failed sync")monkeypatch.setattr(main, "_refresh_active_memory_provider_dependencies", forbidden)with pytest.raises(pm.InstallError, match="network unavailable"):- update_cmd_zip._reinstall_python_deps_after_zip([])+ update_cmd_zip._reinstall_python_deps_after_zip()def test_pull_dependency_failure_keeps_recovery_marker(tmp_path, monkeypatch):- import hermes_cli.main as mainfrom hermes_cli import update_cmd_deps, update_cmdmonkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)monkeypatch.setattr(main, "_refuse_update_for_contended_shims", lambda *a: None, raising=False)monkeypatch.setattr(update_cmd, "_write_update_incomplete_marker", lambda: None)- monkeypatch.setattr(main, "_capture_active_tool_dependencies", lambda: [])def fail(*a, **k):raise pm.InstallError("venv", "sync stopped")monkeypatch.setattr(pm, "sync_venv", fail)- monkeypatch.setattr(pm, "uv", lambda **k: (None, {}))def forbidden(*a, **k):raise AssertionError("must retain recovery marker")monkeypatch.setattr(main, "_clear_update_incomplete_marker", forbidden)with pytest.raises(pm.InstallError, match="sync stopped"):update_cmd_deps._sync_python_dependencies_after_pull(- ["git"], "main", "a" * 40, active_lazy_features=[], active_tool_dependencies=[],+ ["git"], "main", "a" * 40, active_lazy_features=[],_windows_gateway_resume=[], desktop_dir=tmp_path, had_desktop_app_before_update=False,)diff --git a/tests/hermes_cli/test_venv_sync.py b/tests/hermes_cli/test_venv_sync.pyindex fb0926a38e5..f07c71294cc 100644--- a/tests/hermes_cli/test_venv_sync.py+++ b/tests/hermes_cli/test_venv_sync.py@@ -3,16 +3,13 @@It is the stdlib-only-at-import pre-venv entry point: the installers callit on a fresh clone before any dependency is importable, and post_updatecalls it after a tree swap when the venv is not trustworthy. Its-behaviour is driven with a FAKE uv — the module's job is deciding-whether/how to call uv and what to record, not resolving packages, and a-fake makes every decision observable (argv, env, cwd) without network.+behaviour is driven through PM's public client; package resolution and+publication belong to PM, not this CLI entry point."""from __future__ import annotationsimport json-import os-import statimport subprocessimport sysimport textwrap@@ -97,46 +94,7 @@ class TestStdlibOnly:assert result.returncode == 0, result.stderr-# ── behaviour, driven through a fake uv ──────────────────────────────────---def _fake_uv(tmp_path: Path, exit_code: int = 0) -> tuple:- """A uv that records its invocation and exits as told.-- Returns ``(binary_path, record_path)``; the binary shape is- platform-appropriate (a .bat trampoline on Windows, a shebang script- on POSIX) so subprocess can execute it directly.- """- record = tmp_path / "uv-calls.jsonl"- recorder = tmp_path / "uv_recorder.py"- recorder.write_text(- "import json, os, sys\n"- f"with open({str(record)!r}, 'a') as f:\n"- " f.write(json.dumps({\n"- " 'argv': sys.argv[1:],\n"- " 'cwd': os.getcwd(),\n"- " 'venv_env': os.environ.get('UV_PROJECT_ENVIRONMENT'),\n"- " 'virtual_env': os.environ.get('VIRTUAL_ENV'),\n"- " }) + '\\n')\n"- f"raise SystemExit({exit_code})\n",- encoding="utf-8",- )- if os.name == "nt":- binary = tmp_path / "uv.bat"- binary.write_text(- f'@echo off\r\n"{sys.executable}" "{recorder}" %*\r\n', encoding="utf-8"- )- else:- binary = tmp_path / "uv"- binary.write_text(- f'#!/bin/sh\nexec "{sys.executable}" "{recorder}" "$@"\n', encoding="utf-8"- )- binary.chmod(binary.stat().st_mode | stat.S_IEXEC)- return binary, record--def _checkout(tmp_path: Path, name: str = "co") -> Path:- """A minimal tree venv_sync classifies as a checkout."""root = tmp_path / name(root / ".git").mkdir(parents=True)(root / "pyproject.toml").write_text("[project]\nname='x'\n")@@ -144,121 +102,52 @@ def _checkout(tmp_path: Path, name: str = "co") -> Path:return root-def _wire_uv(monkeypatch, tmp_path: Path, exit_code: int = 0) -> Path:- """Point venv_sync's managed-uv resolution at a fake binary.-- The resolution itself is pm's (pm.client.uv) and pm's ledger wiring- has its own tests; here the decision layer is under test, so the- seam is venv_sync._managed_uv.- """- binary, record = _fake_uv(tmp_path, exit_code)- monkeypatch.setattr(- venv_sync, "_managed_uv", lambda: (str(binary), dict(os.environ))- )- return record---class TestCheckoutSync:- def test_a_stale_checkout_syncs_frozen_against_its_own_venv(- self, tmp_path, monkeypatch- ):- root = _checkout(tmp_path)- record = _wire_uv(monkeypatch, tmp_path)-- out = venv_sync.sync(root)-- assert out == {"state": "synced", "ok": True}- call = json.loads(record.read_text().splitlines()[0])- assert call["argv"] == ["sync", "--frozen"]- assert call["venv_env"] == str(root / "venv")- assert call["virtual_env"] is None # caller's venv must not leak in- assert Path(call["cwd"]) == root-- def test_a_current_checkout_never_invokes_uv(self, tmp_path, monkeypatch):- """The stamp is the fast path: currency costs a file read."""- root = _checkout(tmp_path)- record = _wire_uv(monkeypatch, tmp_path)+def _wire_pm(monkeypatch, *, current=False, error=None):+ import pm- assert venv_sync.sync(root)["state"] == "synced"- assert venv_sync.sync(root)["state"] == "current"- assert len(record.read_text().splitlines()) == 1 # one call total+ calls = []+ monkeypatch.setattr(pm, "venv_is_current", lambda *, project_root: current)- def test_an_edited_pyproject_invalidates_the_stamp(- self, tmp_path, monkeypatch- ):- """Extras edits without a lock bump still re-sync."""- root = _checkout(tmp_path)- _wire_uv(monkeypatch, tmp_path)- assert venv_sync.sync(root)["state"] == "synced"+ def sync(*, explicit, project_root):+ calls.append((project_root, explicit))+ if error:+ raise pm.InstallError("venv", error)- (root / "pyproject.toml").write_text("[project]\nname='y'\n")+ monkeypatch.setattr(pm, "sync_venv", sync)+ return calls- assert venv_sync.sync(root)["state"] == "synced"- def test_a_lockless_tree_drops_the_frozen_flag(self, tmp_path, monkeypatch):- """A clone without uv.lock still syncs — unfrozen."""+class TestCheckoutSync:+ @pytest.mark.parametrize("foreign", [False, True])+ def test_each_root_uses_the_public_pm_transaction(self, tmp_path, monkeypatch, foreign):root = _checkout(tmp_path)- (root / "uv.lock").unlink()- record = _wire_uv(monkeypatch, tmp_path)-- assert venv_sync.sync(root)["state"] == "synced"- call = json.loads(record.read_text().splitlines()[0])- assert call["argv"] == ["sync"]+ monkeypatch.setattr(venv_sync, "_project_root", lambda: root)+ calls = _wire_pm(monkeypatch)+ assert venv_sync.sync(root if foreign else None) == {"state": "synced", "ok": True}+ assert calls == [(root, True)]- def test_a_failed_sync_writes_no_stamp(self, tmp_path, monkeypatch):- """A failure must leave the next run trying again, not skipping."""+ def test_current_selection_needs_no_transaction(self, tmp_path, monkeypatch):root = _checkout(tmp_path)- _wire_uv(monkeypatch, tmp_path, exit_code=3)-- out = venv_sync.sync(root)-- assert out["state"] == "failed" and "3" in out["detail"]- assert venv_sync.read_stamp(root) == {}+ calls = _wire_pm(monkeypatch, current=True)+ assert venv_sync.sync(root) == {"state": "current", "ok": True}+ assert calls == []- def test_check_mode_reports_and_changes_nothing(self, tmp_path, monkeypatch):+ def test_check_is_passive(self, tmp_path, monkeypatch):root = _checkout(tmp_path)- record = _wire_uv(monkeypatch, tmp_path)+ calls = _wire_pm(monkeypatch)+ before = set(tmp_path.rglob("*"))+ assert venv_sync.sync(root, check=True) == {"state": "would-sync", "ok": True}+ assert calls == []+ assert set(tmp_path.rglob("*")) == before- out = venv_sync.sync(root, check=True)-- assert out["state"] == "would-sync"- assert not record.exists() # no uv call- assert venv_sync.read_stamp(root) == {}-- def test_no_managed_uv_is_a_failure_that_names_the_fix(- self, tmp_path, monkeypatch- ):+ def test_a_failed_sync_is_reported_and_retried(self, tmp_path, monkeypatch):root = _checkout(tmp_path)- # Runtime provisioning failures are reported through the client seam.- from pm.package import InstallError-- def unavailable(**kwargs):- raise InstallError("pm-runtime", "pinned uv and Python are unavailable")-- monkeypatch.setattr("pm.client.uv", unavailable)-- out = venv_sync.sync(root)-- assert out["state"] == "failed"- assert "pm install" in out["detail"]-- def test_own_tree_delegates_to_pms_venv_ledger(self, tmp_path, monkeypatch):- """When the root IS the running tree, pm.sync_venv owns the work- (one extras ledger, one authority) — no direct uv drive."""- root = _checkout(tmp_path)- from pm import paths as pm_paths-- monkeypatch.setattr(pm_paths, "repo_root", lambda: root)- calls = []-- import pm-- monkeypatch.setattr(pm, "sync_venv", lambda explicit=False: calls.append(explicit))-- out = venv_sync.sync(root)-- assert out == {"state": "synced", "ok": True}- assert calls == [True]+ calls = _wire_pm(monkeypatch, error="resolution failed")+ for _ in range(2):+ out = venv_sync.sync(root)+ assert out["state"] == "failed" and not out["ok"]+ assert "resolution failed" in out["detail"]+ assert calls == [(root, True), (root, True)]class TestSealedTrees:@@ -269,12 +158,12 @@ class TestSealedTrees:(root / "install-stamp.json").write_text(json.dumps({"commit": "abc123", "payload": "full", "updateMechanism": "electron-updater"}))- record = _wire_uv(monkeypatch, tmp_path)+ calls = _wire_pm(monkeypatch)out = venv_sync.sync(root)assert out == {"state": "sealed", "ok": True}- assert not record.exists()+ assert calls == []def test_a_dev_tree_with_both_stamp_and_git_is_a_checkout(self, tmp_path, monkeypatch@@ -283,7 +172,7 @@ class TestSealedTrees:(root / "install-stamp.json").write_text(json.dumps({"commit": "abc", "updateMechanism": "electron-updater"}))- _wire_uv(monkeypatch, tmp_path)+ _wire_pm(monkeypatch)assert venv_sync.sync(root)["state"] == "synced"diff --git a/tests/hermes_cli/test_venv_sync_currency.py b/tests/hermes_cli/test_venv_sync_currency.pyindex ad3ae0858bc..198a71c4c23 100644--- a/tests/hermes_cli/test_venv_sync_currency.py+++ b/tests/hermes_cli/test_venv_sync_currency.py@@ -1,4 +1,4 @@-"""Own-tree freshness follows the selected PM generation, not a second stamp."""+"""Checkout freshness follows the selected PM generation, not a second stamp."""import importlibimport jsonimport os@@ -15,6 +15,7 @@ from tests.pm.test_plugin_survival_contract import admission_env # noqa: F401def test_check_uses_real_pm_selection_and_keeps_invalid_evidence(admission_env, monkeypatch, capsys):+ monkeypatch.setattr("pm.client.is_runtime", lambda: True)root, home = admission_envcore = root / 'core'ensure = importlib.import_module('pm.ensure')@@ -23,8 +24,11 @@ def test_check_uses_real_pm_selection_and_keeps_invalid_evidence(admission_env,pins.set_pin('python', '1.0', {'any': {'url': 'https://example.invalid/python', 'sha256': 'a' * 64}})pins.save()monkeypatch.setattr(paths, 'lockfile_path', lambda: pin_path)- venv_sync.write_stamp(core, venv_sync._lock_digest(core))- cached = venv_sync._stamp_path(core).read_bytes()+ # A historical foreign-root stamp must not certify a PM environment.+ old_stamp = core / ".hermes-runtime" / "cache" / "venv-sync.json"+ old_stamp.parent.mkdir(parents=True)+ old_stamp.write_text('{"lockDigest": "old-bootstrap-stamp"}')+ cached = old_stamp.read_bytes()def check(expected, code=0):capsys.readouterr()@@ -32,7 +36,7 @@ def test_check_uses_real_pm_selection_and_keeps_invalid_evidence(admission_env,output = json.loads(capsys.readouterr().out)assert result == code, outputassert output['state'] == expected, output- assert venv_sync._stamp_path(core).read_bytes() == cached+ assert old_stamp.read_bytes() == cachedreturn outputcheck('would-sync')@@ -99,15 +103,15 @@ def test_check_uses_real_pm_selection_and_keeps_invalid_evidence(admission_env,def test_own_tree_sync_reuses_pm_without_writing_an_extra_stamp(admission_env, monkeypatch):- # venv_sync imports the public alias; use the same real engine as admission.- monkeypatch.setattr("pm.sync_venv", importlib.import_module("pm.ensure").sync_venv)+ # Keep the public client seam; run its in-process path against admission's real engine.+ monkeypatch.setattr("pm.client.is_runtime", lambda: True)root, home = admission_envcore = root / 'core'- assert not venv_sync._stamp_path(core).exists()+ assert not (core / ".hermes-runtime" / "cache" / "venv-sync.json").exists()assert venv_sync.sync(core) == {'state': 'synced', 'ok': True}environment = selected_venv(core)saved = paths.runtime_facts_path().read_bytes()- assert not venv_sync._stamp_path(core).exists()+ assert not (core / ".hermes-runtime" / "cache" / "venv-sync.json").exists()assert venv_sync.sync(core) == {'state': 'current', 'ok': True}assert paths.runtime_facts_path().read_bytes() == savedpython = environment / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')@@ -120,4 +124,4 @@ def test_own_tree_sync_reuses_pm_without_writing_an_extra_stamp(admission_env, massert replacement != environmentassert (replacement / 'pyvenv.cfg').is_file()assert venv_sync.sync(core) == {'state': 'current', 'ok': True}- assert not venv_sync._stamp_path(core).exists()+ assert not (core / ".hermes-runtime" / "cache" / "venv-sync.json").exists()