The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e/windows): PR-time install.ps1 -> hermes update journey on native Windows
teknium19129897dd1b1
diff --git a/.github/workflows/tests-os.yml b/.github/workflows/tests-os.ymlindex c2b55075451..854c9f56ee0 100644--- a/.github/workflows/tests-os.yml+++ b/.github/workflows/tests-os.yml@@ -167,6 +167,14 @@ jobs:OPENAI_API_KEY: ''NOUS_API_KEY: ''+ install-update-e2e:+ # The real scripts/install.ps1 -> `hermes update` HEAD -> NEXT journey on a real Windows+ # host (tests/e2e/core/windows_update): fresh install, gateway across the update,+ # interpreter selection, non-ASCII profile paths and tool ACLs, partial-clone fetch and+ # venv holders. Its own workflow so wine2e-install/** pushes can run it alone.+ name: Windows install + update E2E+ uses: ./.github/workflows/windows-install-update-e2e.yml+e2e-windows:# Real Hermes processes on a real Windows host (tests/e2e/core/windows): hermes.exe,# `hermes serve`, `hermes gateway run/stop`, the tui_gateway stdio process, cron scriptdiff --git a/.github/workflows/windows-install-update-e2e.yml b/.github/workflows/windows-install-update-e2e.ymlnew file mode 100644index 00000000000..0f78b97c618--- /dev/null+++ b/.github/workflows/windows-install-update-e2e.yml@@ -0,0 +1,92 @@+name: Windows install + update E2E++# PR-time native Windows install/update journey (tests/e2e/core/windows_update):+# the real scripts/install.ps1 on a fresh fake user profile (git redirected to a local+# bare clone, no git/python/uv on PATH), then the real `hermes update` HEAD -> NEXT,+# a running gateway across that update, and a turn against the loopback provider.+# Each file walks one journey (one install) and asserts several user-visible cells;+# tracked bugs are message-gated xfails (tests/e2e/core/_pending_fixes.py).+#+# Called from tests-os.yml on every Python PR. Pushes to wine2e-install/** run it alone,+# for sabotage proofs and iteration without the rest of CI.++on:+ workflow_call:+ push:+ branches: ['wine2e-install/**']++permissions:+ contents: read++concurrency:+ group: windows-install-update-e2e-${{ github.event_name }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ install-update:+ name: Windows install.ps1 + hermes update E2E+ runs-on: windows-latest-32-core+ timeout-minutes: 40+ steps:+ - name: Checkout code+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ # serve.git is a bare clone of this checkout: the installer's treeless clone and+ # `hermes update` need real history and release tags (version identity), as on GitHub.+ fetch-depth: 0++ - name: Set up locked Python and test dependencies+ uses: ./.github/actions/setup-pm+ with:+ packages: git,ripgrep+ extras: '["all", "telegram", "anthropic", "mistral", "fal", "modal", "daytona", "parallel-web"]'+ test-environment: 'true'+ prune-python-cache: true++ - name: Run Windows install + update E2E+ shell: bash+ run: |+ scripts/run_tests.sh tests/e2e/core/windows_update/ -- \+ -m "platforms and integration" -v --tb=short -rA+ env:+ HERMES_E2E_WINDOWS_INSTALL: '1'+ # Short machine roots: a real install lives at C:\Users\<name>\AppData\Local\hermes;+ # pytest's tmp dir would add ~100 characters before node_modules.+ HERMES_E2E_MACHINE_ROOT: ${{ runner.temp }}\wm+ HERMES_E2E_ARTIFACTS: ${{ runner.temp }}\win-update-e2e+ # One journey per file, all in parallel (each is mostly network + subprocess wait).+ HERMES_TEST_WORKERS: '6'+ HERMES_TEST_FILE_TIMEOUT: '1800'+ HERMES_TEST_FILE_RETRIES: '0'+ OPENROUTER_API_KEY: ''+ OPENAI_API_KEY: ''+ NOUS_API_KEY: ''++ - name: Upload transcripts, logs and receipts+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: windows-install-update-e2e-${{ github.run_attempt }}+ path: ${{ runner.temp }}/win-update-e2e+ if-no-files-found: ignore+ retention-days: 14++ - name: No leftover Python / Hermes processes+ # Backstop for each journey's teardown: nothing a machine started may outlive it.+ if: always()+ shell: pwsh+ run: |+ $names = 'python.exe', 'pythonw.exe', 'hermes.exe', 'node.exe'+ $root = "${{ runner.temp }}\wm".ToLower()+ $deadline = (Get-Date).AddSeconds(20)+ do {+ $left = @(Get-CimInstance Win32_Process | Where-Object {+ ($names -contains $_.Name.ToLower()) -and ("$($_.CommandLine) $($_.ExecutablePath)".ToLower().Contains($root))+ })+ if ($left.Count -eq 0) { 'no leftover processes from the E2E machines'; exit 0 }+ Start-Sleep -Milliseconds 500+ } while ((Get-Date) -lt $deadline)+ foreach ($p in $left) {+ "::error::leftover pid=$($p.ProcessId) ppid=$($p.ParentProcessId): $($p.CommandLine)"+ }+ exit 1diff --git a/tests/e2e/core/windows_update/__init__.py b/tests/e2e/core/windows_update/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/windows_update/_machine.py b/tests/e2e/core/windows_update/_machine.pynew file mode 100644index 00000000000..1658561edc9--- /dev/null+++ b/tests/e2e/core/windows_update/_machine.py@@ -0,0 +1,493 @@+"""A fresh Windows machine for the PR-time install.ps1 -> ``hermes update`` suite.++Every file here drives the REAL user entry points on a real Windows runner:++* ``scripts/install.ps1 -NonInteractive`` (this checkout's script, run as a file from a+ directory that is not a project, like a user who downloaded it);+* the ``hermes.exe`` it publishes in ``%LOCALAPPDATA%\\hermes\\bin`` for every later+ command (``--version``, one-shot turns, ``gateway run/status/stop``, ``update``);+* ``hermes update --yes`` from HEAD to NEXT, a synthetic child of HEAD.++Only external edges are replaced (tests/install/README.md, "The isolation trick"):++* git: a bare clone of this checkout (``serve.git``) answers every canonical Hermes URL via+ ``url.<file>.insteadOf`` in a machine-owned ``GIT_CONFIG_GLOBAL``. ``serve.git`` allows+ filtered fetches, so the installer's ``--filter=tree:0`` clone is a real partial clone,+ as it is against GitHub. Every ``git.exe`` directory is removed from PATH, so the+ installer stages its own pinned Git, as it does on a clean Windows box.+* the model provider: the recording loopback server (tests/fakes/fake_llm_provider.py).++Tool and dependency downloads (uv, the managed Python, wheels, Node) use the network,+exactly like the real installer.++Each machine is a fake user profile under pytest's tmp dir: ``USERPROFILE``/``HOME``/+``LOCALAPPDATA``/``APPDATA`` point inside it and ``HERMES_HOME`` is NOT set, so the+installer and every ``hermes`` command resolve the default ``%LOCALAPPDATA%\\hermes``+the way a real user's do. The installer also prepends its bin dir to the user PATH in+HKCU; the machine restores that value on teardown.++The suite mutates HKCU and downloads a toolchain per machine, so it only runs where+``HERMES_E2E_WINDOWS_INSTALL=1`` (the CI job sets it).+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import time+import uuid+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Iterable++import pytest++from tests.e2e.core.windows._helpers import (+ _PASSTHROUGH_ENV,+ _SECRET_SUFFIXES,+ Run,+ _decode,+ describe,+ kill_tree,+ wait_until,+)+from tests.fakes.fake_llm_provider import write_hermes_home++REPO_ROOT = Path(__file__).resolve().parents[4]+OPT_IN_ENV = "HERMES_E2E_WINDOWS_INSTALL"+INSTALL_TIMEOUT = 1500.0+UPDATE_TIMEOUT = 1200.0+CMD_TIMEOUT = 300.0+GATEWAY_READY_TIMEOUT = 240.0+CANONICAL_URLS = (+ "https://github.com/NousResearch/hermes-agent.git",+ "https://github.com/NousResearch/hermes-agent",+ "[email protected]:NousResearch/hermes-agent.git",+)+NEXT_MARKER = ".hermes-e2e-next"+# Captured before any machine strips PATH: harness plumbing (serve.git, rev-parse) only.+REAL_GIT = shutil.which("git")++# Every module here also carries platforms("windows") + integration + live_system_guard_bypass+# literally in its own ``pytestmark`` (scripts/ci/list_os_marked_tests.py reads the file text).+REQUIRES_OPT_IN = pytest.mark.skipif(+ os.environ.get(OPT_IN_ENV) != "1",+ reason=f"mutates HKCU PATH and downloads a toolchain; set {OPT_IN_ENV}=1 (CI does)")+++def _strip_path(path: str, drop: Iterable[str]) -> str:+ """PATH minus every directory that holds one of ``drop`` (a clean machine has none)."""+ kept = []+ for entry in path.split(os.pathsep):+ if not entry:+ continue+ if any(os.path.isfile(os.path.join(entry, name)) for name in drop):+ continue+ kept.append(entry)+ return os.pathsep.join(kept)+++def harness_git(*args: str, cwd: Path | None = None, env: dict[str, str] | None = None,+ timeout: float = 600.0) -> str:+ """The driver's own git (never the product's). Raises on failure: it is plumbing."""+ assert REAL_GIT, "harness needs git on PATH to stage serve.git"+ base = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}+ base.update(env or {})+ res = subprocess.run([REAL_GIT, "-c", "safe.directory=*", *args], cwd=cwd, env=base,+ capture_output=True, timeout=timeout)+ out, err = _decode(res.stdout), _decode(res.stderr)+ if res.returncode:+ raise RuntimeError(f"harness git {' '.join(args)} failed rc={res.returncode}: {err[-2000:]}")+ return out.strip()+++def _hkcu_path() -> tuple[str, int] | None:+ import winreg++ try:+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_READ) as key:+ value, kind = winreg.QueryValueEx(key, "Path")+ return str(value), int(kind)+ except OSError:+ return None+++def _restore_hkcu_path(saved: tuple[str, int] | None) -> None:+ import winreg++ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_SET_VALUE) as key:+ if saved is None:+ try:+ winreg.DeleteValue(key, "Path")+ except OSError:+ pass+ else:+ winreg.SetValueEx(key, "Path", 0, saved[1], saved[0])+++@dataclass+class Machine:+ """One fresh Windows user with a local git origin and a loopback provider."""++ root: Path+ profile_name: str+ base_url: str+ path_prepend: list[str] = field(default_factory=list)+ head: str = ""+ next: str = ""+ started: float = field(default_factory=time.time)+ _hkcu: Any = None+ _seq: int = 0+ _spawned: list[subprocess.Popen] = field(default_factory=list)++ # -- layout ---------------------------------------------------------------++ @property+ def profile(self) -> Path:+ return self.root / "Users" / self.profile_name++ @property+ def local(self) -> Path:+ return self.profile / "AppData" / "Local"++ @property+ def hermes_home(self) -> Path:+ return self.local / "hermes"++ @property+ def install_dir(self) -> Path:+ return self.hermes_home / "hermes-agent"++ @property+ def hermes_exe(self) -> Path:+ return self.hermes_home / "bin" / "hermes.exe"++ @property+ def serve(self) -> Path:+ return self.root / "serve.git"++ @property+ def logs(self) -> Path:+ path = self.root / "transcripts"+ path.mkdir(parents=True, exist_ok=True)+ return path++ # -- environment ----------------------------------------------------------++ def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:+ env = {k: v for k, v in os.environ.items()+ if k in _PASSTHROUGH_ENV and not k.upper().endswith(_SECRET_SUFFIXES)}+ roaming = self.profile / "AppData" / "Roaming"+ self.local.mkdir(parents=True, exist_ok=True)+ roaming.mkdir(parents=True, exist_ok=True)+ path = _strip_path(os.environ.get("PATH", ""), ("git.exe", "python.exe", "python3.exe", "uv.exe"))+ env.update({+ "PATH": os.pathsep.join([*self.path_prepend, path]),+ "USERPROFILE": str(self.profile),+ "HOME": str(self.profile),+ "LOCALAPPDATA": str(self.local),+ "APPDATA": str(roaming),+ "GIT_CONFIG_GLOBAL": str(self.root / "e2e-gitconfig"),+ "NO_COLOR": "1",+ # state.db lives under tmp; under a pytest ancestor the live-DB guard would refuse it.+ "HERMES_STATE_DB_GUARD_BYPASS": "1",+ })+ env.update(extra or {})+ return env++ # -- staging --------------------------------------------------------------++ def stage(self) -> None:+ """serve.git at HEAD (+ NEXT in its object store), the URL redirect, a seeded home."""+ self.root.mkdir(parents=True, exist_ok=True)+ self.head = harness_git("-C", str(REPO_ROOT), "rev-parse", "HEAD")+ harness_git("clone", "--bare", "--quiet", str(REPO_ROOT), str(self.serve))+ harness_git("-C", str(self.serve), "update-ref", "refs/heads/main", self.head)+ harness_git("-C", str(self.serve), "symbolic-ref", "HEAD", "refs/heads/main")+ for key in ("uploadpack.allowAnySHA1InWant", "uploadpack.allowFilter"):+ harness_git("-C", str(self.serve), "config", key, "true")+ self.next = self._mint_next()+ file_url = "file:///" + str(self.serve).replace("\\", "/")+ rewrites = "".join(f"\tinsteadOf = {url}\n" for url in CANONICAL_URLS)+ (self.root / "e2e-gitconfig").write_text(f'[url "{file_url}"]\n{rewrites}', encoding="utf-8")+ # What the user's config would hold after choosing a provider: the loopback mock.+ # install.ps1 keeps an existing config.yaml/.env.+ write_hermes_home(self.hermes_home, self.base_url)+ with (self.hermes_home / "config.yaml").open("a", encoding="utf-8") as fh:+ fh.write("display:\n compact: true\n")+ # insteadOf rewrites `remote get-url origin` too, so the updater would see a fork and+ # ask to add the official upstream; this is the product's own headless opt-out.+ (self.hermes_home / ".skip_upstream_prompt").write_text("", encoding="utf-8")+ self._hkcu = _hkcu_path()++ def _mint_next(self) -> str:+ """NEXT: HEAD plus a root marker and a nested one (a new subtree for the treeless+ clone to fetch). Lives only in serve.git until ``advance()`` points main at it."""+ blob_src = self.root / "next-marker.txt"+ blob_src.write_text("synthetic NEXT commit for the Windows install/update E2E\n", encoding="utf-8")+ blob = harness_git("-C", str(self.serve), "hash-object", "-w", "--no-filters", str(blob_src))+ index = self.root / "next.index"+ env = {"GIT_INDEX_FILE": str(index),+ "GIT_AUTHOR_NAME": "Hermes E2E", "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "Hermes E2E", "GIT_COMMITTER_EMAIL": "[email protected]"}+ harness_git("-C", str(self.serve), "read-tree", self.head, env=env)+ for path in (NEXT_MARKER, f"tests/e2e/{NEXT_MARKER}"):+ harness_git("-C", str(self.serve), "update-index", "--add", "--cacheinfo",+ f"100644,{blob},{path}", env=env)+ tree = harness_git("-C", str(self.serve), "write-tree", env=env)+ index.unlink(missing_ok=True)+ return harness_git("-C", str(self.serve), "commit-tree", tree, "-p", self.head,+ "-m", "e2e: synthetic next commit", env=env)++ def advance(self) -> None:+ """Publish NEXT on main: an update becomes available the way it does for a user."""+ harness_git("-C", str(self.serve), "update-ref", "refs/heads/main", self.next)++ # -- running --------------------------------------------------------------++ def _run_logged(self, argv: list[str], label: str, *, timeout: float, cwd: Path | None = None,+ env_extra: dict[str, str] | None = None) -> Run:+ """Run to completion with the full transcript on disk (survives a timeout)."""+ self._seq += 1+ log = self.logs / f"{self._seq:02d}-{label}.log"+ with log.open("wb") as fh:+ proc = subprocess.Popen(argv, cwd=cwd or self.profile, env=self.env(env_extra),+ stdin=subprocess.DEVNULL, stdout=fh, stderr=subprocess.STDOUT)+ try:+ code = proc.wait(timeout=timeout)+ except subprocess.TimeoutExpired:+ subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"], capture_output=True, timeout=60)+ proc.wait(timeout=60)+ raise AssertionError(+ f"{label} did not finish within {timeout:.0f}s\n{self._tail(log)}\n{self.evidence()}")+ return Run(code, _decode(log.read_bytes()), "")++ @staticmethod+ def _tail(path: Path, n: int = 6000) -> str:+ try:+ text = _decode(path.read_bytes())+ except OSError:+ return f"<no {path.name}>"+ return f"--- {path.name} (last {n} chars) ---\n{text[-n:]}"++ def install(self) -> Run:+ """``powershell -File install.ps1 -NonInteractive`` from a directory that is no project."""+ script = self.root / "install.ps1"+ shutil.copyfile(REPO_ROOT / "scripts" / "install.ps1", script)+ cwd = self.root / "install-cwd"+ cwd.mkdir(parents=True, exist_ok=True)+ return self._run_logged(+ ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script), "-NonInteractive"],+ "install", timeout=INSTALL_TIMEOUT, cwd=cwd)++ def hermes(self, *args: str, label: str | None = None, timeout: float = CMD_TIMEOUT,+ env_extra: dict[str, str] | None = None) -> Run:+ assert self.hermes_exe.is_file(), f"installer published no {self.hermes_exe}\n{self.evidence()}"+ name = label or "hermes-" + "-".join(a.strip("-") for a in args[:2] if a)+ return self._run_logged([str(self.hermes_exe), *args], name, timeout=timeout, env_extra=env_extra)++ def update(self, *extra: str, label: str = "update") -> Run:+ return self.hermes("update", "--yes", *extra, label=label, timeout=UPDATE_TIMEOUT)++ def installed_head(self) -> str:+ try:+ return harness_git("-C", str(self.install_dir), "rev-parse", "HEAD")+ except RuntimeError as exc:+ return f"<unreadable: {exc}>"++ def git_config(self, key: str) -> str:+ try:+ return harness_git("-C", str(self.install_dir), "config", "--get", key)+ except RuntimeError:+ return ""++ # -- gateway --------------------------------------------------------------++ def gateway_state(self) -> dict:+ try:+ return json.loads((self.hermes_home / "gateway_state.json").read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}++ def spawn_gateway(self, env_extra: dict[str, str] | None = None) -> subprocess.Popen:+ """``hermes gateway run`` through the published launcher, windowless and detached from+ this console: the shape the Desktop / login item uses to host a gateway."""+ self._seq += 1+ log = self.logs / f"{self._seq:02d}-gateway-run.log"+ flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW+ with log.open("wb") as fh:+ proc = subprocess.Popen([str(self.hermes_exe), "gateway", "run"], cwd=self.profile,+ env=self.env(env_extra), stdin=subprocess.DEVNULL, stdout=fh,+ stderr=subprocess.STDOUT, creationflags=flags)+ self._spawned.append(proc)+ return proc++ def wait_gateway_running(self, *, not_pid: int | None = None,+ timeout: float = GATEWAY_READY_TIMEOUT) -> dict:+ """The gateway's own record says ``running`` for a live pid (optionally a new one)."""+ import psutil++ def ready() -> dict | None:+ state = self.gateway_state()+ pid = state.get("pid")+ if state.get("gateway_state") != "running" or not pid or pid == not_pid:+ return None+ return state if psutil.pid_exists(int(pid)) else None++ try:+ return wait_until(ready, timeout, "gateway_state.json to report a live running gateway", interval=0.5)+ except AssertionError as exc:+ raise AssertionError(f"{exc}\n{self.evidence()}") from None++ # -- diagnostics ----------------------------------------------------------++ def owned_processes(self) -> list[Any]:+ """Live processes of this machine: exe/cwd/argv under its root, or its HERMES_HOME."""+ import psutil++ root = os.path.normcase(os.path.normpath(str(self.root)))+ home = os.path.normcase(os.path.normpath(str(self.hermes_home)))+ me = os.getpid()+ owned = []+ for proc in psutil.process_iter():+ try:+ if proc.pid == me or proc.create_time() < self.started - 1.0:+ continue+ env = {k.upper(): v for k, v in proc.environ().items()}+ hh = os.path.normcase(os.path.normpath(env.get("HERMES_HOME", "") or "-"))+ blob = os.path.normcase(" ".join([proc.exe() or "", proc.cwd() or "", *proc.cmdline()]))+ except (psutil.Error, OSError):+ continue+ if hh == home or root in blob:+ owned.append(proc)+ return owned++ def evidence(self) -> str:+ """Receipts, logs and the process table: what a failure message must carry."""+ parts = [f"machine root: {self.root}", f"HEAD={self.head} NEXT={self.next}",+ f"installed checkout: {self.installed_head()}"]+ receipt = self.hermes_home / "logs" / "update_receipts" / "latest.json"+ if receipt.is_file():+ parts.append(self._tail(receipt, 4000))+ parts.append(f"gateway_state.json: {self.gateway_state()}")+ parts.append(f"gateway.pid present: {(self.hermes_home / 'gateway.pid').exists()}")+ logs = self.hermes_home / "logs"+ for name in ("gateway.log", "gateway-stdio.log", "errors.log", "agent.log", "update.log",+ "desktop-update-handoff.log"):+ if (logs / name).is_file():+ parts.append(self._tail(logs / name, 3000))+ try:+ parts.append("owned processes:\n " + "\n ".join(describe(self.owned_processes()) or ["<none>"]))+ except Exception as exc: # diagnostics must never mask the real failure+ parts.append(f"process table unavailable: {exc}")+ return "\n".join(parts)++ def teardown(self) -> None:+ kill_tree(self.owned_processes())+ for proc in self._spawned:+ if proc.poll() is None:+ subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"], capture_output=True, timeout=60)+ try:+ _restore_hkcu_path(self._hkcu)+ except OSError:+ pass+ artifacts = os.environ.get("HERMES_E2E_ARTIFACTS")+ if artifacts:+ dest = Path(artifacts) / self.root.name+ shutil.copytree(self.logs, dest / "transcripts", dirs_exist_ok=True)+ for sub in ("logs",):+ src = self.hermes_home / sub+ if src.is_dir():+ shutil.copytree(src, dest / sub, dirs_exist_ok=True,+ ignore=shutil.ignore_patterns("*.db", "*.db-*"))+ (dest / "evidence.txt").write_text(self.evidence(), encoding="utf-8", errors="replace")+++def new_machine(tmp_root: Path, base_url: str, *, label: str, profile_name: str = "e2e",+ path_prepend: list[str] | None = None) -> Machine:+ """A staged machine. ``HERMES_E2E_MACHINE_ROOT`` (CI: a short runner.temp dir) keeps the+ install tree near the depth of a real ``C:\\Users\\<name>\\AppData\\Local\\hermes``;+ pytest's own tmp dir is already ~100 characters deep on Windows, and node_modules does+ the rest of the way to MAX_PATH."""+ base = Path(os.environ.get("HERMES_E2E_MACHINE_ROOT") or tmp_root)+ machine = Machine(root=base / f"{label}-{uuid.uuid4().hex[:4]}", profile_name=profile_name,+ base_url=base_url, path_prepend=list(path_prepend or []))+ machine.stage()+ return machine+++class Journey:+ """One expensive walk (install -> update -> ...) shared by a module's cells.++ Each step's value, or the exception it raised, is recorded; a cell reading a step+ re-raises that step's own failure (never a gate-matching claim), so a broken+ prerequisite fails the cells that need it and nothing else."""++ def __init__(self, machine: Machine) -> None:+ self.machine = machine+ self.results: dict[str, Any] = {}++ def step(self, name: str, fn: Any) -> Any:+ try:+ self.results[name] = fn()+ except Exception as exc: # recorded, re-raised by the cells that read it+ self.results[name] = exc+ return self.results[name]++ def ok(self, name: str) -> bool:+ return name in self.results and not isinstance(self.results[name], BaseException)++ def __getitem__(self, name: str) -> Any:+ if name not in self.results:+ raise RuntimeError(f"journey step {name!r} never ran\n{self.machine.evidence()}")+ value = self.results[name]+ if isinstance(value, BaseException):+ raise RuntimeError(f"journey step {name!r} failed: {value}") from value+ return value++ def require(self, name: str, ok: bool, message: str, run: Run | None = None) -> None:+ """A prerequisite of later steps: raise (recorded by ``step``) when it does not hold."""+ if not ok:+ raise RuntimeError(fail_with(self.machine, f"{name}: {message}", run))+++def fail_with(machine: Machine, message: str, run: Run | None = None) -> str:+ """Assertion text: the claim first (gates match on it), then the transcript and evidence."""+ tail = f"\n--- transcript rc={run.returncode} ---\n{run.stdout[-6000:]}" if run is not None else ""+ return f"{message}{tail}\n{machine.evidence()}"+++@dataclass+class Turn:+ run: Run+ reply_id: str+ reached_wire: bool++ @property+ def ok(self) -> bool:+ return self.run.returncode == 0 and self.reply_id in self.run.stdout and self.reached_wire+++def one_shot_turn(machine: Machine, srv: Any, label: str) -> Turn:+ """``hermes chat -q ... -Q`` through the published launcher against the loopback provider."""+ from tests.e2e.core.windows._helpers import last_user+ from tests.fakes.fake_llm_provider import Text++ prompt_id, reply_id = f"PROMPT-{uuid.uuid4().hex[:8]}", f"REPLY-{uuid.uuid4().hex[:8]}"+ before = len(srv.main_requests())+ srv.push(Text(f"The answer is {reply_id}."))+ res = machine.hermes("chat", "-q", f"Say the code {prompt_id}", "-Q", label=label)+ wired = any(prompt_id in last_user(body) for body in srv.main_requests()[before:])+ return Turn(res, reply_id, wired)+++# Printed only when a launch detours through source-update completion instead of running+# the requested command (hermes_cli/venv_sync.py, hermes_cli/source_build.py, update_cmd).+SOURCE_COMPLETION_MARKERS = ("completing source-update", "Preparing Node dependencies", "Update complete")+++def source_completion_detour(run: Run) -> str | None:+ return next((m for m in SOURCE_COMPLETION_MARKERS if m in run.stdout), None)diff --git a/tests/e2e/core/windows_update/test_fresh_install_update.py b/tests/e2e/core/windows_update/test_fresh_install_update.pynew file mode 100644index 00000000000..a3652e1a7d2--- /dev/null+++ b/tests/e2e/core/windows_update/test_fresh_install_update.py@@ -0,0 +1,101 @@+"""Fresh source install on native Windows, then ``hermes update`` HEAD -> NEXT.++Failure class: the first things a new Windows user does. ``install.ps1 -NonInteractive``+on a clean profile (no git, no Python, no uv on PATH), the first agent launch, then the+first update and the turn after it. Verdicts come from what a user sees: exit codes,+which commit the checkout serves, what the launcher prints, and what reached the+loopback provider.+"""++from __future__ import annotations++import json++import pytest++from tests.e2e.core._pending_fixes import known_gate+from tests.e2e.core.windows_update._machine import (+ NEXT_MARKER,+ REQUIRES_OPT_IN,+ Journey,+ fail_with,+ new_machine,+ one_shot_turn,+ source_completion_detour,+)+from tests.fakes.fake_llm_provider import FakeLLMServer++pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,+ pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]++KNOWN = {+ "first_launch": (+ r"^first agent launch after a pristine install detoured through source-update completion",+ "gated on #123314: a fresh Windows source install enters source-update completion on the "+ "first agent launch",+ ),+}++[email protected](scope="module")+def journey(tmp_path_factory):+ with FakeLLMServer() as srv:+ machine = new_machine(tmp_path_factory.mktemp("fresh"), srv.base_url, label="fresh")+ j = Journey(machine)+ try:+ j.step("install", machine.install)+ j.step("version", lambda: machine.hermes("--version"))+ j.step("first_turn", lambda: one_shot_turn(machine, srv, "first-turn"))+ machine.advance()+ j.step("update", machine.update)+ j.step("turn_after_update", lambda: one_shot_turn(machine, srv, "turn-after-update"))+ yield j+ finally:+ machine.teardown()+++def test_install_lands_on_head_and_publishes_hermes(journey: Journey) -> None:+ m, run = journey.machine, journey["install"]+ assert run.returncode == 0, fail_with(m, f"install.ps1 exited {run.returncode}", run)+ head = m.installed_head()+ assert head == m.head, fail_with(m, f"install.ps1 checked out {head}, expected HEAD {m.head}", run)+ marker = m.install_dir / ".hermes-bootstrap-complete"+ assert marker.is_file(), fail_with(m, "install.ps1 reported success but wrote no bootstrap marker", run)+ pinned = json.loads(marker.read_text(encoding="utf-8-sig")).get("pinnedCommit")+ assert pinned == m.head, fail_with(m, f"bootstrap marker pins {pinned}, expected {m.head}", run)+ version = journey["version"]+ assert version.returncode == 0 and "Hermes Agent v" in version.stdout, fail_with(+ m, "the published hermes.exe cannot report its version", version)+++def test_first_agent_launch_runs_the_turn(journey: Journey) -> None:+ m, turn = journey.machine, journey["first_turn"]+ detour = source_completion_detour(turn.run)+ with known_gate(KNOWN, "first_launch"):+ assert detour is None, fail_with(+ m, f"first agent launch after a pristine install detoured through source-update completion "+ f"(printed {detour!r})", turn.run)+ assert turn.ok, fail_with(+ m, f"first agent launch did not complete a turn (reply printed={turn.reply_id in turn.run.stdout}, "+ f"prompt reached provider={turn.reached_wire})", turn.run)+++def test_update_moves_checkout_to_next(journey: Journey) -> None:+ m, run = journey.machine, journey["update"]+ assert run.returncode == 0, fail_with(m, f"hermes update exited {run.returncode}", run)+ head = m.installed_head()+ assert head == m.next, fail_with(m, f"after hermes update the checkout is at {head}, expected NEXT {m.next}", run)+ assert (m.install_dir / NEXT_MARKER).is_file(), fail_with(m, "NEXT's marker file is missing from the checkout", run)+ receipt_path = m.hermes_home / "logs" / "update_receipts" / "latest.json"+ receipt = json.loads(receipt_path.read_text(encoding="utf-8")) if receipt_path.is_file() else {}+ assert receipt.get("outcome") == "success", fail_with(+ m, f"update receipt outcome is {receipt.get('outcome')!r}, expected 'success'", run)+++def test_turn_after_update(journey: Journey) -> None:+ m, turn = journey.machine, journey["turn_after_update"]+ assert source_completion_detour(turn.run) is None, fail_with(+ m, "the first turn after a completed update re-ran source-update completion", turn.run)+ assert turn.ok, fail_with(+ m, f"turn after update failed (reply printed={turn.reply_id in turn.run.stdout}, "+ f"prompt reached provider={turn.reached_wire})", turn.run)diff --git a/tests/e2e/core/windows_update/test_gateway_across_update.py b/tests/e2e/core/windows_update/test_gateway_across_update.pynew file mode 100644index 00000000000..f0fd9e15dfd--- /dev/null+++ b/tests/e2e/core/windows_update/test_gateway_across_update.py@@ -0,0 +1,141 @@+"""A running gateway across ``hermes update`` on native Windows.++Failure class: gateway hand-off. A user (or the Desktop / login item) hosts+``hermes gateway run`` through the published ``hermes.exe``; ``hermes update`` must stop+it, update the checkout, relaunch it on the new commit, and leave it where every later+command can find it: ``hermes gateway status``, ``hermes gateway stop`` and the next+``hermes update``'s own pause step.+"""++from __future__ import annotations++import re++import psutil+import pytest++from tests.e2e.core._pending_fixes import known_gate+from tests.e2e.core.windows._helpers import wait_until+from tests.e2e.core.windows_update._machine import (+ REQUIRES_OPT_IN,+ Journey,+ fail_with,+ new_machine,+)+from tests.fakes.fake_llm_provider import FakeLLMServer++pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,+ pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]++_INVISIBLE = ("gated on #124318 (same root as #123430/#123463/#123490): the updater relaunches the "+ "gateway as `python -I -c ...`, a form Windows gateway discovery rejects, so the live "+ "gateway is invisible")+KNOWN = {+ "update_restart": (r"^hermes update with a running gateway reported a failed gateway restart", _INVISIBLE),+ "discoverable": (r"^after update the serving gateway \(pid \d+\) is invisible", _INVISIBLE),+ "next_update": (r"^the next hermes update is blocked at the gateway pause step", _INVISIBLE),+ "stop": (r"^after update `hermes gateway stop` left the serving gateway \(pid \d+\) running", _INVISIBLE),+}+_RESTART_FAILURE = re.compile(+ r"^.*(recovery failed|restart could not be verified|restart incomplete|not verified alive).*$", re.M)+_STATUS_LINE = re.compile(r"^.*[✓✗].*[Gg]ateway.*$", re.M)+++def _status_line(text: str) -> str:+ found = _STATUS_LINE.findall(text)+ return found[0].strip() if found else "<no status line>"+++def _alive(pid: int) -> bool:+ try:+ return psutil.Process(pid).is_running() and psutil.Process(pid).status() != psutil.STATUS_ZOMBIE+ except psutil.Error:+ return False++[email protected](scope="module")+def journey(tmp_path_factory):+ with FakeLLMServer() as srv:+ machine = new_machine(tmp_path_factory.mktemp("gw"), srv.base_url, label="gw")+ j = Journey(machine)+ try:+ install = j.step("install", machine.install)+ if j.ok("install"):+ j.step("install_ok", lambda: j.require("install", install.returncode == 0,+ f"install.ps1 exited {install.returncode}", install))+ if j.ok("install_ok"):+ j.step("spawn", machine.spawn_gateway)+ before = j.step("state_before", machine.wait_gateway_running)+ j.step("status_before", lambda: machine.hermes("gateway", "status", label="status-before"))+ machine.advance()+ j.step("update", machine.update)+ old_pid = int(before.get("pid") or 0) if isinstance(before, dict) else None+ j.step("state_after", lambda: machine.wait_gateway_running(not_pid=old_pid))+ j.step("status_after", lambda: machine.hermes("gateway", "status", label="status-after"))+ j.step("pidfile_after", lambda: (machine.hermes_home / "gateway.pid").exists())+ j.step("update_again", lambda: machine.update(label="update-again"))+ j.step("state_before_stop", machine.gateway_state)+ j.step("stop", lambda: machine.hermes("gateway", "stop", label="stop"))+ yield j+ finally:+ machine.teardown()+++def test_launcher_started_gateway_is_visible_before_update(journey: Journey) -> None:+ m, state, status = journey.machine, journey["state_before"], journey["status_before"]+ assert status.returncode == 0 and "running" in _status_line(status.stdout).lower(), fail_with(+ m, f"the launcher-started gateway (pid {state.get('pid')}) is invisible to `hermes gateway status` "+ f"before any update: {_status_line(status.stdout)!r}", status)+++def test_update_with_running_gateway_succeeds(journey: Journey) -> None:+ m, run = journey.machine, journey["update"]+ journey["state_before"] # the precondition: a gateway was running when the update began+ failure = _RESTART_FAILURE.search(run.stdout)+ with known_gate(KNOWN, "update_restart"):+ assert run.returncode == 0 and failure is None, fail_with(+ m, f"hermes update with a running gateway reported a failed gateway restart "+ f"(rc={run.returncode}): {failure.group(0).strip() if failure else '<no restart message>'}", run)+++def test_gateway_serves_next_after_update(journey: Journey) -> None:+ m, state = journey.machine, journey["state_after"]+ pid, sha = int(state.get("pid") or 0), str(state.get("code_sha") or "")+ assert _alive(pid), fail_with(m, f"the relaunched gateway pid {pid} is not alive")+ assert len(sha) >= 7 and m.next.startswith(sha), fail_with(+ m, f"the relaunched gateway serves code_sha={sha!r}, expected NEXT {m.next}")+++def test_gateway_discoverable_after_update(journey: Journey) -> None:+ m, state, status = journey.machine, journey["state_after"], journey["status_after"]+ pid, pidfile = int(state.get("pid") or 0), journey["pidfile_after"]+ line = _status_line(status.stdout)+ with known_gate(KNOWN, "discoverable"):+ assert status.returncode == 0 and str(pid) in line and pidfile, fail_with(+ m, f"after update the serving gateway (pid {pid}) is invisible: `hermes gateway status` says "+ f"{line!r}; gateway.pid present={pidfile}", status)+++def test_next_update_is_not_blocked(journey: Journey) -> None:+ m, run = journey.machine, journey["update_again"]+ journey["state_after"] # a gateway was running (the relaunched one)+ blocked = "Could not map Windows gateway PIDs" in run.stdout+ with known_gate(KNOWN, "next_update"):+ assert run.returncode == 0 and not blocked, fail_with(+ m, f"the next hermes update is blocked at the gateway pause step (rc={run.returncode}, "+ f"'Could not map Windows gateway PIDs' printed={blocked})", run)+++def test_gateway_stop_after_update(journey: Journey) -> None:+ m, stop, state = journey.machine, journey["stop"], journey["state_before_stop"]+ pid = int(state.get("pid") or 0)+ assert pid, fail_with(m, f"no gateway recorded before stop: {state}")+ try:+ wait_until(lambda: not _alive(pid), 90, f"gateway pid {pid} to exit after stop", interval=0.5)+ stopped = True+ except AssertionError:+ stopped = False+ with known_gate(KNOWN, "stop"):+ assert stopped, fail_with(+ m, f"after update `hermes gateway stop` left the serving gateway (pid {pid}) running", stop)+ assert stop.returncode == 0, fail_with(m, f"hermes gateway stop exited {stop.returncode}", stop)diff --git a/tests/e2e/core/windows_update/test_git_and_holders.py b/tests/e2e/core/windows_update/test_git_and_holders.pynew file mode 100644index 00000000000..fe7430d9558--- /dev/null+++ b/tests/e2e/core/windows_update/test_git_and_holders.py@@ -0,0 +1,133 @@+"""Git and process-holder edges of ``hermes update`` on native Windows.++Failure class: git on Windows.++* ``install.ps1`` clones with ``--filter=tree:0`` using the Git it pins. ``hermes update``+ must then fetch into that partial clone and land on the new commit. The fetch goes+ through the same pinned Git that has hit ``BUG: builtin/pack-objects.c`` (#124323).+* ``hermes update --list-venv-holders`` is the read-only twin of the Windows venv-holder+ guard. It must list every live process running from the install's venv and exit 3,+ so automation can stop exactly those PIDs, and print ``[]``/exit 0 once they are gone+ (#123050).+"""++from __future__ import annotations++import json+import subprocess++import psutil+import pytest++from tests.e2e.core._pending_fixes import known_gate+from tests.e2e.core.windows._helpers import Run, wait_until+from tests.e2e.core.windows_update._machine import (+ REQUIRES_OPT_IN,+ Journey,+ Machine,+ fail_with,+ new_machine,+)+from tests.fakes.fake_llm_provider import FakeLLMServer++pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,+ pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]++KNOWN = {+ "partial_fetch": (r"^hermes update over the installer's partial clone failed: .*BUG: builtin/pack-objects",+ "gated on #124323: the pinned Git's pack-objects BUG on the --filter=tree:0 clone"),+ "holders": (r"^`hermes update --list-venv-holders` did not report the live venv holders .*"+ r"\(rc=0, reported pids \[\]\)",+ "gated on #123050: --list-venv-holders reads the retired hermes_cli.main stub and always "+ "prints []"),+}+VENV_HOLDERS_EXIT = 3+++def _venv_pythons(machine: Machine) -> list:+ return sorted(machine.hermes_home.glob("installs/*/environments/*/venv/Scripts/python.exe"))+++def _spawn_holders(machine: Machine) -> list[int]:+ """What keeps a venv busy on a real box: long-lived processes on its interpreter."""+ pythons = _venv_pythons(machine)+ assert pythons, f"harness: no venv\\Scripts\\python.exe under {machine.hermes_home / 'installs'}"+ pids = []+ for exe in pythons:+ proc = subprocess.Popen([str(exe), "-c", "import time; time.sleep(900)"], cwd=machine.profile,+ env=machine.env(), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)+ machine._spawned.append(proc)+ pids.append(proc.pid)+ wait_until(lambda: all(psutil.pid_exists(p) for p in pids), 30, "venv holders to start")+ return pids+++def _stop_holders(pids: list[int]) -> None:+ for pid in pids:+ subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, timeout=60)+ wait_until(lambda: not any(psutil.pid_exists(p) for p in pids), 60, "venv holders to exit")+++def _reported(run: Run) -> list[int] | None:+ text = run.stdout+ start, end = text.find("["), text.rfind("]")+ if start < 0 or end < start:+ return None+ try:+ return sorted(int(h["pid"]) for h in json.loads(text[start:end + 1]))+ except (ValueError, TypeError, KeyError):+ return None++[email protected](scope="module")+def journey(tmp_path_factory):+ with FakeLLMServer() as srv:+ machine = new_machine(tmp_path_factory.mktemp("git"), srv.base_url, label="git")+ j = Journey(machine)+ try:+ install = j.step("install", machine.install)+ if j.ok("install"):+ j.step("install_ok", lambda: j.require("install", install.returncode == 0,+ f"install.ps1 exited {install.returncode}", install))+ if j.ok("install_ok"):+ j.step("partial_filter", lambda: machine.git_config("remote.origin.partialclonefilter"))+ machine.advance()+ j.step("update", machine.update)+ pids = j.step("holders", lambda: _spawn_holders(machine))+ j.step("list_live", lambda: machine.hermes("update", "--list-venv-holders", label="list-holders"))+ if j.ok("holders"):+ j.step("holders_stopped", lambda: _stop_holders(pids))+ j.step("list_none", lambda: machine.hermes("update", "--list-venv-holders", label="list-none"))+ yield j+ finally:+ machine.teardown()+++def test_update_fetches_into_the_installers_partial_clone(journey: Journey) -> None:+ m, run, flt = journey.machine, journey["update"], journey["partial_filter"]+ assert flt, fail_with(m, "harness: the installer's clone is not partial (no remote.origin.partialclonefilter); "+ "serve.git should allow filters")+ fetch_bug = next((ln.strip() for ln in run.stdout.splitlines() if "BUG:" in ln or "fatal:" in ln), "")+ with known_gate(KNOWN, "partial_fetch"):+ assert run.returncode == 0 and m.installed_head() == m.next, fail_with(+ m, f"hermes update over the installer's partial clone failed: rc={run.returncode}, checkout at "+ f"{m.installed_head()} (NEXT {m.next}); {fetch_bug or 'no git error printed'}", run)+++def test_list_venv_holders_reports_live_holders(journey: Journey) -> None:+ m, pids, run = journey.machine, journey["holders"], journey["list_live"]+ reported = _reported(run)+ assert reported is not None, fail_with(m, "--list-venv-holders printed no JSON list", run)+ with known_gate(KNOWN, "holders"):+ assert run.returncode == VENV_HOLDERS_EXIT and set(pids) <= set(reported), fail_with(+ m, f"`hermes update --list-venv-holders` did not report the live venv holders {pids} "+ f"(rc={run.returncode}, reported pids {reported})", run)+++def test_list_venv_holders_empty_once_they_exit(journey: Journey) -> None:+ m, run = journey.machine, journey["list_none"]+ journey["holders_stopped"]+ reported = _reported(run)+ assert run.returncode == 0 and reported == [], fail_with(+ m, f"with no venv holders left, --list-venv-holders exited {run.returncode} reporting {reported}", run)diff --git a/tests/e2e/core/windows_update/test_interpreter.py b/tests/e2e/core/windows_update/test_interpreter.pynew file mode 100644index 00000000000..3cdb7b00f30--- /dev/null+++ b/tests/e2e/core/windows_update/test_interpreter.py@@ -0,0 +1,155 @@+"""Which interpreter and which site-packages a Windows gateway runs on after an update.++Failure class: interpreter. Real Windows machines carry two traps the managed runtime+must ignore:++* a different, standalone Python on PATH ahead of anything Hermes installed (#123185);+* the pre-PM in-tree ``hermes-agent\\venv`` an older install left behind (#123965, #123972).++After ``hermes update`` the gateway the user starts through ``hermes.exe`` must run on+the managed Python under ``%LOCALAPPDATA%\\hermes`` and must never add the stale venv to+``sys.path`` or publish it to its children. The stale venv carries a ``.pth`` hook that+drops a ``<pid>`` marker whenever any process adds its site dir, so "loaded the stale+venv" is observed directly rather than inferred from a crash.+"""++from __future__ import annotations++import os+import re+import time+from pathlib import Path++import psutil+import pytest++from tests.e2e.core._pending_fixes import known_gate+from tests.e2e.core.windows_update._machine import (+ REQUIRES_OPT_IN,+ Journey,+ Machine,+ fail_with,+ new_machine,+ one_shot_turn,+)+from tests.fakes.fake_llm_provider import FakeLLMServer++pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,+ pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]++KNOWN = {+ "path_python": (r"^the gateway runs on a Python outside the managed runtime",+ "gated on #123185: the Windows gateway boots under a newer system Python on PATH"),+ "stale_venv": (r"^the gateway loaded the stale pre-PM in-tree venv",+ "gated on #123965/#123972: the Windows gateway adds the stale in-tree venv to sys.path"),+}+_WORKER_DEATH = re.compile(r"^.*Supervised task \S+ died.*$", re.M)+++def _system_python_dir() -> Path:+ """The newest standalone CPython in the runner's tool cache: the "Python on PATH"."""+ cache = Path(os.environ.get("RUNNER_TOOL_CACHE") or r"C:\hostedtoolcache\windows")+ found = sorted(cache.glob("Python/3.*/x64/python.exe"),+ key=lambda p: tuple(int(x) for x in re.findall(r"\d+", p.parent.parent.name)[:3]))+ assert found, f"harness: no standalone CPython under {cache} to put on PATH"+ return found[-1].parent+++def _seed_stale_venv(machine: Machine) -> Path:+ """A pre-PM in-tree venv as older installs left it, with a load detector."""+ markers = machine.root / "stale-venv-loads"+ markers.mkdir(parents=True, exist_ok=True)+ venv = machine.install_dir / "venv"+ site = venv / "Lib" / "site-packages"+ site.mkdir(parents=True, exist_ok=True)+ (venv / "Scripts").mkdir(exist_ok=True)+ (venv / "pyvenv.cfg").write_text(+ "home = C:\\Python311\ninclude-system-site-packages = false\nversion = 3.11.15\n", encoding="utf-8")+ (site / "zz_e2e_stale_venv_probe.pth").write_text(+ f"import os; open(os.path.join({str(markers)!r}, str(os.getpid())), 'w').close()\n", encoding="utf-8")+ return markers+++def _loaded_by(markers: Path) -> set[int]:+ return {int(p.name) for p in markers.iterdir() if p.name.isdigit()} if markers.is_dir() else set()+++def _under(path: str, root: Path) -> bool:+ norm = os.path.normcase(os.path.normpath(path))+ base = os.path.normcase(os.path.normpath(str(root)))+ return norm == base or norm.startswith(base + os.sep)++[email protected](scope="module")+def journey(tmp_path_factory):+ system_python = _system_python_dir()+ with FakeLLMServer() as srv:+ machine = new_machine(tmp_path_factory.mktemp("interp"), srv.base_url, label="interp")+ j = Journey(machine)+ try:+ install = j.step("install", machine.install)+ if j.ok("install"):+ j.step("install_ok", lambda: j.require("install", install.returncode == 0,+ f"install.ps1 exited {install.returncode}", install))+ if j.ok("install_ok"):+ markers = _seed_stale_venv(machine)+ j.results["markers"] = markers+ # From here on the user has installed a standalone Python and put it first on PATH.+ machine.path_prepend = [str(system_python), str(system_python / "Scripts")]+ j.results["system_python"] = system_python+ machine.advance()+ update = j.step("update", machine.update)+ if j.ok("update"):+ j.step("update_ok", lambda: j.require("update", update.returncode == 0,+ f"hermes update exited {update.returncode}", update))+ if j.ok("update_ok"):+ j.step("spawn", machine.spawn_gateway)+ state = j.step("state", machine.wait_gateway_running)+ if j.ok("state"):+ time.sleep(15) # supervised workers start ~2 s after boot; give them room to die+ j.step("gateway_proc", lambda: _inspect(int(state["pid"])))+ j.step("turn", lambda: one_shot_turn(machine, srv, "turn-stale-venv"))+ yield j+ finally:+ machine.teardown()+++def _inspect(pid: int) -> dict:+ proc = psutil.Process(pid)+ env = {k.upper(): v for k, v in proc.environ().items()}+ return {"pid": pid, "exe": proc.exe(), "cmdline": proc.cmdline(),+ "VIRTUAL_ENV": env.get("VIRTUAL_ENV", ""), "PYTHONPATH": env.get("PYTHONPATH", "")}+++def test_gateway_runs_on_managed_python(journey: Journey) -> None:+ m, info = journey.machine, journey["gateway_proc"]+ system_python = journey["system_python"]+ with known_gate(KNOWN, "path_python"):+ assert _under(info["exe"], m.hermes_home) and not _under(info["exe"], system_python), fail_with(+ m, f"the gateway runs on a Python outside the managed runtime: {info['exe']} "+ f"(PATH starts with {system_python}; managed runtime lives under {m.hermes_home})")+++def test_gateway_does_not_load_stale_in_tree_venv(journey: Journey) -> None:+ m, info, markers = journey.machine, journey["gateway_proc"], journey.results["markers"]+ stale = str(m.install_dir / "venv")+ published = [k for k in ("VIRTUAL_ENV", "PYTHONPATH")+ if os.path.normcase(stale) in os.path.normcase(info[k])]+ loaded = info["pid"] in _loaded_by(markers)+ log = m.hermes_home / "logs" / "gateway.log"+ deaths = _WORKER_DEATH.findall(log.read_text(encoding="utf-8", errors="replace")) if log.is_file() else []+ with known_gate(KNOWN, "stale_venv"):+ assert not loaded and not published, fail_with(+ m, f"the gateway loaded the stale pre-PM in-tree venv {stale} (site dir added in the gateway "+ f"pid {info['pid']}={loaded}; published via {published or 'nothing'}; worker deaths: {deaths[:3]})")+ assert not deaths, fail_with(m, f"gateway supervised workers died: {deaths[:5]}")+++def test_cli_turn_ignores_stale_venv_and_path_python(journey: Journey) -> None:+ m, turn, markers = journey.machine, journey["turn"], journey.results["markers"]+ gateway_pid = journey["gateway_proc"]["pid"] if journey.ok("gateway_proc") else None+ others = sorted(_loaded_by(markers) - {gateway_pid})+ assert turn.ok, fail_with(+ m, f"a turn with a stale in-tree venv and a system Python on PATH failed (reply printed="+ f"{turn.reply_id in turn.run.stdout}, prompt reached provider={turn.reached_wire})", turn.run)+ assert not others, fail_with(m, f"CLI processes loaded the stale pre-PM in-tree venv: pids {others}", turn.run)diff --git a/tests/e2e/core/windows_update/test_paths_and_acls.py b/tests/e2e/core/windows_update/test_paths_and_acls.pynew file mode 100644index 00000000000..2b2daeb4302--- /dev/null+++ b/tests/e2e/core/windows_update/test_paths_and_acls.py@@ -0,0 +1,187 @@+"""A Windows user profile path with non-ASCII characters and a space, and tool ACLs.++Failure class: paths and ACLs.++* ``C:\\Users\\Jörg Ñúñez`` is an ordinary Windows account. ``install.ps1`` must get+ through the uv ``python-deps`` stage there (#124526), and ``hermes`` must then work and+ update from that profile.+* After ``hermes update`` the managed toolchain under ``%LOCALAPPDATA%\\hermes\\tools``+ must still be executable by a non-elevated process: a logon Scheduled Task or Startup+ entry runs with a standard-user token even when the updating session was elevated+ (#122935). The runner session is elevated, so each tool is launched with a Basic User+ (SAFER_LEVELID_NORMALUSER) token, the same token ``runas /trustlevel:0x20000`` uses.+"""++from __future__ import annotations++import subprocess+from pathlib import Path++import pytest++from tests.e2e.core._pending_fixes import known_gate+from tests.e2e.core.windows_update._machine import (+ REQUIRES_OPT_IN,+ Journey,+ fail_with,+ new_machine,+ one_shot_turn,+)+from tests.fakes.fake_llm_provider import FakeLLMServer++pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,+ pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]++PROFILE_NAME = "Jörg Ñúñez e2e"+KNOWN = {+ "install": (r"^install\.ps1 failed for a profile path with non-ASCII characters and spaces: .*"+ r"is not recognized as the name of a cmdlet",+ "gated on #124526: a non-ASCII profile path breaks uv Python path resolution in python-deps"),+ "acl": (r"^managed tools are not executable by a non-elevated process after update: .*WinError 5",+ "gated on #122935: tools\\* keep a hardened DACL a standard-user token cannot execute"),+}+_TOOL_NAMES = {"python.exe", "node.exe", "git.exe", "uv.exe", "rg.exe"}+++def run_as_standard_user(argv: list[str], timeout: float = 120.0) -> tuple[int | None, str]:+ """``(exit code, "")`` or ``(None, launch error)`` for ``argv`` under a Basic User token."""+ import ctypes+ from ctypes import wintypes++ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)++ class STARTUPINFOW(ctypes.Structure):+ _fields_ = [("cb", wintypes.DWORD), ("lpReserved", wintypes.LPWSTR), ("lpDesktop", wintypes.LPWSTR),+ ("lpTitle", wintypes.LPWSTR), ("dwX", wintypes.DWORD), ("dwY", wintypes.DWORD),+ ("dwXSize", wintypes.DWORD), ("dwYSize", wintypes.DWORD), ("dwXCountChars", wintypes.DWORD),+ ("dwYCountChars", wintypes.DWORD), ("dwFillAttribute", wintypes.DWORD),+ ("dwFlags", wintypes.DWORD), ("wShowWindow", wintypes.WORD), ("cbReserved2", wintypes.WORD),+ ("lpReserved2", ctypes.c_void_p), ("hStdInput", wintypes.HANDLE),+ ("hStdOutput", wintypes.HANDLE), ("hStdError", wintypes.HANDLE)]++ class PROCESS_INFORMATION(ctypes.Structure):+ _fields_ = [("hProcess", wintypes.HANDLE), ("hThread", wintypes.HANDLE),+ ("dwProcessId", wintypes.DWORD), ("dwThreadId", wintypes.DWORD)]++ advapi32.SaferCreateLevel.argtypes = [wintypes.DWORD, wintypes.DWORD, wintypes.DWORD,+ ctypes.POINTER(wintypes.HANDLE), ctypes.c_void_p]+ advapi32.SaferComputeTokenFromLevel.argtypes = [wintypes.HANDLE, wintypes.HANDLE,+ ctypes.POINTER(wintypes.HANDLE), wintypes.DWORD,+ ctypes.c_void_p]+ advapi32.SaferCloseLevel.argtypes = [wintypes.HANDLE]+ advapi32.CreateProcessAsUserW.argtypes = [+ wintypes.HANDLE, wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p, wintypes.BOOL,+ wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(STARTUPINFOW),+ ctypes.POINTER(PROCESS_INFORMATION)]+ kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]+ kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]+ kernel32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]++ level, token = wintypes.HANDLE(), wintypes.HANDLE()+ # SAFER_SCOPEID_USER=2, SAFER_LEVELID_NORMALUSER=0x20000, SAFER_LEVEL_OPEN=1+ if not advapi32.SaferCreateLevel(2, 0x20000, 1, ctypes.byref(level), None):+ raise OSError(ctypes.get_last_error(), "SaferCreateLevel failed")+ try:+ if not advapi32.SaferComputeTokenFromLevel(level, None, ctypes.byref(token), 0, None):+ raise OSError(ctypes.get_last_error(), "SaferComputeTokenFromLevel failed")+ finally:+ advapi32.SaferCloseLevel(level)+ si, pi = STARTUPINFOW(), PROCESS_INFORMATION()+ si.cb = ctypes.sizeof(si)+ cmdline = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))+ try:+ if not advapi32.CreateProcessAsUserW(token, argv[0], cmdline, None, None, False,+ 0x08000000, None, None, ctypes.byref(si), ctypes.byref(pi)):+ err = ctypes.get_last_error()+ return None, f"WinError {err}: {ctypes.FormatError(err).strip()}"+ try:+ if kernel32.WaitForSingleObject(pi.hProcess, int(timeout * 1000)) != 0:+ kernel32.TerminateProcess(pi.hProcess, 1)+ return None, f"timed out after {timeout}s"+ code = wintypes.DWORD()+ kernel32.GetExitCodeProcess(pi.hProcess, ctypes.byref(code))+ return int(code.value), ""+ finally:+ kernel32.CloseHandle(pi.hProcess)+ kernel32.CloseHandle(pi.hThread)+ finally:+ kernel32.CloseHandle(token)+++def _standard_user_token_is_really_restricted(scratch: Path) -> str:+ """Harness control: the Basic User token runs system binaries and is not an admin."""+ out = scratch / "whoami-groups.txt"+ code, err = run_as_standard_user(+ [r"C:\Windows\System32\cmd.exe", "/d", "/c", f'whoami /groups /fo csv > "{out}"'])+ assert code == 0, f"harness: cannot launch cmd.exe with a Basic User token (code={code}, {err})"+ admins = [ln for ln in out.read_text(encoding="mbcs", errors="replace").splitlines() if "S-1-5-32-544" in ln]+ assert not admins or all("Deny only" in ln or "deny only" in ln.lower() for ln in admins), (+ f"harness: the Basic User token still holds Administrators: {admins}")+ return "ok"+++def _managed_tools(hermes_home: Path) -> list[Path]:+ tools = hermes_home / "tools"+ found = []+ for pattern in ("*/*.exe", "*/*/*.exe", "*/*/*/*.exe"):+ found += [p for p in tools.glob(pattern) if p.name.lower() in _TOOL_NAMES]+ return sorted(set(found))+++def _tool_runs(hermes_home: Path) -> list[tuple[Path, int | None, str]]:+ return [(exe, *run_as_standard_user([str(exe), "--version"])) for exe in _managed_tools(hermes_home)]++[email protected](scope="module")+def journey(tmp_path_factory):+ with FakeLLMServer() as srv:+ machine = new_machine(tmp_path_factory.mktemp("paths"), srv.base_url, label="paths",+ profile_name=PROFILE_NAME)+ j = Journey(machine)+ try:+ install = j.step("install", machine.install)+ if j.ok("install") and install.returncode == 0:+ j.step("version", lambda: machine.hermes("--version"))+ j.step("turn", lambda: one_shot_turn(machine, srv, "turn-unicode-profile"))+ machine.advance()+ j.step("update", machine.update)+ j.step("control", lambda: _standard_user_token_is_really_restricted(machine.root))+ j.step("tool_runs", lambda: _tool_runs(machine.hermes_home))+ yield j+ finally:+ machine.teardown()+++def test_install_from_non_ascii_profile_with_spaces(journey: Journey) -> None:+ m, run = journey.machine, journey["install"]+ first_error = next((ln.strip() for ln in run.stdout.splitlines() if "[X]" in ln or "✗" in ln), "<none>")+ with known_gate(KNOWN, "install"):+ assert run.returncode == 0, fail_with(+ m, f"install.ps1 failed for a profile path with non-ASCII characters and spaces: {first_error}", run)+++def test_hermes_works_and_updates_from_that_profile(journey: Journey) -> None:+ m = journey.machine+ version, turn, update = journey["version"], journey["turn"], journey["update"]+ assert version.returncode == 0 and "Hermes Agent v" in version.stdout, fail_with(+ m, "hermes --version fails from a non-ASCII profile", version)+ assert turn.ok, fail_with(+ m, f"a turn fails from a non-ASCII profile (reply printed={turn.reply_id in turn.run.stdout}, "+ f"prompt reached provider={turn.reached_wire})", turn.run)+ assert update.returncode == 0 and m.installed_head() == m.next, fail_with(+ m, f"hermes update from a non-ASCII profile exited {update.returncode}, checkout at {m.installed_head()}",+ update)+++def test_managed_tools_stay_executable_for_standard_user(journey: Journey) -> None:+ m, runs = journey.machine, journey["tool_runs"]+ journey["control"]+ journey["update"]+ assert any(exe.name.lower() == "python.exe" for exe, _, _ in runs), fail_with(+ m, f"no managed python.exe under {m.hermes_home / 'tools'}: {[str(e) for e, _, _ in runs]}")+ broken = [f"{exe.relative_to(m.hermes_home)}: {err or f'exit {code}'}" for exe, code, err in runs if code != 0]+ with known_gate(KNOWN, "acl"):+ assert not broken, fail_with(+ m, f"managed tools are not executable by a non-elevated process after update: {'; '.join(broken)}")