Skip to content

The agent that grows with you

test(e2e/hosts): install/update on odd host shapes

teknium1b15bec7e5e6a
diff --git a/tests/e2e/core/upgrade/hosts/__init__.py b/tests/e2e/core/upgrade/hosts/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/e2e/core/upgrade/hosts/_hosts.py b/tests/e2e/core/upgrade/hosts/_hosts.py
new file mode 100644
index 00000000000..6389106449f
--- /dev/null
+++ b/tests/e2e/core/upgrade/hosts/_hosts.py
@@ -0,0 +1,160 @@
+"""Shared staging for the host-shape suites (odd paths, PATH shapes, permissions, libc).
+
+Everything runs through ``tests/e2e/core/upgrade/_helpers.py`` (bwrap sandbox, allowlisted env)
+and ``_install_helpers.py`` (local bare origin + URL rewrite, git wrapper). This module only adds
+what a host shape needs on top: a sandbox rooted at an arbitrary path, the configured fake
+provider, a one-shot turn, a background ``hermes gateway run`` and a login-shell probe.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import signal
+import subprocess
+import time
+from pathlib import Path
+
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.fakes.fake_llm_provider import FakeLLMServer
+
+UPDATE_TIMEOUT = 1500
+# What `prepare_launch` prints when it decides the install is stale and re-runs the source-update
+# completion. A healthy install prints neither on a plain launch.
+COMPLETION_BANNERS = ("completing source-update dependencies", "finishing an interrupted source update")
+
+
+def reran_completion(cp: subprocess.CompletedProcess) -> bool:
+ return any(b in cp.stdout + cp.stderr for b in COMPLETION_BANNERS)
+
+
+def make_origin(root: Path) -> Path:
+ """``I.make_origin`` at the commit under test, serving partial clones like GitHub does.
+
+ install.sh clones ``--filter=tree:0``. Without ``uploadpack.allowFilter`` the local origin
+ ignores the filter and must pack every blob in history, which a blobless developer
+ checkout (the ``--shared`` object store) cannot serve.
+ """
+ origin = I.make_origin(root, I.head_sha())
+ I.git("config", "uploadpack.allowFilter", "true", cwd=origin)
+ return origin
+
+
+def new_sandbox(root: Path, origin: Path) -> I.Sandbox:
+ """``I.new_sandbox`` with the launch-time source-update check a real user's process runs.
+
+ The shared sandbox env sets ``HERMES_DISABLE_LAZY_INSTALLS=1``, which also short-circuits
+ ``prepare_launch`` (the per-launch "is this install current?" check). Host-shape bugs live in
+ exactly that check (path strings that differ from one launch to the next), so these
+ sandboxes run without it, as users do.
+ """
+ sb = I.new_sandbox(root, origin)
+ sb.env.pop("HERMES_DISABLE_LAZY_INSTALLS", None)
+ return sb
+
+
+def ok(cp: subprocess.CompletedProcess) -> subprocess.CompletedProcess:
+ assert cp.returncode == 0 and I.TRACEBACK not in cp.stdout + cp.stderr, I.describe(cp)
+ return cp
+
+
+def configure(sb: I.Sandbox, provider: FakeLLMServer) -> None:
+ """Point the install at the fake provider with a current-version config."""
+ ver = ok(sb.run([sb.python, "-c", "from hermes_cli.config_defaults import DEFAULT_CONFIG as D; print(D['_config_version'])"]))
+ version = int(ver.stdout.strip().splitlines()[-1])
+ (sb.hermes_home / "config.yaml").write_text(I.provider_config(provider.base_url, version), encoding="utf-8")
+ (sb.hermes_home / ".env").write_text(f"OPENAI_API_KEY={I.FAKE_KEY}\n", encoding="utf-8")
+
+
+def turn(sb: I.Sandbox, provider: FakeLLMServer, marker: str, *, env: dict | None = None) -> subprocess.CompletedProcess:
+ """One ``hermes -z`` turn that must reach the provider exactly once and print its reply."""
+ n = len(provider.main_requests())
+ cp = H.run([sb.hermes, "-z", marker], env=env or sb.env, cwd=sb.root, writable=[sb.root], timeout=900)
+ assert cp.returncode == 0 and I.TRACEBACK not in cp.stdout + cp.stderr, I.describe(cp)
+ assert provider.default_text in cp.stdout, "the reply never reached stdout:\n" + I.describe(cp)
+ new = provider.main_requests()[n:]
+ assert len(new) == 1 and marker in json.dumps(new[0]["messages"]), (
+ f"one-shot turn reached the provider {len(new)} times (want 1):\n" + I.describe(cp))
+ return cp
+
+
+def login_shell(sb: I.Sandbox, script: str, *, path: str = "/usr/local/bin:/usr/bin:/bin") -> subprocess.CompletedProcess:
+ """Run ``script`` in a new interactive login bash: PATH comes only from the rc files."""
+ env = dict(sb.env, PATH=path)
+ bash = shutil.which("bash")
+ assert bash is not None, "bash required"
+ return H.run([bash, "-lic", script], env=env, cwd=sb.root, writable=[sb.root], timeout=120)
+
+
+def interpreter_paths(sb: I.Sandbox, python: str | None = None) -> dict:
+ """sys.path / PATH / sys.executable as the installed interpreter sees them."""
+ code = ("import json, os, sys; print(json.dumps({'sys_path': sys.path, 'path': os.environ.get('PATH', ''),"
+ " 'executable': sys.executable}))")
+ cp = ok(sb.run([python or sb.python, "-c", code]))
+ return json.loads(cp.stdout.strip().splitlines()[-1])
+
+
+def missing_entries(entries: list[str]) -> list[str]:
+ """Entries that name a location that does not exist (a mangled or half-quoted path)."""
+ return [e for e in entries
+ if e and not os.path.exists(e) and not e.endswith(".zip") and not e.endswith(".__path_hook__")]
+
+
+class Gateway:
+ """``hermes gateway run`` in the foreground of its own sandbox, as a user starts it by hand."""
+
+ def __init__(self, sb: I.Sandbox):
+ self.sb = sb
+ self.log = sb.root / "gateway-run.log"
+ self.proc: subprocess.Popen | None = None
+
+ def state(self) -> dict:
+ f = self.sb.hermes_home / "gateway_state.json"
+ try:
+ return json.loads(f.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {}
+
+ def start(self, timeout: float = 180) -> dict:
+ fh = open(self.log, "w", encoding="utf-8") # noqa: SIM115 - handed to the child
+ self.proc = subprocess.Popen(
+ H.sandbox_argv([self.sb.hermes, "gateway", "run"], writable=[self.sb.root]),
+ env=self.sb.env, cwd=str(self.sb.root), stdin=subprocess.DEVNULL, stdout=fh,
+ stderr=subprocess.STDOUT, start_new_session=True)
+ fh.close()
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ st = self.state()
+ if st.get("gateway_state") == "running":
+ return st
+ if self.proc.poll() is not None:
+ break
+ time.sleep(0.5)
+ raise AssertionError(
+ f"gateway did not reach gateway_state=running (rc={self.proc.poll()}, state={self.state()})\n"
+ + self.tail())
+
+ def tail(self, n: int = 6000) -> str:
+ parts = []
+ for label, p in (("gateway stdout", self.log), ("agent.log", self.sb.hermes_home / "logs" / "agent.log"),
+ ("errors.log", self.sb.hermes_home / "logs" / "errors.log")):
+ try:
+ parts.append(f"--- {label} ---\n{p.read_text(encoding='utf-8', errors='replace')[-n:]}")
+ except OSError:
+ parts.append(f"--- {label} --- (missing)")
+ return "\n".join(parts)
+
+ def stop(self) -> None:
+ if self.proc is None:
+ return
+ if self.proc.poll() is None:
+ try:
+ os.killpg(self.proc.pid, signal.SIGTERM)
+ self.proc.wait(timeout=60)
+ except subprocess.TimeoutExpired:
+ pass
+ except ProcessLookupError:
+ pass
+ H.kill_tree(self.proc)
diff --git a/tests/e2e/core/upgrade/hosts/test_libc_musl.py b/tests/e2e/core/upgrade/hosts/test_libc_musl.py
new file mode 100644
index 00000000000..6e2e0c65363
--- /dev/null
+++ b/tests/e2e/core/upgrade/hosts/test_libc_musl.py
@@ -0,0 +1,127 @@
+"""Install on a musl libc host (Alpine) through the real ``scripts/install.sh``.
+
+Failure class: libc. Hermes's PM store pins glibc (``-linux-gnu``) builds of uv, CPython and
+Node. On a musl host those binaries either fail to exec or, with the ``gcompat`` shim, load and
+segfault, so an install or update that publishes them leaves every later ``hermes`` command dead
+(#123682). The acceptable outcomes are: musl-compatible tools that run, or a refusal that tells
+the user why (names musl) and publishes nothing unrunnable.
+
+The host shape is a real Alpine userland in a container (``docker run alpine``) with only what
+the documented one-liner needs (bash, git, curl). The installer's clone goes to a read-only
+bind-mounted bare origin at the commit under test; everything else (uv, Python, Node artifacts)
+comes from the network exactly as a user's install does. Skips with a reason when docker is not
+usable on this host.
+"""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core._pending_fixes import known_failure
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.hosts import _hosts as X
+
+IMAGE = "alpine:3.22"
+
+
+def _docker_reason() -> str | None:
+ exe = shutil.which("docker")
+ if exe is None:
+ return "docker CLI not installed; the musl host shape runs in an Alpine container"
+ try:
+ cp = subprocess.run([exe, "info", "--format", "{{.ServerVersion}}"], capture_output=True, text=True, timeout=30)
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ return f"docker daemon unreachable ({exc})"
+ if cp.returncode != 0:
+ return f"docker daemon unusable: {cp.stderr.strip()[:200]}"
+ return None
+
+
+DOCKER_REASON = _docker_reason()
+
+pytestmark = [
+ pytest.mark.platforms("linux"),
+ pytest.mark.skipif(DOCKER_REASON is not None, reason=str(DOCKER_REASON)),
+ pytest.mark.skipif(shutil.which("git") is None, reason="git required"),
+]
+
+# Runs as root inside the container. Everything the user would see goes to stdout; the probe
+# section after the install is fenced so the assertions can split it off.
+SCRIPT = r"""
+set -u
+apk add --no-cache -q bash git curl >/dev/null 2>&1 || { echo "HARNESS: apk add failed"; exit 90; }
+git config --global safe.directory '*'
+git config --global url."file://$ORIGIN".insteadOf https://github.com/NousResearch/hermes-agent.git
+echo "=== libc: $(ldd --version 2>&1 | head -n1)"
+bash /work/install.sh --non-interactive </dev/null
+echo "=== install rc=$?"
+echo "=== probes"
+for exe in "$HOME"/.hermes/tools/*/uv "$HOME"/.hermes/tools/*/bin/python3 "$HOME"/.hermes/tools/*/bin/node \
+ "$HOME"/.local/bin/hermes; do
+ [ -e "$exe" ] || continue
+ timeout 60 "$exe" --version >/dev/null 2>&1
+ echo "probe rc=$? $exe"
+done
+"""
+
+
[email protected](scope="module")
+def alpine_install(tmp_path_factory):
+ root = tmp_path_factory.mktemp("musl")
+ origin = X.make_origin(root)
+ work = root / "work"
+ work.mkdir()
+ shutil.copy(H.WORKTREE / "scripts" / "install.sh", work / "install.sh")
+ # The --shared origin borrows objects from this checkout's object store: mount it too.
+ objects = Path(I.git("rev-parse", "--path-format=absolute", "--git-common-dir", cwd=H.WORKTREE)) / "objects"
+ pull = subprocess.run(["docker", "pull", "-q", IMAGE], capture_output=True, text=True, timeout=600)
+ assert pull.returncode == 0, f"docker pull {IMAGE} failed (network?):\n{pull.stderr[-2000:]}"
+ argv = ["docker", "run", "--rm", "-e", f"ORIGIN={origin}",
+ "-v", f"{origin}:{origin}:ro", "-v", f"{objects}:{objects}:ro", "-v", f"{work}:/work:ro",
+ IMAGE, "sh", "-c", SCRIPT]
+ cp = subprocess.run(argv, capture_output=True, text=True, timeout=1800)
+ assert cp.returncode != 90, "harness: apk could not install bash/git/curl in the container:\n" + I.describe(cp)
+ return cp
+
+
+def _section(out: str) -> tuple[int | None, list[tuple[int, str]]]:
+ rc = None
+ probes: list[tuple[int, str]] = []
+ for line in out.splitlines():
+ if line.startswith("=== install rc="):
+ rc = int(line.rsplit("=", 1)[1])
+ elif line.startswith("probe rc="):
+ code, path = line[len("probe rc="):].split(" ", 1)
+ probes.append((int(code), path))
+ return rc, probes
+
+
+def test_musl_host_gets_runnable_tools_or_a_refusal_naming_musl(alpine_install):
+ cp = alpine_install
+ out = cp.stdout + cp.stderr
+ assert "=== libc:" in out and "musl" in out.split("=== libc:", 1)[1].splitlines()[0].lower(), (
+ "harness: the container is not a musl userland:\n" + I.describe(cp))
+ rc, probes = _section(cp.stdout)
+ assert rc is not None, "harness: the installer never returned inside the container:\n" + I.describe(cp)
+ # What install.sh itself printed: after the harness's libc banner, before its rc line.
+ head = cp.stdout.partition("=== install rc=")[0]
+ after_banner = head.partition("=== libc:")[2]
+ install_log = after_banner.partition("\n")[2] + cp.stderr
+ assert I.TRACEBACK not in install_log, "install.sh crashed with a traceback on musl:\n" + I.describe(cp)
+ dead = [f"{path} (rc={code})" for code, path in probes if code != 0]
+ with known_failure(r"musl host: (installer failed without naming musl|published tool binaries that cannot execute)",
+ "gated on #123682: no musl detection, so PM stages glibc uv/Python/Node on musl hosts"):
+ if rc != 0:
+ assert "musl" in install_log.lower(), (
+ f"musl host: installer failed without naming musl as the reason (rc={rc}):\n" + I.describe(cp))
+ assert not dead, ("musl host: published tool binaries that cannot execute: " + ", ".join(dead)
+ + "\n" + I.describe(cp))
+ if rc == 0:
+ hermes = [p for code, p in probes if p.endswith("/.local/bin/hermes")]
+ assert hermes, "musl host: install exited 0 but published no hermes command:\n" + I.describe(cp)
+
diff --git a/tests/e2e/core/upgrade/hosts/test_path_shapes.py b/tests/e2e/core/upgrade/hosts/test_path_shapes.py
new file mode 100644
index 00000000000..f4b058220a1
--- /dev/null
+++ b/tests/e2e/core/upgrade/hosts/test_path_shapes.py
@@ -0,0 +1,207 @@
+"""Install and run on hosts whose PATH and shell startup files are not a fresh skeleton.
+
+Failure class: PATH shapes. Two things users report once the install "works":
+
+* the installer's PATH wiring duplicates ``~/.local/bin`` when the distro's own startup files
+ already put it on PATH with a bare ``PATH=...`` assignment (Fedora ``.bashrc``, Debian
+ ``.profile``), and a re-run appends again (gated on #123424);
+* a node/npm the user already has, earlier on PATH, either shadows the managed toolchain where
+ Hermes needs the managed one (the TUI/web builds), or the managed node is forced onto an MCP
+ server the user configured with their own ``node`` (gated on #124264).
+
+One real install through HEAD's ``scripts/install.sh`` into a HOME carrying Fedora's stock
+``.bashrc`` / ``.bash_profile``, with a user-owned ``node``/``npm`` first on PATH. That node
+is a stand-in (the external edge): it answers version probes as v22 and logs every call; anything
+else it refuses loudly, except the user's own MCP server script, which it serves as a minimal
+stdio MCP server. The managed node running the same script instead exits the way a native addon
+built for the user's node does (``NODE_MODULE_VERSION`` mismatch) and records which node ran it.
+"""
+
+from __future__ import annotations
+
+import re
+import shutil
+import sys
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core._pending_fixes import known_failure
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.hosts import _hosts as X
+from tests.fakes.fake_llm_provider import FakeLLMServer
+
+pytestmark = [
+ pytest.mark.platforms("linux"),
+ pytest.mark.live_system_guard_bypass,
+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),
+ pytest.mark.skipif(shutil.which("git") is None, reason="git required"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+]
+
+# Fedora 44 /etc/skel, verbatim in the lines that matter: .bashrc puts ~/.local/bin on PATH with
+# a bare assignment (guarded against re-sourcing), .bash_profile sources .bashrc.
+FEDORA_SKEL = {
+ ".bashrc": (
+ "# .bashrc\n\n"
+ "# Source global definitions\n"
+ "if [ -f /etc/bashrc ]; then\n . /etc/bashrc\nfi\n\n"
+ "# User specific environment\n"
+ "if ! [[ \"$PATH\" =~ \"$HOME/.local/bin:$HOME/bin:\" ]]; then\n"
+ " PATH=\"$HOME/.local/bin:$HOME/bin:$PATH\"\n"
+ "fi\nexport PATH\n"
+ ),
+ ".bash_profile": (
+ "# .bash_profile\n\n"
+ "# Get the aliases and functions\n"
+ "if [ -f ~/.bashrc ]; then\n . ~/.bashrc\nfi\n\n"
+ "# User specific environment and startup programs\n"
+ ),
+}
+USER_NODE_VERSION = "v22.11.0"
+MINIMAL_MCP_SERVER = r'''
+import json, sys
+for line in sys.stdin:
+ line = line.strip()
+ if not line:
+ continue
+ msg = json.loads(line)
+ mid, method = msg.get("id"), msg.get("method")
+ if mid is None:
+ continue
+ if method == "initialize":
+ result = {"protocolVersion": msg.get("params", {}).get("protocolVersion", "2025-06-18"),
+ "capabilities": {"tools": {}}, "serverInfo": {"name": "user-node-server", "version": "1"}}
+ elif method == "tools/list":
+ result = {"tools": [{"name": "whoami", "description": "which node runs me",
+ "inputSchema": {"type": "object", "properties": {}}}]}
+ else:
+ result = {}
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": mid, "result": result}) + "\n")
+ sys.stdout.flush()
+'''
+
+
+def _user_toolchain(root: Path) -> dict[str, Path]:
+ """The user's own node/npm (first on PATH) plus their MCP server script."""
+ sysbin = root / "user-node" / "bin"
+ sysbin.mkdir(parents=True)
+ calls = root / "user-node" / "calls.log"
+ mcp_dir = root / "user-mcp"
+ mcp_dir.mkdir()
+ marker = mcp_dir / "ran-with.txt"
+ server_py = mcp_dir / "server.py"
+ server_py.write_text(MINIMAL_MCP_SERVER, encoding="utf-8")
+ server_js = mcp_dir / "server.js"
+ server_js.write_text(
+ "require('fs').writeFileSync(" + repr(str(marker)) + ", process.execPath + ' ' + process.version);\n"
+ "console.error(\"Error: The module 'better_sqlite3.node' was compiled against a different Node.js version "
+ "using NODE_MODULE_VERSION 127. This version of Node.js requires NODE_MODULE_VERSION \" + process.versions.modules);\n"
+ "process.exit(1);\n", encoding="utf-8")
+ python = shutil.which("python3") or sys.executable
+ versions = {"node": USER_NODE_VERSION, "npm": "10.9.0", "npx": "10.9.0"}
+ for name, ver in versions.items():
+ serve = f' *server.js) exec "{python}" "{server_py}" ;;\n' if name == "node" else ""
+ p = sysbin / name
+ p.write_text(
+ "#!/bin/sh\n"
+ f'printf "%s\\n" "{name} $*" >> "{calls}"\n'
+ 'case "$1" in\n'
+ f" --version|-v) echo {ver}; exit 0 ;;\n"
+ f"{serve}"
+ "esac\n"
+ f'echo "user {name} {ver}: refusing to run \'$*\' (Hermes must use its managed toolchain here)" >&2\n'
+ "exit 1\n", encoding="utf-8")
+ p.chmod(0o755)
+ return {"bin": sysbin, "calls": calls, "server_js": server_js, "marker": marker}
+
+
[email protected](scope="module")
+def provider():
+ with FakeLLMServer(default_text="fake reply for the PATH-shapes suite") as srv:
+ yield srv
+
+
[email protected](scope="module")
+def world(tmp_path_factory, provider):
+ root = tmp_path_factory.mktemp("path-shapes")
+ origin = X.make_origin(root)
+ sb = X.new_sandbox(root / "sb", origin)
+ for name, text in FEDORA_SKEL.items():
+ (sb.home / name).write_text(text, encoding="utf-8")
+ user = _user_toolchain(root)
+ # The user's node sits ahead of every system directory, as nvm/volta/distro packages do.
+ parts = sb.env["PATH"].split(":")
+ at = parts.index(str(sb.root / "wrap")) + 1
+ sb.env["PATH"] = ":".join([*parts[:at], str(user["bin"]), *parts[at:]])
+ first = I.run_installer(sb)
+ return {"sb": sb, "user": user, "install": first,
+ "rc_after_install": {n: (sb.home / n).read_text(encoding="utf-8") for n in FEDORA_SKEL}}
+
+
+def _local_bin_count(sb: I.Sandbox) -> tuple[int, str]:
+ probe = X.login_shell(sb, 'printf "PATH=%s\\n" "$PATH"')
+ assert probe.returncode == 0, H.describe(probe)
+ line = next((ln for ln in probe.stdout.splitlines() if ln.startswith("PATH=")), "")
+ entries = line[len("PATH="):].split(":")
+ return sum(1 for e in entries if e.rstrip("/") == str(sb.home / ".local" / "bin")), line
+
+
+def _calls(world) -> list[str]:
+ f = world["user"]["calls"]
+ return f.read_text(encoding="utf-8").splitlines() if f.exists() else []
+
+
+def test_user_node_first_on_path_does_not_shadow_the_managed_toolchain(world, provider):
+ sb, first = world["sb"], world["install"]
+ assert first.returncode == 0, "install.sh failed with the user's own node first on PATH:\n" + I.describe(first)
+ used = [c for c in _calls(world) if not re.fullmatch(r"(node|npm|npx) (--version|-v)", c)]
+ assert not used, ("the installer ran the user's node/npm for real work instead of the managed toolchain:\n"
+ + "\n".join(used) + "\n" + I.describe(first))
+ X.ok(sb.cli("--version"))
+ X.configure(sb, provider)
+ X.turn(sb, provider, "turn with the user's node first on PATH")
+
+
+def test_login_shell_has_local_bin_once_with_stock_fedora_startup_files(world):
+ sb, first = world["sb"], world["install"]
+ assert first.returncode == 0, I.describe(first)
+ count, line = _local_bin_count(sb)
+ assert count >= 1, f"a new login shell does not have ~/.local/bin on PATH at all: {line}"
+ rerun = I.run_installer(sb)
+ assert rerun.returncode == 0, "re-running install.sh failed:\n" + I.describe(rerun)
+ rc_after_rerun = {n: (sb.home / n).read_text(encoding="utf-8") for n in FEDORA_SKEL}
+ count_rerun, line_rerun = _local_bin_count(sb)
+ with known_failure(r"~/\.local/bin (appears [2-9]\d* times|was appended to stock startup files)",
+ "gated on #123424: wire_shell_path's existing-setup regex misses bare PATH= assignments"):
+ assert rc_after_rerun == world["rc_after_install"], (
+ "re-running the installer edited the startup files again: "
+ f"{[n for n in FEDORA_SKEL if rc_after_rerun[n] != world['rc_after_install'][n]]}")
+ changed = [n for n, text in FEDORA_SKEL.items() if world["rc_after_install"][n] != text]
+ assert count == 1 and count_rerun == 1, (
+ f"~/.local/bin appears {count} times on a login shell's PATH after install ({count_rerun} after a re-run):\n"
+ f"{line_rerun}\n(startup files the installer changed: {changed})")
+ assert not changed, f"~/.local/bin was appended to stock startup files that already set it: {changed}"
+
+
+def test_mcp_server_configured_with_the_users_node_runs_on_the_users_node(world, provider):
+ sb, user = world["sb"], world["user"]
+ assert world["install"].returncode == 0, I.describe(world["install"])
+ X.configure(sb, provider)
+ cfg = sb.hermes_home / "config.yaml"
+ cfg.write_text(cfg.read_text(encoding="utf-8")
+ + f"mcp_servers:\n usernode:\n command: node\n args: [\"{user['server_js']}\"]\n",
+ encoding="utf-8")
+ before = len(_calls(world))
+ probe = sb.cli("mcp", "test", "usernode", timeout=180)
+ ran_js = [c for c in _calls(world)[before:] if c.startswith("node ") and c.endswith("server.js")]
+ managed = user["marker"].read_text(encoding="utf-8") if user["marker"].exists() else ""
+ assert I.TRACEBACK not in probe.stdout + probe.stderr, I.describe(probe)
+ assert ran_js or managed, "harness: neither the user's node nor any other node ran the MCP server\n" + I.describe(probe)
+ with known_failure(r"MCP server configured with `command: node` ran on .*not the user's node",
+ "gated on #124264: the managed node is prepended to MCP stdio children's PATH"):
+ assert not managed and ran_js, (
+ f"MCP server configured with `command: node` ran on {managed!r}, not the user's node "
+ f"({user['bin'] / 'node'}, {USER_NODE_VERSION}):\n" + I.describe(probe))
+ assert probe.returncode == 0, "`hermes mcp test` failed although the user's node served the MCP server:\n" + I.describe(probe)
diff --git a/tests/e2e/core/upgrade/hosts/test_paths.py b/tests/e2e/core/upgrade/hosts/test_paths.py
new file mode 100644
index 00000000000..47f4d794ec0
--- /dev/null
+++ b/tests/e2e/core/upgrade/hosts/test_paths.py
@@ -0,0 +1,150 @@
+"""Install, update, gateway and a turn on homes whose paths are not plain ASCII.
+
+Failure class: path handling. Users run Hermes from homes like ``/home/José Müller`` or a
+CJK-named directory, and keep ``~/.hermes`` (or just its ``tools`` store) on another disk behind a
+symlink. Every path the installer and updater write (clone target, uv/python/node store, PM
+generation, the ``~/.local/bin/hermes`` launcher, the rc-file PATH line, sys.path) must survive a
+space, non-ASCII bytes and a symlink hop, and must stay stable from one launch to the next.
+
+Two real installs through HEAD's ``scripts/install.sh``:
+
+* ``odd_home``: the whole sandbox (HOME, HERMES_HOME, TMPDIR) lives under
+ ``José Müller 漢字 dir``. Then a one-shot turn, a new login shell resolving ``hermes``, an
+ upstream release and ``hermes update``, a turn on the new commit and ``hermes gateway run``.
+* ``linked_home``: ``~/.hermes`` is a symlink to a directory on "another volume" (a path with a
+ space and a non-ASCII char). Plain launches must not re-run the source-update completion. Then
+ an orchestrator-style per-task HERMES_HOME reaches the same ``tools``/``installs`` through
+ symlinks, which must not change the PM runtime's identity either (gated on #123798).
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+
+import pytest
+
+from tests.e2e.core._pending_fixes import known_failure
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.hosts import _hosts as X
+from tests.fakes.fake_llm_provider import FakeLLMServer
+
+pytestmark = [
+ pytest.mark.platforms("linux"),
+ pytest.mark.live_system_guard_bypass,
+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),
+ pytest.mark.skipif(shutil.which("git") is None, reason="git required"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+]
+
+ODD_DIR = "José Müller 漢字 dir"
+VOLUME_DIR = "external volume ü"
+
+
[email protected](scope="module")
+def provider():
+ with FakeLLMServer(default_text="fake reply for the host-paths suite") as srv:
+ yield srv
+
+
[email protected](scope="module")
+def odd_home(tmp_path_factory, provider):
+ root = tmp_path_factory.mktemp("paths-odd")
+ origin = X.make_origin(root)
+ sb = X.new_sandbox(root / ODD_DIR, origin)
+ (sb.home / ".bashrc").write_text("# ~/.bashrc\ncase $- in *i*) ;; *) return;; esac\n", encoding="utf-8")
+ (sb.home / ".profile").write_text('if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc"; fi\n', encoding="utf-8")
+ first = I.run_installer(sb)
+ return {"sb": sb, "origin": origin, "root": root, "install": first}
+
+
[email protected](scope="module")
+def linked_home(tmp_path_factory, provider):
+ root = tmp_path_factory.mktemp("paths-linked")
+ origin = X.make_origin(root)
+ sb = X.new_sandbox(root / "sb", origin)
+ real = root / "sb" / VOLUME_DIR / "hermes-data"
+ real.mkdir(parents=True)
+ os.symlink(real, sb.hermes_home)
+ first = I.run_installer(sb)
+ return {"sb": sb, "origin": origin, "root": root, "real": real, "install": first}
+
+
+def _pending_markers(sb: I.Sandbox) -> list[str]:
+ return sorted(str(p) for p in (sb.hermes_home / "installs").glob("*/source-completion-pending"))
+
+
+def test_install_update_gateway_and_turn_under_a_non_ascii_spaced_home(odd_home, provider):
+ sb, first = odd_home["sb"], odd_home["install"]
+ assert ODD_DIR in str(sb.home), "harness: sandbox HOME is not under the odd directory"
+ assert first.returncode == 0, "install.sh failed under a non-ASCII, spaced HOME:\n" + I.describe(first)
+ assert I.git("rev-parse", "HEAD", cwd=sb.checkout) == I.head_sha(), "installed checkout is not the published commit"
+ X.configure(sb, provider)
+ t1 = X.turn(sb, provider, "first turn under a non-ASCII home")
+ assert not X.reran_completion(t1), "the first launch after install re-ran the completion:\n" + I.describe(t1)
+
+ # A new login shell finds the launcher through the rc line the installer wrote.
+ probe = X.login_shell(sb, "command -v hermes; hermes --version >/dev/null && echo LAUNCH-OK")
+ assert probe.returncode == 0, H.describe(probe)
+ lines = probe.stdout.strip().splitlines()
+ assert lines and lines[0] == sb.hermes and "LAUNCH-OK" in lines, (
+ f"a new login shell does not run the installed launcher (want {sb.hermes}):\n" + H.describe(probe))
+
+ # Every sys.path entry of the selected interpreter names a real location.
+ seen = X.interpreter_paths(sb)
+ assert not X.missing_entries(seen["sys_path"]), f"sys.path names locations that do not exist: {X.missing_entries(seen['sys_path'])}"
+ assert os.path.exists(seen["executable"]), f"sys.executable does not exist: {seen['executable']!r}"
+
+ target = I.publish_commit(odd_home["origin"], odd_home["root"], "release: host-paths bump",
+ {"docs/e2e-host-paths-marker.txt": "release 1\n"})
+ up = sb.cli("update", "--yes", "--branch", "main", timeout=X.UPDATE_TIMEOUT)
+ assert up.returncode == 0 and I.TRACEBACK not in up.stdout + up.stderr, (
+ "hermes update failed under a non-ASCII, spaced HOME:\n" + I.describe(up))
+ assert I.git("rev-parse", "HEAD", cwd=sb.checkout) == target, "update exited 0 but HEAD is not the new release"
+ t2 = X.turn(sb, provider, "turn after updating under a non-ASCII home")
+ assert not X.reran_completion(t2), "the first launch after a finished update re-ran the completion:\n" + I.describe(t2)
+ seen = X.interpreter_paths(sb)
+ assert not X.missing_entries(seen["sys_path"]), f"after update, sys.path names missing locations: {X.missing_entries(seen['sys_path'])}"
+
+ gw = X.Gateway(sb)
+ try:
+ st = gw.start()
+ assert st.get("pid") and gw.proc.poll() is None, f"gateway state says running but the process is gone: {st}\n{gw.tail()}"
+ finally:
+ gw.stop()
+
+
+def test_symlinked_hermes_home_launches_without_rerunning_the_completion(linked_home, provider):
+ sb, first = linked_home["sb"], linked_home["install"]
+ assert sb.hermes_home.is_symlink(), "harness: ~/.hermes is not a symlink"
+ assert first.returncode == 0, "install.sh failed with ~/.hermes behind a symlink:\n" + I.describe(first)
+ assert (linked_home["real"] / "hermes-agent" / ".git").exists(), "install did not land on the symlink's target"
+ X.configure(sb, provider)
+ launches = [X.turn(sb, provider, f"turn {i} through a symlinked HERMES_HOME") for i in range(2)]
+ reruns = [i for i, cp in enumerate(launches) if X.reran_completion(cp)]
+ assert not reruns, (f"plain launches {reruns} re-ran the source-update completion on a healthy install:\n"
+ + I.describe(launches[reruns[0]]))
+ assert not _pending_markers(sb), f"a plain launch left source-completion-pending markers: {_pending_markers(sb)}"
+
+
+def test_per_task_home_sharing_the_tools_store_by_symlink_is_current(linked_home, provider):
+ """An orchestrator's per-task HERMES_HOME whose ``tools``/``installs`` link back to the main home."""
+ sb = linked_home["sb"]
+ assert linked_home["install"].returncode == 0, I.describe(linked_home["install"])
+ X.configure(sb, provider)
+ alt = linked_home["root"] / "per-task home ü"
+ alt.mkdir()
+ for name in ("tools", "installs"):
+ os.symlink(sb.hermes_home / name, alt / name)
+ for name in ("config.yaml", ".env"):
+ shutil.copy(sb.hermes_home / name, alt / name)
+ main = X.turn(sb, provider, "control turn in the main home")
+ assert not X.reran_completion(main), "control: the main home itself re-ran the completion:\n" + I.describe(main)
+ task = X.turn(sb, provider, "turn in a per-task home", env=dict(sb.env, HERMES_HOME=str(alt)))
+ with known_failure(r"per-task HERMES_HOME .* re-ran the source-update completion",
+ "gated on #123798: store_root() returns the unresolved $HERMES_HOME/tools, so the same "
+ "store through a symlink is a different PM runtime identity"):
+ assert not X.reran_completion(task), (
+ "a per-task HERMES_HOME whose tools/installs symlink to the main home re-ran the source-update "
+ "completion on a current install:\n" + I.describe(task))
diff --git a/tests/e2e/core/upgrade/hosts/test_permissions.py b/tests/e2e/core/upgrade/hosts/test_permissions.py
new file mode 100644
index 00000000000..b5cc9387363
--- /dev/null
+++ b/tests/e2e/core/upgrade/hosts/test_permissions.py
@@ -0,0 +1,121 @@
+"""Install trees the running user cannot write: turns keep working, updates fail and say why.
+
+Failure class: users and permissions. A second uid sharing an install (a root gateway whose
+workers run as other uids, #120151's topology), an admin-provisioned machine or an image leaves
+the code and PM state (checkout, tool store, ``installs/``) readable but not writable by the user
+who runs Hermes, while their own data under HERMES_HOME stays writable. On such a tree:
+
+* a turn must work: deciding that an install is current is a read, and nothing on the launch
+ path may need write access to the install (gated on #124635 while every launch opens PM
+ lock files for writing);
+* ``hermes update`` must exit non-zero with a message that names the permission problem, never
+ report success, never crash with a traceback, and leave the install on its old commit;
+* once the tree is writable again, the same ``hermes update`` succeeds: the refused attempt left
+ nothing behind that blocks the next one.
+
+One real install through HEAD's ``scripts/install.sh``; upstream then publishes a release. The
+read-only state is real file modes (``chmod -R a-w``), which is exactly what a different uid
+sees on a tree it does not own.
+"""
+
+from __future__ import annotations
+
+import re
+import shutil
+import subprocess
+
+import pytest
+
+from tests.e2e.core._pending_fixes import known_failure
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.hosts import _hosts as X
+from tests.fakes.fake_llm_provider import FakeLLMServer
+
+pytestmark = [
+ pytest.mark.platforms("linux"),
+ pytest.mark.live_system_guard_bypass,
+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),
+ pytest.mark.skipif(shutil.which("git") is None, reason="git required"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+]
+
+# What the install owns; HERMES_HOME itself (config, .env, sessions, logs) stays the user's.
+CODE_DIRS = ("hermes-agent", "tools", "installs")
+ACTIONABLE = re.compile(r"(?i)permission denied|read-only|not writable|no write access|EACCES|Errno 13")
+
+
+def _chmod_code(sb: I.Sandbox, *, writable: bool) -> None:
+ for name in CODE_DIRS:
+ subprocess.run(["chmod", "-R", "u+w" if writable else "a-w", str(sb.hermes_home / name)], check=True)
+
+
[email protected](scope="module")
+def provider():
+ with FakeLLMServer(default_text="fake reply for the permissions suite") as srv:
+ yield srv
+
+
[email protected](scope="module")
+def world(tmp_path_factory, provider):
+ root = tmp_path_factory.mktemp("perms")
+ origin = X.make_origin(root)
+ sb = X.new_sandbox(root / "sb", origin)
+ out = {"sb": sb, "install": I.run_installer(sb)}
+ try:
+ if out["install"].returncode == 0:
+ X.configure(sb, provider)
+ X.turn(sb, provider, "turn on a writable tree")
+ out["before"] = I.git("rev-parse", "HEAD", cwd=sb.checkout)
+ out["target"] = I.publish_commit(origin, root, "release: permissions bump",
+ {"docs/e2e-host-perms-marker.txt": "release 1\n"})
+ n = len(provider.main_requests())
+ _chmod_code(sb, writable=False)
+ try:
+ out["ro_turn"] = sb.run([sb.hermes, "-z", "turn on a read-only install tree"], timeout=900)
+ out["ro_turn_requests"] = len(provider.main_requests()) - n
+ out["ro_update"] = sb.cli("update", "--yes", "--branch", "main", timeout=X.UPDATE_TIMEOUT)
+ out["ro_head"] = I.git("rev-parse", "HEAD", cwd=sb.checkout)
+ finally:
+ _chmod_code(sb, writable=True)
+ out["rw_update"] = sb.cli("update", "--yes", "--branch", "main", timeout=X.UPDATE_TIMEOUT)
+ yield out
+ finally:
+ if sb.hermes_home.exists():
+ _chmod_code(sb, writable=True)
+
+
+def test_read_only_install_tree_still_runs_a_turn(world, provider):
+ assert world["install"].returncode == 0, "install.sh failed:\n" + I.describe(world["install"])
+ cp = world["ro_turn"]
+ err = cp.stdout + cp.stderr
+ assert I.TRACEBACK not in err, "a turn crashed on a read-only install tree:\n" + I.describe(cp)
+ with known_failure(r"read-only install tree: the turn failed .*Permission denied: .*/installs/.*\.lock",
+ "gated on #124635: every launch opens PM lock files under installs/ for writing, so a "
+ "uid without write access to the install cannot start Hermes"):
+ # Either it works, or it says the install is not writable by this user without sending them
+ # to a remedy that needs the same write access (`hermes pm repair`, "finish the update").
+ if cp.returncode != 0:
+ misleading = re.findall(r"run `hermes (?:pm repair|update)`[^\n]*", err)
+ assert ACTIONABLE.search(err) and not misleading, (
+ f"read-only install tree: the turn failed (rc={cp.returncode}) and pointed at remedies that need the "
+ f"same write access {misleading}: {cp.stderr.strip()[-800:].replace(chr(10), ' | ')}\n" + I.describe(cp))
+ if cp.returncode == 0:
+ assert provider.default_text in cp.stdout, "the reply never reached stdout:\n" + I.describe(cp)
+ assert world["ro_turn_requests"] == 1, f"the turn reached the provider {world['ro_turn_requests']} times (want 1)"
+
+
+def test_update_on_a_read_only_tree_refuses_with_a_reason_and_recovers(world, provider):
+ assert world["install"].returncode == 0, "install.sh failed:\n" + I.describe(world["install"])
+ up = world["ro_update"]
+ out = up.stdout + up.stderr
+ assert up.returncode != 0, "hermes update reported success on an install tree it cannot write:\n" + I.describe(up)
+ assert I.TRACEBACK not in out, "hermes update crashed on a read-only install tree:\n" + I.describe(up)
+ assert ACTIONABLE.search(out), "hermes update failed on a read-only tree without saying why:\n" + I.describe(up)
+ assert world["ro_head"] == world["before"], "a refused update still moved the checkout"
+ again = world["rw_update"]
+ assert again.returncode == 0 and I.TRACEBACK not in again.stdout + again.stderr, (
+ "after the tree became writable again, hermes update still failed:\n" + I.describe(again))
+ assert I.git("rev-parse", "HEAD", cwd=world["sb"].checkout) == world["target"], (
+ "update exited 0 but HEAD is not the new release")
+ X.turn(world["sb"], provider, "turn after the recovered update")