The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
merge: integrate desktop update acceptance tests
ethernet37650f810c5f
diff --cc hermes_cli/runtime_repair.pyindex 09c65353bc9,00000000000..4c8d5472006mode 100644,000000..100644--- a/hermes_cli/runtime_repair.py+++ b/hermes_cli/runtime_repair.py@@@ -1,1185 -1,0 +1,1186 @@@+"""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.11 → 3.12) so the+ # user isn't stuck on every `hermes update` with no path to a fixed+ # runtime (issue #76106). The requires-python constraint+ # (>=3.11,<3.14) 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, 14): # up to 3.13+ 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.ensure 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.11") -> bool:+ return True # dont remove me. ask ethernetdiff --cc tests/hermes_cli/test_runtime_repair.pyindex e3f5257afae,a68ed36cae9..97b2555148d--- a/tests/hermes_cli/test_runtime_repair.py+++ b/tests/hermes_cli/test_runtime_repair.py@@@ -146,49 -484,8 +146,52 @@@ class TestRuntimeRepairassert 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.managed_uv import (+ from hermes_cli.runtime_repair import (_acquire_repair_lock,_release_repair_lock,repair_vulnerable_runtime,diff --cc tests/install/windows-e2e.ps1index 00000000000,fd142d4b1ce..20b841bf8dcmode 000000,100644..100644--- a/tests/install/windows-e2e.ps1+++ b/tests/install/windows-e2e.ps1@@@ -1,0 -1,1040 +1,1040 @@@+ # ============================================================================+ # Windows Desktop GUI install + update E2E driver (the REAL user flow)+ # ============================================================================+ # Proves, on a real Windows machine, that a user who installs Hermes the way+ # the website tells them to can then update to the commit under test through+ # a real update surface -- with every leg driven through the GUI a user+ # actually touches:+ #+ # INSTALL - downloads the production Hermes-Setup.exe from the website,+ # launches it HEADED, and AutoHotkey clicks Install, waits,+ # then clicks Launch. The real Electron Hermes.exe must appear.+ # The exe runs EXACTLY as shipped against serve.git, whose+ # `main` is parked at OLD (-InstallRef, default: the newest+ # release tag) -- so the install lands on OLD the same way a+ # user's install landed on whatever main served that day.+ # UPDATE - OLD -> HEAD through the route selected by -Route:+ # desktop (implemented) launch the installed Hermes.exe+ # under Playwright's Electron driver and CLICK+ # Settings -> About -> "Update now". The+ # production hand-off chain runs untouched:+ # marker, app quit, detached updater, `hermes+ # update`, desktop rebuild, RELAUNCH. Asserts+ # target sha, marker cleanup, result JSON (when+ # the script path wrote one), working hermes,+ # and the relaunched app window.+ # update run `hermes update` from the installed venv+ # (the CLI route a GUI user might take).+ # installer re-run the bootstrap installer over the+ # existing install (download Hermes-Setup.exe+ # again, AHK clicks Install; lands on HEAD).+ #+ # HOW THE STAGING WORKS (no MITM proxy, no network fakery):+ # We bare-clone the checkout into <workroot>\serve.git and point every git+ # process at it with url.<file-url>.insteadOf rewrites for the two+ # canonical repo URLs, via a driver-owned gitconfig selected with+ # GIT_CONFIG_GLOBAL. (NOT GIT_CONFIG_COUNT/KEY_n/VALUE_n env config --+ # install.ps1 sets those itself and silently clobbers them.) The+ # installer's `git clone` and `hermes update`'s `git fetch origin`+ # transparently hit OUR bare repo. Its `main` serves OLD for the install+ # phase; the update phase advances it to HEAD -- an update becomes+ # available exactly the way it does for a real user. Installer and+ # updater run byte-for-byte as shipped; everything else (uv, PyPI, npm,+ # the installer's raw.githubusercontent install.ps1 download) uses the+ # real network, same as a user install.+ #+ # PROOF: screenshots at every renderer step (Playwright), full-desktop+ # screenshots around the installer/AHK phases, a rolling desktop capture+ # (every 3s) plus a continuous ffmpeg screen recording (recording.mkv) for+ # both phases, ahk.log, and the hand-off log. All uploaded as CI artifacts.+ #+ # DEVIATIONS FROM PRODUCTION (each one deliberate and small):+ # * the git URL redirect itself+ # * serve.git gets uploadpack.allowAnySHA1InWant=true so the installer's+ # baked -Commit pin can be fetched from the redirected clone the same+ # way GitHub's upload-pack allows it.+ # * A dummy provider key is seeded after install so the update leg sees+ # the ready app shell instead of the onboarding overlay (a real+ # updating user has a configured provider).+ # * The git shim reports the official URL. Detached updaters can resolve a+ # different git.exe, so the test home also records that upstream setup was+ # declined. The file:// transport must not prompt to add a second remote.+ #+ # USAGE (local Windows box or CI):+ # powershell -File tests\install\windows-e2e.ps1 -Phase all+ # ... -Phase stage / install / update+ # Phases share state via <workroot>\shas.json, so CI can run them as+ # separate steps for readable logs. -InstallMethod and -Route are+ # orthogonal axes: the install phase dispatches on -InstallMethod, the+ # update phase on -Route, and install writes what update needs (paths,+ # how OLD landed) into the shared state - so any implemented update can+ # follow any implemented install.+ # ============================================================================++ param(+ [ValidateSet("stage", "install", "update", "all")]+ [string]$Phase = "all",++ # How OLD gets installed, named by the same ids the combination+ # generator (scripts/sandbox/generate-e2e-matrix.mjs) declares.+ [ValidateSet("desktop-installer@latest", "installer-script", "installer-script+desktop")]+ [string]$InstallMethod = "desktop-installer@latest",++ # Update method to exercise in the update phase, same id namespace.+ # open-app-update (from a desktop-installer install) and hermes-update /+ # installer-script / installer-script+desktop (from script installs) are+ # implemented; the rest are declared arms so the surface is stable when+ # they land.+ [ValidateSet("open-app-update", "hermes-desktop-app-update", "hermes-update", "desktop-installer@latest", "installer-script", "installer-script+desktop")]+ [string]$Route = "open-app-update",++ # The OLD version: the ref served as `main` while the installer runs,+ # i.e. what the user starts on. The published Hermes-Setup.exe carries+ # no commit pin (Pin { commit: None, branch: "main" }) -- it installs+ # whatever `main` points at, so staging OLD means serving it there.+ # Empty or "auto" = newest release tag in the checkout (the "user on+ # the current release" starting point, same philosophy as the linux+ # axis's tag matrix). "auto" exists because `powershell -File` silently+ # swallows an empty-string argument ('Missing an argument for+ # parameter'), so the workflow cannot pass "".+ [string]$InstallRef = "auto",++ # Repo checkout whose HEAD is the update target.+ [string]$RepoRoot = "",++ [string]$WorkRoot = $(if ($env:HERMES_E2E_WORKROOT) { $env:HERMES_E2E_WORKROOT } else { Join-Path $env:TEMP "hermes-desktop-gui-e2e" }),++ [string]$SetupExeUrl = "https://hermes-assets.nousresearch.com/Hermes-Setup.exe",++ # Pinned @playwright/test for the update-gui driver. Installed fresh+ # into a scratch dir every run -- never resolved from the installed+ # tree -- so the driver behaves identically for every OLD ref. Bump+ # deliberately; keep roughly in step with the repo's own lockfile.+ [string]$PlaywrightVersion = "1.58.2"+ )++ $ErrorActionPreference = "Stop"+ $ProgressPreference = "SilentlyContinue"+ # Match an interactive Unicode console when Python output is piped into the+ # UTF-8 transcript. Old releases otherwise select cp1252 and crash on banners.+ $env:PYTHONIOENCODING = "utf-8"+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false+ $OutputEncoding = [Console]::OutputEncoding++ if (-not $RepoRoot) {+ $RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path+ }++ $ServeRepo = Join-Path $WorkRoot "serve.git"+ $HermesHome = Join-Path $WorkRoot "hermes-home"+ $InstallDir = Join-Path $HermesHome "hermes-agent"+ $StatePath = Join-Path $WorkRoot "shas.json"+ $ProofRoot = Join-Path $WorkRoot "proof"+ $AhkDir = Join-Path $WorkRoot "ahk"+ $AssetsDir = Join-Path $PSScriptRoot "e2e-assets"++ $RepoUrlHttps = "https://github.com/NousResearch/hermes-agent.git"+ $RepoUrlSsh = "[email protected]:NousResearch/hermes-agent.git"++ function Write-Step([string]$Message) {+ Write-Host ""+ Write-Host ("=" * 74)+ Write-Host "== $Message"+ Write-Host ("=" * 74)+ }++ function Assert-True([bool]$Condition, [string]$Message) {+ if (-not $Condition) {+ throw "E2E ASSERTION FAILED: $Message"+ }+ Write-Host " [ok] $Message"+ }++ function Invoke-Git([string[]]$GitArgs) {+ # PS 5.1 trap: under $ErrorActionPreference = "Stop", a native command+ # that writes ANYTHING to stderr while merged via 2>&1 throws a+ # NativeCommandError even when it exits 0 (git loves stderr for+ # progress/notices). Relax EAP around the native call only; exit-code+ # checking below is the real error gate.+ #+ # ALWAYS the real git.exe, never the shim we ship.+ # annoying bug where .bat files eat ^ args.+ # if hermes ever adds a git command that calls something with ^ this will break, lol.+ $prevEap = $ErrorActionPreference+ $ErrorActionPreference = "Continue"+ try {+ $output = & $script:RealGitExe @GitArgs 2>&1+ if ($LASTEXITCODE -ne 0) {+ throw "git $($GitArgs -join ' ') failed (exit $LASTEXITCODE): $output"+ }+ return ($output | Out-String).Trim()+ } finally {+ $ErrorActionPreference = $prevEap+ }+ }++ function Set-GitRedirect {+ # we redirect to our own repo so we can play around with what commit hermes thinks we're on.+ # MECHANISM: a driver-owned global gitconfig selected via+ # GIT_CONFIG_GLOBAL. Do NOT use GIT_CONFIG_COUNT/KEY_n/VALUE_n env+ # config here -- install.ps1 SETS those itself (GIT_CONFIG_COUNT=1,+ # windows.appendAtomically), silently clobbering any redirect we put+ # there. install.ps1's own `git config --global` writes simply land in+ # our file, so its compat settings still apply. Nothing leaks onto the+ # machine: the file lives in the workroot and dies with it.+ $fileUrl = "file:///" + ($ServeRepo -replace "\\", "/")+ $gitCfg = Join-Path $WorkRoot "e2e-gitconfig"+ if (-not (Test-Path -LiteralPath $WorkRoot)) {+ New-Item -ItemType Directory -Path $WorkRoot -Force | Out-Null+ }+ # first, get the set origin url+ $actualGitUrl = Invoke-Git @("-C", $RepoRoot, "remote", "get-url", "origin")- # then override it++ # then override it+ @"+ [url "$fileUrl"]+ insteadOf = $actualGitUrl+ insteadOf = $RepoUrlHttps+ insteadOf = $RepoUrlSsh+ "@ | Set-Content -LiteralPath $gitCfg -Encoding ASCII+ $env:GIT_CONFIG_GLOBAL = $gitCfg++ # check it worked+ $actualGitUrl = Invoke-Git @("-C", $RepoRoot, "remote", "get-url", "origin")+ Assert-True ($actualGitUrl -eq $fileUrl) "git URL redirect: origin resolves to '$actualGitUrl', expected '$fileUrl'."+ Write-Host " git URL redirect via GIT_CONFIG_GLOBAL=$gitCfg"+ Write-Host " $RepoUrlHttps -> $fileUrl"++ # shim git and make 'git remote get-url origin' report the actual HA upstream++ # insteadOf is transparent for transport but `git remote get-url origin` gives you the+ # replacement, so _get_origin_url() sees file://$SERVE_REPO and _is_fork() would return true.+ # we check for the arguments "remote get-url origin" in order in any position+ # to allow for e.g. -c with some config being passed.+ # if we didn't do this, we'd need the .skip_upstream_prompt file to prevent a hang in headless,"add the+ # official repo as upstream?" prompt would hang a headless run. But we don't anymore :D++ $realGit = (Get-Command git.exe -ErrorAction Stop).Source+ $shimDir = Join-Path $WorkRoot "shim"+ New-Item -ItemType Directory -Path $shimDir -Force | Out-Null+ $shimPath = Join-Path $shimDir "git.bat"+ @"+ @echo off+ setlocal enabledelayedexpansion+ set prev2=+ set prev1=+ :loop+ if "%~1"=="" goto passthrough+ if /I "!prev2!"=="remote" if /I "!prev1!"=="get-url" if /I "%~1"=="origin" (+ echo $RepoUrlHttps+ exit /b 0+ )+ set prev2=!prev1!+ set prev1=%~1+ shift+ goto loop+ :passthrough+ `"$realGit`" %*+ exit /b %ERRORLEVEL%+ "@ | Set-Content -LiteralPath $shimPath -Encoding ASCII++ $env:PATH = "$shimDir;$env:PATH"++ # Check it worked THROUGH the shim - deliberately not Invoke-Git, which+ # pins the real git.exe. `git` via PATH here is exactly how the+ # product's callers resolve it. Probe the intercepted verb AND plain+ # passthrough.+ #+ # KNOWN HOLE, accepted: cmd parses the command line before the bat sees+ # %*, and callers only quote args containing whitespace (PowerShell+ # native binding and python's list2cmdline alike) - so a caret arg like+ # rev-parse HEAD^{commit} loses its caret THROUGH ANY .bat, unfixably.+ # A .ps1 shim would dodge cmd but PATHEXT-resolving callers (python -+ # the shim's entire audience) never see .ps1 files, so .bat it stays.+ # The driver's own git plumbing therefore pins git.exe (Invoke-Git),+ # and the product's shimmed flows (fork detection: remote get-url) use+ # no caret revs. If a product path ever sends carets through the shim,+ # the leg fails loudly on a bad-revision error naming the mangled arg.+ $prevEap = $ErrorActionPreference; $ErrorActionPreference = "Continue"+ $observedGitUrl = (& git -C $RepoRoot remote get-url origin 2>&1 | Out-String).Trim()+ $passthroughProbe = (& git -C $RepoRoot rev-parse HEAD 2>&1 | Out-String).Trim()+ $passthroughExit = $LASTEXITCODE+ $ErrorActionPreference = $prevEap+ Assert-True ($observedGitUrl -eq $RepoUrlHttps) "git remote get-url shim: origin resolves to '$observedGitUrl', expected '$RepoUrlHttps'"+ Assert-True ($passthroughExit -eq 0 -and $passthroughProbe -match '^[0-9a-f]{40}$') "shim passthrough works: rev-parse HEAD -> '$passthroughProbe'"+ Write-Host " git remote get-url shim: $shimPath -> $realGit"+ Write-Host " 'remote get-url origin' now reports $RepoUrlHttps"+ }++ function Read-State {+ if (-not (Test-Path -LiteralPath $StatePath)) {+ throw "State file not found: $StatePath -- run '-Phase stage' first."+ }+ return Get-Content -LiteralPath $StatePath -Raw | ConvertFrom-Json+ }++ function Get-InstalledHead {+ return Invoke-Git @("-C", $InstallDir, "rev-parse", "HEAD")+ }++ function Get-DesktopExe {+ foreach ($c in @(+ (Join-Path $InstallDir "apps\desktop\release\win-unpacked\Hermes.exe"),+ (Join-Path $InstallDir "apps\desktop\release\win-arm64-unpacked\Hermes.exe")+ )) {+ if (Test-Path -LiteralPath $c) { return $c }+ }+ return $null+ }++ # Install-side state snapshot, taken BEFORE Test-HermesRuns can throw: on+ # app-update legs the updater runs detached and its transcript lands in the+ # product logs and hand-off files, not in this driver. Copy those plus the+ # venv entry-point dir while the install is still there to inspect, so a+ # failed post-update assertion leaves its evidence in the proof tree.+ function Save-InstallSideState([string]$Label) {+ $dest = Join-Path $ProofRoot "install-side-$Label"+ New-Item -ItemType Directory -Path $dest -Force | Out-Null+ $logsDir = Join-Path $HermesHome "logs"+ if (Test-Path -LiteralPath $logsDir) {+ Copy-Item $logsDir (Join-Path $dest "hermes-logs") -Recurse -Force -ErrorAction SilentlyContinue+ }+ $resultFile = Join-Path $HermesHome ".hermes-update-result.json"+ if (Test-Path -LiteralPath $resultFile) {+ Copy-Item $resultFile $dest -Force -ErrorAction SilentlyContinue+ }+ $venvScripts = Join-Path $InstallDir "venv\Scripts"+ if (Test-Path -LiteralPath $venvScripts) {+ Get-ChildItem -LiteralPath $venvScripts |+ Select-Object Name, Length, LastWriteTime |+ Format-Table -AutoSize | Out-String |+ Set-Content (Join-Path $dest "venv-scripts-ls.txt")+ }+ Get-ChildItem -LiteralPath $HermesHome -ErrorAction SilentlyContinue |+ Select-Object Name, Length, LastWriteTime |+ Format-Table -AutoSize | Out-String |+ Set-Content (Join-Path $dest "hermes-home-ls.txt")+ }++ function Test-HermesRuns([string]$Label) {+ Save-InstallSideState $Label+ $hermesExe = Join-Path $InstallDir "venv\Scripts\hermes.exe"+ Assert-True (Test-Path -LiteralPath $hermesExe) "$Label -- venv\Scripts\hermes.exe exists"+ & $hermesExe --version 2>&1 | ForEach-Object { Write-Host " hermes --version| $_" }+ Assert-True ($LASTEXITCODE -eq 0) "$Label -- hermes --version exits 0"+ }++ # ----------------------------------------------------------------------------+ # Script-install arm: the irm | iex one-liner, headless (the install.ps1+ # shipped AT the ref under test, run with flags probed from that ref's own+ # script text - older releases reject parameters added later).+ # ----------------------------------------------------------------------------+ # shellcheck source=../e2e-assets/ts-prefix.ps1+ . (Join-Path $PSScriptRoot "e2e-assets\ts-prefix.ps1")++ function Write-LogGroup([string]$Title, [string]$LogPath) {+ Write-Host "::group::$Title"+ if (Test-Path -LiteralPath $LogPath) { Get-Content -LiteralPath $LogPath | Write-Host }+ Write-Host "::endgroup::"+ }++ function Invoke-RefInstaller {+ param([string]$Ref, [string]$Label, [switch]$IncludeDesktop)+ $script = Join-Path $WorkRoot "install-$Label.ps1"+ (Invoke-Git @("-C", $RepoRoot, "show", "$Ref`:scripts/install.ps1")) -join "`n" |+ Set-Content -LiteralPath $script -Encoding UTF8+ $flags = @("-SkipSetup", "-HermesHome", $HermesHome, "-InstallDir", $InstallDir)+ $text = Get-Content -LiteralPath $script -Raw+ if ($text -match '\$NonInteractive') { $flags += "-NonInteractive" }+ if ($IncludeDesktop) {+ # The desktop stage is the point of this leg: a ref without the+ # parameter is a hard failure, not a silent plain install.+ if ($text -notmatch '\$IncludeDesktop') {+ throw "E2E ASSERTION FAILED: ref $Ref does not support -IncludeDesktop; this leg cannot mean what it claims"+ }+ $flags += "-IncludeDesktop"+ }+ New-Item -ItemType Directory -Path (Join-Path $WorkRoot "logs") -Force | Out-Null+ $log = Join-Path $WorkRoot "logs\install-$Label.log"+ $prevEap = $ErrorActionPreference; $ErrorActionPreference = "Continue"+ & powershell -NoProfile -ExecutionPolicy Bypass -File $script @flags 2>&1 | Add-TsPrefix | Out-File -Encoding UTF8 $log+ $installExit = $LASTEXITCODE+ $ErrorActionPreference = $prevEap+ Write-LogGroup "install.ps1 ($Label) transcript" $log+ Assert-True ($installExit -eq 0) "install.ps1 ($Label) exited 0"+ }++ function Assert-DesktopArtifact([string]$Label) {+ Assert-True ($null -ne (Get-DesktopExe)) "$Label -- desktop app built by installer under apps\desktop\release"+ }++ function Invoke-HermesUpdate {+ # The venv updater. --yes reaches the update subcommand only in later+ # releases; ask the installed binary, never parse its source.+ $hermesExe = Join-Path $InstallDir "venv\Scripts\hermes.exe"+ $updateArgs = @("update")+ $prevEap = $ErrorActionPreference; $ErrorActionPreference = "Continue"+ $helpText = & $hermesExe update --help 2>&1 | Out-String+ if ($helpText -match '--yes') { $updateArgs += "--yes" }+ New-Item -ItemType Directory -Path (Join-Path $WorkRoot "logs") -Force | Out-Null+ $log = Join-Path $WorkRoot "logs\update.log"+ Push-Location $InstallDir+ try {+ & $hermesExe @updateArgs 2>&1 | Add-TsPrefix | Out-File -Encoding UTF8 $log+ $updateExit = $LASTEXITCODE+ } finally {+ Pop-Location+ $ErrorActionPreference = $prevEap+ }+ Write-LogGroup "hermes update transcript" $log+ Assert-True ($updateExit -eq 0) "hermes update exited $updateExit (expected 0)"+ }++ function Invoke-HermesDesktopAppUpdate([string]$TargetSha) {+ # The hermes-desktop launch surface: `hermes desktop` runs its whole+ # real pipeline; the driver intercepts the product's final spawn+ # (argv/cwd/env captured by e2e-assets/launch-capture/sitecustomize.py)+ # and re-executes it under Playwright, which clicks Update now.+ $hermesExe = Join-Path $InstallDir "venv\Scripts\hermes.exe"+ $spec = Join-Path $WorkRoot "launch-spec.json"+ New-Item -ItemType Directory -Path (Join-Path $WorkRoot "logs") -Force | Out-Null+ $log = Join-Path $WorkRoot "logs\desktop-launch-capture.log"++ $capDir = Join-Path $AssetsDir "launch-capture"+ $prevPy = $env:PYTHONPATH+ $prevCap = $env:HERMES_E2E_CAPTURE_LAUNCH+ $env:PYTHONPATH = if ($prevPy) { "$capDir;$prevPy" } else { $capDir }+ $env:HERMES_E2E_CAPTURE_LAUNCH = $spec+ $prevEap = $ErrorActionPreference; $ErrorActionPreference = "Continue"+ Push-Location $InstallDir+ try {+ & $hermesExe desktop 2>&1 | Add-TsPrefix | Out-File -Encoding UTF8 $log+ $capExit = $LASTEXITCODE+ } finally {+ Pop-Location+ $ErrorActionPreference = $prevEap+ $env:PYTHONPATH = $prevPy+ $env:HERMES_E2E_CAPTURE_LAUNCH = $prevCap+ }+ Write-LogGroup "hermes desktop (launch capture) transcript" $log+ Assert-True ($capExit -eq 0) "hermes desktop exited 0 during launch capture"+ Assert-True (Test-Path -LiteralPath "$spec.captured") "a launch was actually captured (exit 0 without a launch must not pass)"++ $node = Get-ManagedNode+ $driverDir = Join-Path $WorkRoot "pw-driver"+ New-Item -ItemType Directory -Path $driverDir -Force | Out-Null+ $npmCli = Join-Path (Split-Path -Parent $node) "node_modules\npm\bin\npm-cli.js"+ Assert-True (Test-Path -LiteralPath $npmCli) "managed npm exists beside the managed node"+ Push-Location $driverDir+ try {+ & $node $npmCli install --no-save --no-audit --no-fund "@playwright/test@$PlaywrightVersion" 2>&1 |+ Select-Object -Last 5 | ForEach-Object { Write-Host " npm| $_" }+ $npmExit = $LASTEXITCODE+ } finally {+ Pop-Location+ }+ Assert-True ($npmExit -eq 0) "npm install @playwright/test@$PlaywrightVersion into the driver dir"++ Copy-Item (Join-Path $AssetsDir "launch-from-spec.mjs") (Join-Path $driverDir "launch-from-spec.mjs") -Force+ Copy-Item (Join-Path $AssetsDir "window-input.cjs") (Join-Path $driverDir "window-input.cjs") -Force+ $prevEap = $ErrorActionPreference; $ErrorActionPreference = "Continue"+ Push-Location $driverDir+ try {+ & $node "launch-from-spec.mjs" --spec $spec `+ --result (Join-Path $HermesHome ".hermes-update-result.json") `+ --expect-sha $TargetSha --repo-dir $InstallDir 2>&1 |+ ForEach-Object { Write-Host " pw| $_" }+ $driveExit = $LASTEXITCODE+ } finally {+ Pop-Location+ $ErrorActionPreference = $prevEap+ }+ Assert-True ($driveExit -eq 0) "app driven via captured hermes desktop spec; update completed"+ }++ function Save-DesktopScreenshot([string]$OutFile) {+ # Single full-desktop screenshot (primary screen).+ try {+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing+ $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds+ $bmp = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)+ $gfx = [System.Drawing.Graphics]::FromImage($bmp)+ $gfx.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)+ $bmp.Save($OutFile, [System.Drawing.Imaging.ImageFormat]::Png)+ $gfx.Dispose(); $bmp.Dispose()+ Write-Host " desktop screenshot: $OutFile"+ } catch {+ Write-Host " WARNING: desktop screenshot failed: $($_.Exception.Message)"+ }+ }++ function Start-DesktopRecorder([string]$OutDir) {+ # Rolling desktop capture: one PNG every 3s from a detached PowerShell,+ # capped at 800 frames (~40 min). Proof that survives any step failure.+ New-Item -ItemType Directory -Path $OutDir -Force | Out-Null+ $script = Join-Path $WorkRoot "recorder.ps1"+ @'+ param([string]$OutDir)+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing+ for ($i = 0; $i -lt 800; $i++) {+ if (Test-Path (Join-Path $OutDir "STOP")) { break }+ try {+ $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds+ $bmp = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)+ $gfx = [System.Drawing.Graphics]::FromImage($bmp)+ $gfx.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)+ $bmp.Save((Join-Path $OutDir ("frame-{0:D4}.png" -f $i)), [System.Drawing.Imaging.ImageFormat]::Png)+ $gfx.Dispose(); $bmp.Dispose()+ } catch {}+ Start-Sleep -Seconds 3+ }+ '@ | Set-Content -LiteralPath $script -Encoding UTF8+ $proc = Start-Process -FilePath "powershell.exe" `+ -ArgumentList "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $script, "-OutDir", $OutDir `+ -WindowStyle Hidden -PassThru+ Write-Host " desktop recorder started (pid $($proc.Id)) -> $OutDir"+ return $proc+ }++ function Stop-DesktopRecorder($proc, [string]$OutDir) {+ try { Set-Content -LiteralPath (Join-Path $OutDir "STOP") -Value "stop" } catch {}+ if ($proc) {+ try { $proc.WaitForExit(8000) | Out-Null } catch {}+ try { if (-not $proc.HasExited) { Stop-Process -Id $proc.Id -Force } } catch {}+ }+ }++ function Stop-HermesAppProcesses([string]$Label) {+ # Close the desktop app the blunt way between phases (a user quitting).+ # Only Hermes.exe (Electron) -- never hermes.exe (the venv CLI shim).+ $procs = @(Get-Process -Name "Hermes" -ErrorAction SilentlyContinue)+ foreach ($p in $procs) {+ try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {}+ }+ if ($procs.Count -gt 0) {+ Write-Host " [$Label] stopped $($procs.Count) Hermes.exe process(es)"+ Start-Sleep -Seconds 3+ }+ }++ function Get-ManagedNode {+ # `hermes update`/desktop builds use the Hermes-managed Node; use the same+ # one to run the Playwright driver so no system Node is required.+ $candidates = @(+ (Join-Path $HermesHome "node\node.exe"),+ (Join-Path $HermesHome "bin\node\node.exe"),+ (Join-Path $InstallDir "node\node.exe")+ )+ foreach ($c in $candidates) {+ if (Test-Path -LiteralPath $c) { return $c }+ }+ $fromPath = Get-Command node -ErrorAction SilentlyContinue+ if ($fromPath) { return $fromPath.Source }+ throw "No node.exe found (managed or on PATH)"+ }++ # ----------------------------------------------------------------------------+ # Phase: stage -- serve.git with `main` at OLD (advanced to HEAD by update-gui)+ # ----------------------------------------------------------------------------+ function Invoke-PhaseStage {+ Write-Step "STAGE: bare serve repo, main -> OLD (install base)"++ if (Test-Path -LiteralPath $WorkRoot) {+ Remove-Item -LiteralPath $WorkRoot -Recurse -Force+ }+ New-Item -ItemType Directory -Path $WorkRoot -Force | Out-Null+ # The purge above deleted the redirect gitconfig; re-arm it so the+ # bare-clone below (and everything after) sees the redirect file.+ Set-GitRedirect++ $current = Invoke-Git @("-C", $RepoRoot, "rev-parse", "HEAD")+ Write-Host " HEAD (update target): $current"++ # OLD: explicit -InstallRef, or the newest release tag -- the version a+ # user who installed on release day is on.+ $oldRef = $InstallRef+ if (-not $oldRef -or $oldRef -eq "auto") {+ # Parens matter: without them PowerShell binds -split as an+ # argument to Invoke-Git instead of an operator on its result.+ $tagList = Invoke-Git @("-C", $RepoRoot, "tag", "--list", "v*", "--sort=-creatordate")+ $oldRef = ($tagList -split "\r?\n" | Select-Object -First 1)+ if (-not $oldRef) { throw "no v* release tags in the checkout and no -InstallRef given -- cannot pick an OLD version" }+ }+ $old = Invoke-Git @("-C", $RepoRoot, "rev-parse", "$oldRef^{commit}")+ Write-Host " OLD ($oldRef): $old"+ Assert-True ($old -ne $current) "OLD differs from HEAD (an update is genuinely available)"++ # Bare-clone the checkout: this is the repo the installer and updater+ # actually talk to. Local-path clone hardlinks objects, so it's fast+ # even for full history. The published installer carries NO commit pin+ # (Pin { commit: None, branch: main }) -- it installs whatever `main`+ # serves, so staging OLD means parking `main` there; the update phase+ # advances it to HEAD.+ Invoke-Git @("clone", "--bare", "--quiet", $RepoRoot, $ServeRepo) | Out-Null+ Invoke-Git @("-C", $ServeRepo, "update-ref", "refs/heads/main", $old) | Out-Null+ Invoke-Git @("-C", $ServeRepo, "symbolic-ref", "HEAD", "refs/heads/main") | Out-Null++ # Belt-and-braces: SOME installer builds do bake a -Commit pin. A pinned+ # sha is in serve.git's history but not at a ref tip, so the redirected+ # fetch needs any-SHA1 upload-pack permission (GitHub grants the+ # equivalent for fetch of reachable commits).+ Invoke-Git @("-C", $ServeRepo, "config", "uploadpack.allowAnySHA1InWant", "true") | Out-Null+ Write-Host " serve.git: uploadpack.allowAnySHA1InWant=true (installer commit pin, if any)"++ @{ old = $old; old_ref = $oldRef; current = $current } |+ ConvertTo-Json | Set-Content -LiteralPath $StatePath -Encoding UTF8+ Write-Host " state written: $StatePath"+ New-Item -ItemType Directory -Path $ProofRoot -Force | Out-Null+ }++ # ----------------------------------------------------------------------------+ # Phase: install-gui -- website Hermes-Setup.exe, headed, AHK-driven+ # ----------------------------------------------------------------------------+ function Invoke-PhaseInstallGui {+ param(+ # "install" (first run, must land on OLD) or "update" (re-run over an+ # existing install after serve.git advanced, must land on the target).+ [string]$Mode = "install",+ [string]$ExpectedSha = "",+ [string]$ExpectedLabel = ""+ )+ $state = Read-State+ if ($Mode -eq "install") {+ $ExpectedSha = $state.old+ $ExpectedLabel = "OLD ($($state.old_ref))"+ }+ Write-Step "$($Mode.ToUpper()) (GUI): Hermes-Setup.exe from the website, headed, AHK clicks"+ $proof = Join-Path $ProofRoot $(if ($Mode -eq "install") { "install-gui" } else { "update-gui-installer" })+ New-Item -ItemType Directory -Path $proof -Force | Out-Null++ # The production installer, from the website. This is the binary users+ # double-click, run EXACTLY as shipped: its own pinned install.ps1, its+ # own baked BUILD_PIN_COMMIT. The only environmental difference is the+ # git URL redirect to serve.git.+ $setupExe = Join-Path $WorkRoot "Hermes-Setup.exe"+ if (-not (Test-Path -LiteralPath $setupExe)) {+ Write-Host " downloading $SetupExeUrl"+ Invoke-WebRequest -Uri $SetupExeUrl -OutFile $setupExe+ }+ Assert-True ((Get-Item $setupExe).Length -gt 1MB) "Hermes-Setup.exe downloaded ($([math]::Round((Get-Item $setupExe).Length / 1MB, 1)) MB)"++ # AutoHotkey v2, portable zip (no installer, no winget flakes).+ $ahkExe = Join-Path $AhkDir "AutoHotkey64.exe"+ if (-not (Test-Path -LiteralPath $ahkExe)) {+ $zip = Join-Path $WorkRoot "ahk.zip"+ Invoke-WebRequest -Uri "https://github.com/AutoHotkey/AutoHotkey/releases/download/v2.0.19/AutoHotkey_2.0.19.zip" -OutFile $zip+ Expand-Archive -Path $zip -DestinationPath $AhkDir -Force+ }+ Assert-True (Test-Path -LiteralPath $ahkExe) "AutoHotkey64.exe available"++ # AHK script + button templates side by side (ImageSearch resolves+ # relative to the script dir).+ Copy-Item -Path (Join-Path $AssetsDir "install-and-launch.ahk"), (Join-Path $AssetsDir "install-button.png"), (Join-Path $AssetsDir "launch-button.png") -Destination $AhkDir -Force++ $env:HERMES_HOME = $HermesHome+ # As shipped: NO dev-root override, no pin override. Ensure a stray+ # local dev checkout can't hijack resolution.+ Remove-Item Env:HERMES_SETUP_DEV_REPO_ROOT -ErrorAction SilentlyContinue+ New-Item -ItemType Directory -Path $HermesHome -Force | Out-Null++ $recorder = Start-DesktopRecorder (Join-Path $proof "desktop-frames")+ $ahkLog = Join-Path $proof "ahk.log"+ try {+ Save-DesktopScreenshot (Join-Path $proof "00-before-installer.png")++ # Launch the REAL installer, headed -- exactly a double-click.+ $installer = Start-Process -FilePath $setupExe -PassThru+ Write-Host " Hermes-Setup.exe launched (pid $($installer.Id))"++ # Drive it: Install click -> wait -> Launch click -> Hermes.exe window.+ # Arg 3 lets the AHK script use the installer's own log as the+ # install-finished fallback signal.+ $ahk = Start-Process -FilePath $ahkExe `+ -ArgumentList (Join-Path $AhkDir "install-and-launch.ahk"), $ahkLog, "Hermes-Setup.exe", (Join-Path $HermesHome "logs\bootstrap-installer.log") `+ -PassThru+ # Install on a cold runner takes a while; the AHK script's own inner+ # timeout (45 min on the Launch wait) is the effective budget.+ if (-not $ahk.WaitForExit(50 * 60 * 1000)) {+ Stop-Process -Id $ahk.Id -Force -ErrorAction SilentlyContinue+ throw "AutoHotkey driver did not finish within 50 minutes"+ }+ if (Test-Path -LiteralPath $ahkLog) {+ Get-Content -LiteralPath $ahkLog | ForEach-Object { Write-Host " ahk| $_" }+ }+ Assert-True ($ahk.ExitCode -eq 0) "AutoHotkey driver exited 0 (Install clicked, Launch clicked, app window seen)"++ Save-DesktopScreenshot (Join-Path $proof "01-app-launched.png")++ # The Launch hand-off under test: the app the installer spawned must+ # actually be running.+ Assert-True ($null -ne (Get-Process -Name "Hermes" -ErrorAction SilentlyContinue)) "Hermes.exe process is running (installer Launch hand-off worked)"++ # Installer should have exited after Launch.+ if (-not $installer.HasExited) {+ Start-Sleep -Seconds 10+ }+ Assert-True $installer.HasExited "Hermes-Setup.exe exited after Launch"+ }+ finally {+ Stop-DesktopRecorder $recorder (Join-Path $proof "desktop-frames")+ # Surface the installer's own log win or lose, full and folded.+ $bootLog = Join-Path $HermesHome "logs\bootstrap-installer.log"+ if (Test-Path -LiteralPath $bootLog) {+ Write-Host "::group::bootstrap-installer.log"+ Get-Content -LiteralPath $bootLog | Write-Host+ Write-Host "::endgroup::"+ Copy-Item $bootLog $proof -Force -ErrorAction SilentlyContinue+ }+ }++ # Close the freshly launched app (user quits after first look).+ Stop-HermesAppProcesses "post-install"++ # The installer cloned/updated from serve.git's `main`; the phase's+ # expected sha says where that must land (install: OLD; update: HEAD).+ $installedSha = Get-InstalledHead+ Write-Host " installer landed on: $installedSha (expected $ExpectedLabel = $ExpectedSha)"+ Assert-True ($installedSha -eq $ExpectedSha) "installed checkout is at $ExpectedLabel"+ if ($Mode -eq "install") {+ Assert-True ($installedSha -ne $state.current) "installed checkout differs from HEAD (an update is genuinely available)"+ }+ Test-HermesRuns "post-$Mode-gui"+ Assert-True ($null -ne (Get-DesktopExe)) "packaged Desktop Hermes.exe exists"++ # Seed a provider so the update leg meets the ready app shell, not the+ # onboarding overlay (an updating user has a configured provider).+ $envFile = Join-Path $HermesHome ".env"+ if (-not (Test-Path -LiteralPath $envFile) -or -not ((Get-Content $envFile -Raw -ErrorAction SilentlyContinue) -match "OPENROUTER_API_KEY")) {+ Add-Content -LiteralPath $envFile -Value "OPENROUTER_API_KEY=sk-or-...-key"+ }+ Write-Host " seeded placeholder provider key for the update leg"+ }++ # ----------------------------------------------------------------------------+ # Phase: update-gui -- OLD -> HEAD through the selected route+ # ----------------------------------------------------------------------------+ function Invoke-GuiUpdateDesktopRoute([string]$TargetSha) {+ Write-Step "UPDATE (GUI, route=desktop): advance served main -> $TargetSha, click Update now"+ $proof = Join-Path $ProofRoot "update-gui"+ New-Item -ItemType Directory -Path $proof -Force | Out-Null++ $env:HERMES_HOME = $HermesHome++ # The update becomes available the way it does for a real user: the+ # remote's main moves forward. (Install ran against main = OLD.)+ Invoke-Git @("-C", $ServeRepo, "update-ref", "refs/heads/main", $TargetSha) | Out-Null+ Write-Host " serve.git main advanced to $TargetSha"++ $desktopExe = Get-DesktopExe+ Assert-True ($null -ne $desktopExe) "packaged Hermes.exe present before update"++ $resultPath = Join-Path $HermesHome ".hermes-update-result.json"+ $markerPath = Join-Path $HermesHome ".hermes-update-in-progress"+ Remove-Item -LiteralPath $resultPath -Force -ErrorAction SilentlyContinue++ $node = Get-ManagedNode+ # The Playwright driver gets its OWN pinned @playwright/test in a+ # scratch dir -- NEVER the installed tree's copy. The driver talks to+ # the app over Playwright's inspection pipe, so its Playwright version+ # is independent of the app under test; installing it ourselves makes+ # the leg identical for every OLD ref (older releases predate the+ # dependency entirely, and hoisting moves it around in newer ones).+ $driverDir = Join-Path $WorkRoot "pw-driver"+ New-Item -ItemType Directory -Path $driverDir -Force | Out-Null+ $npmCli = Join-Path (Split-Path -Parent $node) "node_modules\npm\bin\npm-cli.js"+ Assert-True (Test-Path -LiteralPath $npmCli) "managed npm exists beside the managed node"+ Push-Location $driverDir+ try {+ & $node $npmCli install --no-save --no-audit --no-fund "@playwright/test@$PlaywrightVersion" 2>&1 |+ Select-Object -Last 5 | ForEach-Object { Write-Host " npm| $_" }+ $npmExit = $LASTEXITCODE+ } finally {+ Pop-Location+ }+ Assert-True ($npmExit -eq 0) "npm install @playwright/test@$PlaywrightVersion into the driver dir"++ $recorder = Start-DesktopRecorder (Join-Path $proof "desktop-frames")+ try {+ # Launch the installed app and click through Settings -> About ->+ # Update now. Exit 0 = the app quit for the updater hand-off.+ # Copy the driver INTO $driverDir first: Node resolves+ # require('@playwright/test') from the SCRIPT's own directory upward,+ # so running it from the CI checkout would resolve the wrong (or no)+ # node_modules.+ $driver = Join-Path $driverDir "e2e-drive-update.cjs"+ Copy-Item (Join-Path $AssetsDir "drive-update.cjs") $driver -Force+ Copy-Item (Join-Path $AssetsDir "window-input.cjs") (Join-Path $driverDir "window-input.cjs") -Force+ Copy-Item (Join-Path $AssetsDir "process-close.cjs") (Join-Path $driverDir "process-close.cjs") -Force+ Push-Location $driverDir+ $prevEap = $ErrorActionPreference+ $ErrorActionPreference = "Continue"+ try {+ & $node $driver $desktopExe $proof 2>&1 |+ ForEach-Object { Write-Host " $_" }+ $driveExit = $LASTEXITCODE+ } finally {+ Pop-Location+ $ErrorActionPreference = $prevEap+ Remove-Item -LiteralPath $driver -Force -ErrorAction SilentlyContinue+ }+ Assert-True ($driveExit -eq 0) "GUI driver clicked Update now and the app quit for hand-off"++ # The detached updater (spawned by the app, NOT by us) now runs+ # `hermes update` + desktop rebuild + relaunch. Which updater depends+ # on the installed checkout, and BOTH are production paths:+ # * checkouts shipping scripts/desktop-update.ps1 -> that script,+ # which writes .hermes-update-result.json on every exit;+ # * older checkouts -> the staged hermes-setup.exe --update flow,+ # which does NOT write the result JSON.+ # So: poll for COMPLETION = (result JSON) OR (checkout reached the+ # target sha AND the marker is gone). The sha/marker/hermes/relaunch+ # asserts below are the hard gate either way; the JSON is asserted+ # only when the script path produced it.+ #+ # The update pulls a large diff AND does a full Electron desktop+ # rebuild (vite + electron-builder) plus a uv sync; a WORKING updater+ # finishes well under 35 minutes on these runners (slowest observed+ # leg anywhere in the matrix: 29m end to end). A wedged updater never+ # finishes at any bound, so a longer wait only delays the report.+ # The desktop-build output goes to logs/update.log (not the streamed+ # handoff log), so we tail update.log here to show progress.+ Write-Host " waiting for the detached updater to finish (up to 35 min) ..."+ $updateLog = Join-Path $HermesHome "logs\update.log"+ $updateLogPos = 0+ $deadline = (Get-Date).AddMinutes(35)+ $nextDiagnostic = Get-Date+ while ((Get-Date) -lt $deadline) {+ if ($env:GITHUB_ACTIONS -eq "true" -and (Get-Date) -ge $nextDiagnostic) {+ & powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $AssetsDir "july-handoff-diagnostics.ps1") -WorkRoot $WorkRoot -Label "waiting"+ $nextDiagnostic = (Get-Date).AddMinutes(2)+ }+ if (Test-Path -LiteralPath $resultPath) { break }+ $head = ""+ try { $head = Get-InstalledHead } catch {}+ if ($head -eq $TargetSha -and -not (Test-Path -LiteralPath $markerPath)) { break }+ # Tail any new update.log lines so the desktop-rebuild phase is+ # visible in the CI step output.+ if (Test-Path -LiteralPath $updateLog) {+ try {+ $lines = Get-Content -LiteralPath $updateLog -ErrorAction SilentlyContinue+ if ($lines.Count -gt $updateLogPos) {+ $lines[$updateLogPos..($lines.Count - 1)] | ForEach-Object { Write-Host " update.log| $_" }+ $updateLogPos = $lines.Count+ }+ } catch {}+ }+ Start-Sleep -Seconds 20+ }+ if (Test-Path -LiteralPath $resultPath) {+ $result = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json+ Write-Host " updater result: ok=$($result.ok) code=$($result.exit_code) msg=$($result.message)"+ Assert-True ([bool]$result.ok) "updater result ok=true"+ } else {+ Write-Host " (no result JSON -- staged-binary updater path; relying on sha/marker/relaunch asserts)"+ }++ # Marker may briefly outlive the result write; allow it a moment.+ $mDeadline = (Get-Date).AddMinutes(2)+ while ((Get-Date) -lt $mDeadline -and (Test-Path -LiteralPath $markerPath)) { Start-Sleep -Seconds 5 }+ Assert-True (-not (Test-Path -LiteralPath $markerPath)) "update marker cleaned up"++ Assert-True ((Get-InstalledHead) -eq $TargetSha) "checkout landed on target commit"+ Test-HermesRuns "post-update"+ Assert-True ($null -ne (Get-DesktopExe)) "Hermes.exe still present after update"++ # The production hand-off relaunches the desktop (RelaunchExe).+ # A relaunched window is the user-visible proof the update loop closed.+ Write-Host " waiting for the relaunched Hermes.exe ..."+ $rDeadline = (Get-Date).AddMinutes(5)+ $relaunched = $null+ while ((Get-Date) -lt $rDeadline) {+ $relaunched = Get-Process -Name "Hermes" -ErrorAction SilentlyContinue+ if ($relaunched) { break }+ Start-Sleep -Seconds 5+ }+ Assert-True ($null -ne $relaunched) "updater relaunched the desktop app"+ Start-Sleep -Seconds 12 # let the window paint for the screenshot+ # Foreground the relaunched Hermes window so the proof screenshot+ # captures IT, not whatever else is on top (the full-desktop grab is+ # otherwise at the mercy of z-order -- an earlier run caught VS Code).+ try {+ $mainProc = Get-Process -Name "Hermes" -ErrorAction SilentlyContinue |+ Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1+ if ($mainProc) {+ Add-Type -Namespace HdE2E -Name Win -MemberDefinition @'+ [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetForegroundWindow(System.IntPtr h);+ [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool ShowWindow(System.IntPtr h, int n);+ '@ -ErrorAction SilentlyContinue+ [HdE2E.Win]::ShowWindow($mainProc.MainWindowHandle, 9) | Out-Null # SW_RESTORE+ [HdE2E.Win]::SetForegroundWindow($mainProc.MainWindowHandle) | Out-Null+ Start-Sleep -Seconds 2+ }+ } catch {}+ Save-DesktopScreenshot (Join-Path $proof "99-relaunched-desktop.png")+ }+ finally {+ Stop-DesktopRecorder $recorder (Join-Path $proof "desktop-frames")+ $handoffLog = Join-Path $HermesHome "logs\desktop-update-handoff.log"+ if (Test-Path -LiteralPath $handoffLog) {+ Write-Host "::group::desktop-update-handoff.log"+ Get-Content -LiteralPath $handoffLog | Write-Host+ Write-Host "::endgroup::"+ Copy-Item $handoffLog (Join-Path $proof "desktop-update-handoff.log") -Force -ErrorAction SilentlyContinue+ }+ if ($env:GITHUB_ACTIONS -eq "true") {+ & powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $AssetsDir "july-handoff-diagnostics.ps1") -WorkRoot $WorkRoot -Label "before-teardown"+ }+ # Quit the relaunched app so job teardown is clean.+ Stop-HermesAppProcesses "post-update"+ }+ }++ function Invoke-PhaseInstall {+ # Dispatch on the install axis. Each arm ends with the same contract:+ # checkout at OLD, hermes runs, and state carries how OLD landed so any+ # update arm can follow any install arm.+ $state = Read-State+ # Isolated install target for every arm; serve.git's file:// origin+ # looks like a fork to the updater, whose "add the official repo as+ # upstream?" prompt would hang a headless run - the marker is the+ # product's own suppression mechanism.+ $env:HERMES_HOME = $HermesHome+ New-Item -ItemType Directory -Path $HermesHome -Force | Out-Null+ switch ($InstallMethod) {+ "desktop-installer@latest" {+ Invoke-PhaseInstallGui+ }+ "installer-script" {+ Write-Step "INSTALL (script): OLD's own install.ps1, headless"+ Invoke-RefInstaller $state.old "old"+ Assert-True ((Get-InstalledHead) -eq $state.old) "installed checkout is at OLD"+ Test-HermesRuns "post-install-script"+ }+ "installer-script+desktop" {+ Write-Step "INSTALL (script+desktop): OLD's own install.ps1 -IncludeDesktop, headless"+ Invoke-RefInstaller $state.old "old" -IncludeDesktop+ Assert-True ((Get-InstalledHead) -eq $state.old) "installed checkout is at OLD"+ Test-HermesRuns "post-install-script-desktop"+ Assert-DesktopArtifact "OLD"+ }+ }+ }++ function Invoke-PhaseUpdate {+ $state = Read-State+ $env:HERMES_HOME = $HermesHome+ # Match the POSIX driver's explicit opt-out when a detached updater bypasses+ # the PATH shim and sees our local transport as a fork.+ New-Item -ItemType File -Path (Join-Path $HermesHome ".skip_upstream_prompt") -Force | Out-Null++ # The update becomes available the way it does for a real user: the+ # remote's main moves forward. The GUI route re-advances harmlessly+ # (same sha); script routes need it here because only the GUI arm's+ # helper used to own this step.+ Invoke-Git @("-C", $ServeRepo, "update-ref", "refs/heads/main", $state.current) | Out-Null+ Write-Host " serve.git main advanced to $($state.current)"++ switch ($Route) {+ "open-app-update" {+ # Meaningful only where an OS entry point exists - install.ps1+ # -IncludeDesktop registers shortcuts too, so both desktop-+ # bearing installs qualify; the workflow gate enforces which+ # pairs are dispatched.+ Invoke-GuiUpdateDesktopRoute $state.current+ }+ "hermes-desktop-app-update" {+ Invoke-HermesDesktopAppUpdate $state.current+ }+ "hermes-update" {+ Invoke-HermesUpdate+ }+ "installer-script" {+ # A user re-running the one-liner today gets the CURRENT script.+ Invoke-RefInstaller $state.current "head"+ }+ "installer-script+desktop" {+ Invoke-RefInstaller $state.current "head" -IncludeDesktop+ Assert-DesktopArtifact "HEAD"+ }+ "desktop-installer@latest" {+ # A user re-downloading Hermes-Setup.exe and clicking Install over+ # the existing install (the GUI twin of re-running the one-liner).+ # Windows has no already-installed fast path, so the full installer+ # UI shows and the same AHK drive applies; install.ps1's repository+ # stage fetches into the existing checkout, now aimed at HEAD.+ # Rotate the bootstrap log first: it appends across runs, and the+ # AHK's "bootstrap complete" fallback must not match the install+ # phase's completion line.+ $bootLog = Join-Path $HermesHome "logs\bootstrap-installer.log"+ if (Test-Path -LiteralPath $bootLog) {+ Move-Item -LiteralPath $bootLog -Destination "$bootLog.install-phase" -Force+ }+ Invoke-PhaseInstallGui -Mode "update" -ExpectedSha $state.current -ExpectedLabel "HEAD"+ Assert-DesktopArtifact "HEAD"+ }+ }++ Assert-True ((Get-InstalledHead) -eq $state.current) "checkout landed on HEAD"+ Test-HermesRuns "post-update"+ }++ function Invoke-CheckedPhaseUpdate {+ # Trace old Python stacks on CI without replacing updater behavior.+ $state = Read-State+ if ($env:GITHUB_ACTIONS -eq "true" -and $state.old -eq "7c1a029553d87c43ecff8a3821336bc95872213b" -and $InstallMethod -eq "desktop-installer@latest" -and $Route -eq "open-app-update") {+ $traceDir = Join-Path $AssetsDir "handoff-trace"+ $env:PYTHONPATH = if ($env:PYTHONPATH) { "$traceDir;$env:PYTHONPATH" } else { $traceDir }+ $env:HERMES_E2E_HANDOFF_TRACE = Join-Path $WorkRoot "proof\handoff-stacks"+ $env:PYTHONUNBUFFERED = "1"+ }+ Remove-Item -LiteralPath (Join-Path $WorkRoot "known-failure.json") -Force -ErrorAction SilentlyContinue+ # Only evidence produced by this update attempt can match an exception.+ foreach ($oldLog in @((Join-Path $WorkRoot "logs\update.log"), (Join-Path $HermesHome "logs\desktop.log"))) {+ if (Test-Path -LiteralPath $oldLog) { Move-Item -LiteralPath $oldLog -Destination "$oldLog.before-update" -Force }+ }+ try {+ Invoke-PhaseUpdate+ } catch {+ $failure = $_+ $node = Get-ManagedNode+ $classification = & $node (Join-Path $AssetsDir "known-failures.cjs") $WorkRoot $InstallMethod $Route $failure.Exception.Message+ $classificationExit = $LASTEXITCODE+ if ($classificationExit -ne 0) { throw $failure }+ $receipt = ($classification | Out-String) | ConvertFrom-Json+ Write-Host "KNOWN FAILURE [$($receipt.id)]: $($receipt.title)"+ Write-Host " $($receipt.explanation)"+ if ($env:GITHUB_OUTPUT) {+ Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "known_failure=$($receipt.id)" -Encoding UTF8+ }+ if ($env:GITHUB_STEP_SUMMARY) {+ Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding UTF8 -Value "Known historical failure: $($receipt.title). See the result chart footnote and uploaded known-failure.json."+ }+ }+ }++ # ----------------------------------------------------------------------------+ # Dispatch+ # ----------------------------------------------------------------------------+ Write-Host "Windows install/update E2E driver (real user flows)"+ Write-Host " phase: $Phase"+ Write-Host " install: $InstallMethod"+ Write-Host " route: $Route"+ Write-Host " repo: $RepoRoot"+ Write-Host " workroot: $WorkRoot"++ $script:RealGitExe = (Get-Command git.exe -ErrorAction Stop).Source++ Set-GitRedirect++ switch ($Phase) {+ "stage" { Invoke-PhaseStage }+ "install" { Invoke-PhaseInstall }+ "update" { Invoke-CheckedPhaseUpdate }+ "all" {+ Invoke-PhaseStage+ Invoke-PhaseInstall+ Invoke-CheckedPhaseUpdate+ }+ }++ Write-Host ""+ Write-Host "Phase '$Phase' completed successfully."