The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e-upgrade): fresh install, profile-update cron and broken-import scenarios
teknium17f63e90f9d63
diff --git a/tests/e2e/core/upgrade/_install_helpers.py b/tests/e2e/core/upgrade/_install_helpers.pynew file mode 100644index 00000000000..e8939dac1c9--- /dev/null+++ b/tests/e2e/core/upgrade/_install_helpers.py@@ -0,0 +1,205 @@+"""Helpers for the fresh-install / update-with-user-state / profile-update suites.++Every process runs through ``_helpers.run`` (bwrap sandbox, allowlisted env, fake HOME). On top+of that this module stages what a real user machine looks like to the installer and updater:++* a local bare ``origin`` (``--shared`` onto this checkout: no network, no object copy) that+ the official clone URLs are rewritten to by the sandbox's own ``~/.gitconfig``, plus a ``git``+ wrapper that reports the official URL for ``remote get-url origin`` (``insteadOf`` would+ otherwise expose the local path and send the updater down the fork path);+* a managed ``$HERMES_HOME/bin/uv`` pointing at the host's uv (warm cache, no download);+* ``TMPDIR`` inside the sandbox root (the host's is not writable in the sandbox).+"""++from __future__ import annotations++import hashlib+import json+import os+import shutil+import sqlite3+import subprocess+from dataclasses import dataclass+from pathlib import Path++from tests.e2e.core.upgrade import _helpers as H++OFFICIAL_HTTPS = "https://github.com/NousResearch/hermes-agent.git"+OFFICIAL_SSH = "[email protected]:NousResearch/hermes-agent.git"+TRACEBACK = "Traceback (most recent call last)"+FAKE_KEY = "sk-fake-e2e-install-update"+++def real_uv() -> str | None:+ cand = shutil.which("uv") or str(H.REAL_HOME / ".hermes" / "bin" / "uv")+ return cand if cand and Path(cand).exists() else None+++def git(*args: str, cwd: Path, check: bool = True, env: dict | None = None) -> str:+ cp = subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, text=True,+ env=env or {**os.environ, "GIT_TERMINAL_PROMPT": "0"})+ if check and cp.returncode != 0:+ raise AssertionError(f"git {args} failed in {cwd}: {cp.stderr}")+ return cp.stdout.strip()+++def head_sha() -> str:+ return git("rev-parse", "HEAD", cwd=H.WORKTREE)+++def make_origin(root: Path, ref: str) -> Path:+ """Bare origin with ``main`` at ``ref``."""+ origin = root / "origin.git"+ git("clone", "-q", "--bare", "--shared", "--no-tags", str(H.WORKTREE), str(origin), cwd=root)+ git("update-ref", "refs/heads/main", ref, cwd=origin)+ git("symbolic-ref", "HEAD", "refs/heads/main", cwd=origin)+ git("config", "uploadpack.allowAnySHA1InWant", "true", cwd=origin)+ return origin+++def publish_commit(origin: Path, scratch: Path, message: str, files: dict[str, str]) -> str:+ """Add one upstream commit on origin/main (a new release the user updates to); returns its sha."""+ work = scratch / f"publish-{hashlib.sha1(message.encode()).hexdigest()[:8]}"+ if work.exists():+ shutil.rmtree(work)+ env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GIT_AUTHOR_NAME": "e2e", "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "e2e", "GIT_COMMITTER_EMAIL": "[email protected]"}+ git("clone", "-q", "--shared", "--no-checkout", "-b", "main", str(origin), str(work), cwd=scratch, env=env)+ git("reset", "-q", "main", cwd=work, env=env)+ for rel, text in files.items():+ p = work / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(text, encoding="utf-8")+ git("add", "--", rel, cwd=work, env=env)+ git("commit", "-q", "-m", message, cwd=work, env=env)+ git("push", "-q", "origin", "HEAD:main", cwd=work, env=env)+ return git("rev-parse", "HEAD", cwd=work)+++@dataclass+class Sandbox:+ root: Path+ env: dict[str, str]++ @property+ def home(self) -> Path:+ return Path(self.env["HOME"])++ @property+ def hermes_home(self) -> Path:+ return Path(self.env["HERMES_HOME"])++ @property+ def checkout(self) -> Path:+ return self.hermes_home / "hermes-agent"++ @property+ def hermes(self) -> str:+ """The command the installer put on PATH, as a user's shell resolves it."""+ return str(self.home / ".local" / "bin" / "hermes")++ def run(self, argv: list[str], *, timeout: float = 600, cwd: Path | None = None,+ input: str | None = None) -> subprocess.CompletedProcess:+ return H.run(argv, env=self.env, cwd=cwd or self.root, writable=[self.root], timeout=timeout, input=input)++ def cli(self, *args: str, timeout: float = 600) -> subprocess.CompletedProcess:+ return self.run([self.hermes, *args], timeout=timeout)+++def new_sandbox(root: Path, origin: Path | None = None, *, pythonpath: Path | None = None) -> Sandbox:+ """Empty fake HOME: no ``~/.hermes`` at all, only what a fresh machine with uv/git/node has."""+ root.mkdir(parents=True, exist_ok=True)+ wrap = root / "wrap"+ env = H.isolated_env(root, extra_path=[wrap], pythonpath=pythonpath)+ home = Path(env["HOME"])+ shutil.rmtree(home / ".hermes")+ (root / "tmp").mkdir(exist_ok=True)+ env["TMPDIR"] = str(root / "tmp")+ env["SHELL"] = "/bin/bash"+ # A fresh machine: ~/.local/bin is NOT on PATH yet; the installer must wire it up.+ managed = home / ".hermes" / "bin"+ managed.mkdir(parents=True)+ uv = managed / "uv"+ uv.write_text(f'#!/bin/sh\nif [ "$1" = self ]; then exit 0; fi\nexec "{real_uv()}" "$@"\n', encoding="utf-8")+ uv.chmod(0o755)+ if origin is not None:+ (home / ".gitconfig").write_text(+ f'[url "file://{origin}"]\n insteadOf = {OFFICIAL_HTTPS}\n insteadOf = {OFFICIAL_SSH}\n', encoding="utf-8")+ wrap.mkdir(exist_ok=True)+ real_git = shutil.which("git")+ shim = wrap / "git"+ shim.write_text(+ "#!/usr/bin/env bash\n"+ 'p2=""; p1=""\n'+ 'for a in "$@"; do\n'+ f' if [ "$p2" = remote ] && [ "$p1" = get-url ] && [ "$a" = origin ]; then echo "{OFFICIAL_HTTPS}"; exit 0; fi\n'+ ' p2="$p1"; p1="$a"\n'+ "done\n"+ f'exec "{real_git}" "$@"\n', encoding="utf-8")+ shim.chmod(0o755)+ return Sandbox(root=root, env=env)+++def run_installer(sb: Sandbox, *, timeout: float = 1800) -> subprocess.CompletedProcess:+ """HEAD's scripts/install.sh, non-interactive, as the documented `curl | bash` run does it."""+ script = sb.root / "install.sh"+ shutil.copy(H.WORKTREE / "scripts" / "install.sh", script)+ return sb.run(["bash", str(script), "--skip-setup", "--skip-browser", "--skip-computer-use", "--non-interactive"],+ timeout=timeout, input="")+++def provider_config(base_url: str, version: int | None, extra: str = "") -> str:+ """A hand-edited user config: comments, a key HEAD does not know, and the fake provider."""+ ver = f"_config_version: {version}\n" if version is not None else ""+ return (+ "# My Hermes config. Hand-edited; comments must survive.\n"+ "model:\n"+ " provider: custom\n"+ f" base_url: {base_url} # local fake provider\n"+ " default: fake-model\n"+ " context_length: 128000\n"+ "agent:\n"+ " api_max_retries: 1 # keep it snappy\n"+ "# A key this Hermes version does not know about (from a plugin or a newer release).\n"+ "my_future_section:\n"+ " nested_flag: true\n"+ " words: \"unicode é 漢字 and a # that is not a comment\"\n"+ f"{extra}{ver}"+ )+++def tree_digest(path: Path) -> dict[str, str]:+ """{relative path: sha256} of every regular file / symlink target under ``path``."""+ out: dict[str, str] = {}+ for p in sorted(path.rglob("*")):+ rel = str(p.relative_to(path))+ if p.is_symlink():+ out[rel] = "link:" + os.readlink(p)+ elif p.is_file():+ out[rel] = hashlib.sha256(p.read_bytes()).hexdigest()+ return out+++def db_state(db: Path) -> dict:+ con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)+ try:+ integrity = con.execute("PRAGMA integrity_check").fetchall()+ sessions = sorted(r[0] for r in con.execute("SELECT id FROM sessions"))+ msgs = con.execute("SELECT session_id, role, content FROM messages ORDER BY id").fetchall()+ finally:+ con.close()+ return {"integrity": integrity, "sessions": sessions,+ "messages": hashlib.sha256(repr(msgs).encode()).hexdigest(), "n_messages": len(msgs)}+++def cron_jobs(profile_home: Path) -> list[dict]:+ f = profile_home / "cron" / "jobs.json"+ if not f.exists():+ return []+ data = json.loads(f.read_text(encoding="utf-8"))+ items = data.get("jobs", data) if isinstance(data, dict) else data+ return [j for j in items if isinstance(j, dict)]+++def describe(cp: subprocess.CompletedProcess) -> str:+ return H.describe(cp)diff --git a/tests/e2e/core/upgrade/test_install_fresh.py b/tests/e2e/core/upgrade/test_install_fresh.pynew file mode 100644index 00000000000..4d81b2c2c77--- /dev/null+++ b/tests/e2e/core/upgrade/test_install_fresh.py@@ -0,0 +1,154 @@+"""Fresh install through the real `scripts/install.sh` into an empty HOME, then a re-run.++The installer is HEAD's own copy, run the way the documented one-liner runs it (non-interactive,+stdin at EOF, setup wizard skipped) inside the bwrap sandbox with an empty fake HOME that has+only a fresh distro's dotfiles. Its git clone is redirected to a local bare clone of this+checkout (``_install_helpers``); uv comes from the host's warm cache. After the install the+user's shell resolves ``hermes`` from ``~/.local/bin`` (the installer wires PATH into the+shell rc), ``hermes --version`` answers from the installed checkout, and a one-shot turn reaches+the (fake) provider and is persisted.++Re-running the installer on that live install (what users do to "repair" or to update) must be+idempotent: same checkout, user edits to config/.env/SOUL and their sessions byte-identical,+the PATH line not appended twice, and the install still works.+"""++from __future__ import annotations++import json+import re+import shutil++import pytest++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++pytestmark = [+ pytest.mark.linux_only,+ 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"),+]++RC_FILES = (".bashrc", ".profile")+# A fresh distro's skeleton dotfiles (as /etc/skel ships them): .bashrc bails out early for+# non-interactive shells, .profile sources it.+SKEL = {+ ".bashrc": "# ~/.bashrc\ncase $- in *i*) ;; *) return;; esac\nHISTSIZE=1000\n",+ ".profile": '# ~/.profile\nif [ -n "$BASH_VERSION" ] && [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc"; fi\n',+}+++def _path_lines(sb: I.Sandbox) -> dict[str, int]:+ """How many lines in each shell rc put ~/.local/bin on PATH."""+ out = {}+ for name in RC_FILES:+ text = (sb.home / name).read_text(encoding="utf-8")+ out[name] = sum(1 for line in text.splitlines()+ if ".local/bin" in line and "PATH" in line and not line.lstrip().startswith("#"))+ return out+++def _login_shell_hermes(sb: I.Sandbox) -> str:+ """Resolve `hermes` the way a new login shell would: PATH comes only from the rc files."""+ env = dict(sb.env)+ env["PATH"] = "/usr/local/bin:/usr/bin:/bin"+ cp = H.run(["bash", "-lc", "command -v hermes"], env=env, cwd=sb.root, writable=[sb.root], timeout=60)+ return cp.stdout.strip()+++def _state(sb: I.Sandbox) -> dict:+ hh = sb.hermes_home+ return {+ "config": (hh / "config.yaml").read_bytes(),+ "env": (hh / ".env").read_bytes(),+ "soul": (hh / "SOUL.md").read_bytes(),+ "db": I.db_state(hh / "state.db"),+ "custom_skill": I.tree_digest(hh / "skills" / "my-own-skill"),+ }++[email protected](scope="module")+def provider():+ with FakeLLMServer(default_text="fake reply for the install suite") as srv:+ yield srv++[email protected](scope="module")+def installed(tmp_path_factory, provider):+ root = tmp_path_factory.mktemp("fresh-install")+ origin = I.make_origin(root, I.head_sha())+ sb = I.new_sandbox(root / "sb", origin)+ for name, text in SKEL.items():+ (sb.home / name).write_text(text, encoding="utf-8")+ first = I.run_installer(sb)+ return sb, first+++def _turn(sb: I.Sandbox, provider: FakeLLMServer, marker: str) -> None:+ n = len(provider.main_requests())+ cp = sb.cli("-z", marker)+ assert cp.returncode == 0 and I.TRACEBACK not in cp.stdout + cp.stderr, I.describe(cp)+ assert provider.default_text in cp.stdout, I.describe(cp)+ new = provider.main_requests()[n:]+ assert len(new) == 1 and marker in json.dumps(new[0]["messages"]), "one-shot turn did not reach the provider once"+++def _configure(sb: I.Sandbox, provider: FakeLLMServer) -> None:+ py = str(sb.checkout / "venv" / "bin" / "python")+ ver = sb.run([py, "-c", "from hermes_cli.config_defaults import DEFAULT_CONFIG as D; print(D['_config_version'])"])+ assert ver.returncode == 0, I.describe(ver)+ 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# my note\n", encoding="utf-8")+ (sb.hermes_home / "SOUL.md").write_text("You are my own customised agent.\n", encoding="utf-8")+ skill = sb.hermes_home / "skills" / "my-own-skill"+ skill.mkdir(parents=True, exist_ok=True)+ (skill / "SKILL.md").write_text("---\nname: my-own-skill\ndescription: mine\n---\nDo my thing.\n", encoding="utf-8")+++def test_fresh_install_serves_head_and_runs_a_turn(installed, provider):+ sb, first = installed+ assert first.returncode == 0, "install.sh failed on an empty HOME:\n" + I.describe(first)+ assert I.git("rev-parse", "HEAD", cwd=sb.checkout) == I.head_sha(), "installed checkout is not the published commit"+ assert I.git("status", "--porcelain", "--untracked-files=no", cwd=sb.checkout) == "", "installer dirtied the checkout"+ # A new login shell finds the command through the rc files the installer edited.+ assert _login_shell_hermes(sb) == sb.hermes, "a new shell does not resolve `hermes` to the installed launcher"+ assert all(n >= 1 for n in _path_lines(sb).values()), f"PATH not wired into the shell rc: {_path_lines(sb)}"+ ver = sb.cli("--version")+ assert ver.returncode == 0 and I.TRACEBACK not in ver.stdout + ver.stderr, I.describe(ver)+ probe = sb.run([str(sb.checkout / "venv" / "bin" / "python"), "-c", "import hermes_cli, run_agent; print(hermes_cli.__file__); print(run_agent.__file__)"])+ assert probe.returncode == 0, I.describe(probe)+ for line in probe.stdout.split():+ assert line.startswith(str(sb.checkout)), f"installed venv imports code from outside the checkout: {line}"+ for rel in ("config.yaml", ".env", "SOUL.md"):+ assert (sb.hermes_home / rel).is_file(), f"installer did not seed ~/.hermes/{rel}"+ _configure(sb, provider)+ _turn(sb, provider, "first turn on a fresh install")+ db = I.db_state(sb.hermes_home / "state.db")+ assert db["integrity"] == [("ok",)] and len(db["sessions"]) == 1 and db["n_messages"] >= 2, db+++def test_rerunning_the_installer_is_idempotent(installed, provider):+ sb, first = installed+ assert first.returncode == 0, I.describe(first)+ if not (sb.hermes_home / "state.db").exists():+ _configure(sb, provider)+ _turn(sb, provider, "first turn on a fresh install")+ before = _state(sb)+ rc_before = _path_lines(sb)+ commit = I.git("rev-parse", "HEAD", cwd=sb.checkout)+ second = I.run_installer(sb)+ assert second.returncode == 0, "re-running install.sh on a working install failed:\n" + I.describe(second)+ assert re.search(r"(?i)traceback", second.stdout + second.stderr) is None, I.describe(second)+ assert I.git("rev-parse", "HEAD", cwd=sb.checkout) == commit, "re-run moved the checkout"+ after = _state(sb)+ for key in before:+ assert after[key] == before[key], f"re-running the installer changed the user's {key}"+ assert _path_lines(sb) == rc_before, f"PATH line appended again: {rc_before} -> {_path_lines(sb)}"+ assert _login_shell_hermes(sb) == sb.hermes+ _turn(sb, provider, "turn after re-running the installer")+ db = I.db_state(sb.hermes_home / "state.db")+ assert set(before["db"]["sessions"]) < set(db["sessions"]), "earlier session lost or new turn not persisted"diff --git a/tests/e2e/core/upgrade/test_profile_update_cron.py b/tests/e2e/core/upgrade/test_profile_update_cron.pynew file mode 100644index 00000000000..44260edc6e3--- /dev/null+++ b/tests/e2e/core/upgrade/test_profile_update_cron.py@@ -0,0 +1,151 @@+"""`hermes profile install` / `hermes profile update` against a real distribution with cron jobs.++A distribution author schedules jobs with the real CLI (``hermes -p author cron create``) and+publishes the profile directory; a user installs it, schedules a job of their own, and later+pulls the author's next version with ``hermes profile update``. Every step is a fresh sandboxed+CLI process over a fake HOME; the assertions read the cron store the scheduler itself reads+(``cron/jobs.json``) and the CLI's own ``cron list``.++Contract (documented in the command help and profile-distributions.md): shipped jobs are+installed but NOT auto-scheduled; an update refreshes the jobs the distribution ships, removes+the ones the author retired, and leaves the jobs the user added in place.+"""++from __future__ import annotations++import json+import shutil+from pathlib import Path++import pytest++from tests.e2e.core.upgrade import _helpers as H+from tests.e2e.core.upgrade import _install_helpers as I++pytestmark = [+ pytest.mark.linux_only,+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),+]+++class Gap(Exception):+ """A contract breach tracked in KNOWN. Not an AssertionError, so a strict xfail on it cannot+ swallow an unrelated failure (a crashed CLI, a missing job store) in the same test."""+++def gap(ok: bool, msg: str) -> None:+ if not ok:+ raise Gap(msg)+++KNOWN: dict[str, str] = {+ "keeps_user_jobs": "#120823 profile update replaces cron/jobs.json wholesale, deleting the user's own jobs",+ "install_paused": "#120823 profile install leaves shipped cron jobs enabled and scheduled",+}+++def known(key: str):+ return pytest.mark.xfail(strict=True, raises=Gap, reason=KNOWN[key]) if key in KNOWN else ()+++PY = str(H.WORKTREE / ".venv" / "bin" / "python")+++class World:+ def __init__(self, root: Path):+ self.root = root+ self.env = H.isolated_env(root, pythonpath=H.WORKTREE)+ (root / "tmp").mkdir(exist_ok=True)+ self.env["TMPDIR"] = str(root / "tmp")+ self.hermes_home = Path(self.env["HERMES_HOME"])+ self.src = root / "dist-src"+ self.log: list[str] = []+ self.after_install: list[dict] = []+ self.before_update: list[dict] = []+ self.after_update: list[dict] = []++ def cli(self, *args: str):+ cp = H.run([PY, "-m", "hermes_cli.main", *args], env=self.env, cwd=self.root, writable=[self.root], timeout=300)+ self.log.append(H.describe(cp, 1500))+ assert cp.returncode == 0 and I.TRACEBACK not in cp.stdout + cp.stderr, H.describe(cp)+ return cp++ @property+ def installed(self) -> Path:+ return self.hermes_home / "profiles" / "shipped-bot"+++def _by_name(jobs: list[dict]) -> dict[str, dict]:+ return {str(j.get("name")): j for j in jobs}+++def _is_scheduled(job: dict) -> bool:+ return bool(job.get("enabled", True)) and job.get("state") not in ("paused", "disabled")+++def _publish(world: World, version: str, soul: str, jobs: list[dict]) -> None:+ (world.src / "distribution.yaml").write_text(+ f"name: shipped-bot\nversion: {version}\ndescription: e2e distribution\n", encoding="utf-8")+ (world.src / "SOUL.md").write_text(soul, encoding="utf-8")+ store = world.src / "cron" / "jobs.json"+ data = json.loads(store.read_text(encoding="utf-8"))+ if isinstance(data, dict):+ data["jobs"] = jobs+ else:+ data = jobs+ store.write_text(json.dumps(data, indent=2), encoding="utf-8")++[email protected](scope="module")+def world(tmp_path_factory) -> World:+ w = World(tmp_path_factory.mktemp("profile-dist"))+ # The author builds the agent with the real CLI.+ w.cli("profile", "create", "author", "--no-alias")+ w.cli("-p", "author", "cron", "create", "--name", "weekly-digest", "0 9 * * 1", "write the weekly digest v1")+ w.cli("-p", "author", "cron", "create", "--name", "retired-job", "0 8 * * *", "a job the author retires in v2")+ author = w.hermes_home / "profiles" / "author"+ assert set(_by_name(I.cron_jobs(author))) == {"weekly-digest", "retired-job"}+ w.src.mkdir()+ shutil.copytree(author / "cron", w.src / "cron", ignore=shutil.ignore_patterns("*.lock", "output", "*.db*"))+ _publish(w, "1.0.0", "You are shipped-bot v1.\n", I.cron_jobs(author))+ # The user installs it.+ w.cli("profile", "install", str(w.src), "-y")+ w.after_install = I.cron_jobs(w.installed)+ # The user schedules a job of their own and pauses one shipped job they do not want.+ w.cli("-p", "shipped-bot", "cron", "create", "--name", "my-own-reminder", "0 7 * * *", "the user's own reminder")+ w.before_update = I.cron_jobs(w.installed)+ assert set(_by_name(w.before_update)) == {"weekly-digest", "retired-job", "my-own-reminder"}, w.before_update+ # The author ships v2: the digest prompt changes, retired-job is gone.+ v2 = [dict(j) for j in I.cron_jobs(author) if j.get("name") == "weekly-digest"]+ v2[0]["prompt"] = "write the weekly digest v2"+ _publish(w, "1.1.0", "You are shipped-bot v2.\n", v2)+ w.cli("profile", "update", "shipped-bot", "-y")+ w.after_update = I.cron_jobs(w.installed)+ return w+++def test_profile_update_refreshes_shipped_jobs_and_drops_retired_ones(world):+ jobs = _by_name(world.after_update)+ assert "weekly-digest" in jobs, f"shipped job missing after update: {world.after_update}"+ assert jobs["weekly-digest"].get("prompt") == "write the weekly digest v2", "shipped job definition not refreshed"+ assert "retired-job" not in jobs, "a job the author retired is still scheduled after `profile update`"+ assert sum(1 for j in world.after_update if j.get("name") == "weekly-digest") == 1, "shipped job duplicated"+ assert (world.installed / "SOUL.md").read_text(encoding="utf-8") == "You are shipped-bot v2.\n"+ listed = world.cli("-p", "shipped-bot", "cron", "list").stdout+ assert "weekly-digest" in listed and "retired-job" not in listed, listed++[email protected]("key", [pytest.param("keeps_user_jobs", marks=known("keeps_user_jobs"))])+def test_profile_update_keeps_the_users_own_cron_jobs(world, key):+ jobs = _by_name(world.after_update)+ gap("my-own-reminder" in jobs, f"`profile update` deleted the user's own cron job; jobs now: {sorted(jobs)}")+ assert jobs["my-own-reminder"].get("prompt") == "the user's own reminder"+ assert _is_scheduled(jobs["my-own-reminder"]), "the user's own job was paused by the update"++[email protected]("key", [pytest.param("install_paused", marks=known("install_paused"))])+def test_profile_install_does_not_auto_schedule_shipped_jobs(world, key):+ jobs = _by_name(world.after_install)+ assert set(jobs) == {"weekly-digest", "retired-job"}, world.after_install+ running = sorted(n for n, j in jobs.items() if _is_scheduled(j))+ gap(not running, f"shipped jobs are live right after `profile install` (documented: not auto-scheduled): {running}")diff --git a/tests/e2e/core/upgrade/test_update_userstate_import.py b/tests/e2e/core/upgrade/test_update_userstate_import.pynew file mode 100644index 00000000000..b21d22c4a94--- /dev/null+++ b/tests/e2e/core/upgrade/test_update_userstate_import.py@@ -0,0 +1,140 @@+"""`hermes import` of a broken backup archive must report failure, never "restored".++The archive is made by the real ``hermes backup`` from a populated home, then damaged the ways+archives really break (a download cut off half-way, a file that is not a zip at all, one member+whose bytes rotted, a target directory the importer cannot write). Each import runs as a fresh+sandboxed CLI over a home that already holds the user's current config; the contract is the+exit code and wording a script or the dashboard keys on, and that a failed import leaves the+existing home untouched.+"""++from __future__ import annotations++import shutil+import zipfile+from pathlib import Path++import pytest++from tests.e2e.core.upgrade import _helpers as H+from tests.e2e.core.upgrade import _install_helpers as I++pytestmark = [+ pytest.mark.linux_only,+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),+]++PY = str(H.WORKTREE / ".venv" / "bin" / "python")+RESTORED = "has been restored"+CURRENT_CONFIG = "# the user's CURRENT config, which a failed import must not touch\nmodel:\n default: current-model\n"+SKILL = "---\nname: demo\ndescription: demo skill from the backup\n---\n" + ("body line\n" * 400)+++class Gap(Exception):+ """Contract breach tracked in KNOWN (not an AssertionError: a crash still fails the test)."""+++KNOWN: dict[str, str] = {+ "partial": "#119953 import that skipped members prints 'restored' and exits 0",+ "rotten-member": "#121258 import of an archive with one corrupt member dies with a zlib.error traceback",+}+++def known(key: str):+ return pytest.mark.xfail(strict=True, raises=Gap, reason=KNOWN[key]) if key in KNOWN else ()+++def _home(root: Path, name: str) -> dict:+ env = H.isolated_env(root / name, pythonpath=H.WORKTREE)+ (root / name / "tmp").mkdir(exist_ok=True)+ env["TMPDIR"] = str(root / name / "tmp")+ return env+++def _cli(root: Path, env: dict, *args: str):+ return H.run([PY, "-m", "hermes_cli.main", *args], env=env, cwd=root, writable=[root], timeout=300)++[email protected](scope="module")+def archive(tmp_path_factory) -> tuple[Path, Path]:+ root = tmp_path_factory.mktemp("import")+ env = _home(root, "src")+ hh = Path(env["HERMES_HOME"])+ (hh / "config.yaml").write_text("# from the backup\nmodel:\n default: backup-model\n", encoding="utf-8")+ (hh / "SOUL.md").write_text("soul from the backup\n", encoding="utf-8")+ (hh / "skills" / "demo").mkdir(parents=True)+ (hh / "skills" / "demo" / "SKILL.md").write_text(SKILL, encoding="utf-8")+ out = root / "backup.zip"+ cp = _cli(root, env, "backup", "-o", str(out))+ assert cp.returncode == 0 and out.exists(), H.describe(cp)+ assert {"config.yaml", "SOUL.md", "skills/demo/SKILL.md"} <= set(zipfile.ZipFile(out).namelist())+ return root, out+++def _truncated(src: Path, dst: Path) -> None:+ data = src.read_bytes()+ dst.write_bytes(data[: len(data) // 2])+++def _not_a_zip(src: Path, dst: Path) -> None:+ dst.write_bytes(b"<html>502 Bad Gateway</html>\n" * 40)+++def _rotten_member(src: Path, dst: Path) -> None:+ """Flip bytes inside skills/demo/SKILL.md's compressed data: the central directory still+ lists every member, but that one fails its CRC on read."""+ shutil.copy(src, dst)+ with zipfile.ZipFile(dst) as zf:+ info = zf.getinfo("skills/demo/SKILL.md")+ raw = bytearray(dst.read_bytes())+ # local header: 30 fixed bytes + name + extra, then the compressed payload+ name_len = int.from_bytes(raw[info.header_offset + 26: info.header_offset + 28], "little")+ extra_len = int.from_bytes(raw[info.header_offset + 28: info.header_offset + 30], "little")+ start = info.header_offset + 30 + name_len + extra_len+ for i in range(start + 4, start + min(info.compress_size, 64) - 4):+ raw[i] ^= 0x5A+ dst.write_bytes(bytes(raw))+++BROKEN = {"truncated": _truncated, "not-a-zip": _not_a_zip, "rotten-member": _rotten_member}++[email protected]("kind", [pytest.param(k, marks=known(k)) for k in BROKEN])+def test_import_of_a_broken_archive_fails_and_leaves_the_home_alone(archive, kind):+ root, good = archive+ bad = root / f"{kind}.zip"+ BROKEN[kind](good, bad)+ env = _home(root, f"dst-{kind}")+ hh = Path(env["HERMES_HOME"])+ (hh / "config.yaml").write_text(CURRENT_CONFIG, encoding="utf-8")+ cp = _cli(root, env, "import", str(bad), "--force")+ out = cp.stdout + cp.stderr+ if I.TRACEBACK in out:+ raise Gap(f"import of a {kind} archive crashed instead of reporting it:\n" + H.describe(cp))+ assert cp.returncode != 0, f"import of a {kind} archive exited 0:\n" + H.describe(cp)+ assert RESTORED not in out, f"import of a {kind} archive claims success:\n" + H.describe(cp)+ if kind != "rotten-member":+ # Nothing readable in the archive: nothing may change.+ assert (hh / "config.yaml").read_text(encoding="utf-8") == CURRENT_CONFIG+ skill = hh / "skills" / "demo" / "SKILL.md"+ assert not skill.exists() or skill.read_text(encoding="utf-8") == SKILL, "a corrupt member was written as the skill"++[email protected]("key", [pytest.param("partial", marks=known("partial"))])+def test_import_that_skips_members_reports_incomplete(archive, key):+ root, good = archive+ env = _home(root, "dst-partial")+ hh = Path(env["HERMES_HOME"])+ locked = hh / "skills" / "demo"+ locked.mkdir(parents=True)+ locked.chmod(0o555) # left behind root-owned by an earlier `sudo hermes ...`+ try:+ cp = _cli(root, env, "import", str(good), "--force")+ finally:+ locked.chmod(0o755)+ out = cp.stdout + cp.stderr+ assert I.TRACEBACK not in out, H.describe(cp)+ assert (hh / "config.yaml").read_text(encoding="utf-8").startswith("# from the backup"), "readable members not restored"+ assert not (locked / "SKILL.md").exists(), "harness: the locked directory was writable"+ if cp.returncode == 0 or RESTORED in out:+ raise Gap("import skipped skills/demo/SKILL.md yet reported success:\n" + H.describe(cp))