The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): disable plugins that no longer fit instead of failing the update
ethernetccf631701a24
diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.pyindex 516f32bab1d..069eba6aa61 100644--- a/hermes_cli/_update_takeover.py+++ b/hermes_cli/_update_takeover.py@@ -35,7 +35,9 @@ def prepare(request: dict) -> tuple[Path, dict[str, str]]:# Repair preserves the old stamp. Changed source inputs instead need# an ordinary sync, which builds and validates a fresh generation too.repair = repair_marker.is_file() and venv_is_current(project_root=root)- sync_venv(None if repair else extras, explicit=True, project_root=root, repair=repair)+ # An update never fails because of a plugin: misfits are disabled and reported.+ sync_venv(None if repair else extras, explicit=True, project_root=root, repair=repair,+ evict_incompatible_plugins=not repair)request["pm_receipt"] = receipt.last_for_update(correlation)publish_launchers(root)repair_marker.unlink(missing_ok=True)diff --git a/hermes_cli/post_update.py b/hermes_cli/post_update.pyindex 25ffb566d41..359c1b2cc88 100644--- a/hermes_cli/post_update.py+++ b/hermes_cli/post_update.py@@ -264,7 +264,7 @@ def step_provision_runtimes() -> dict:for name in problems:try:if name == "venv":- pm.sync_venv(explicit=True)+ pm.sync_venv(explicit=True, evict_incompatible_plugins=True)else:pm.ensure(name, explicit=True)refreshed.append(name)diff --git a/hermes_cli/runtime_state.py b/hermes_cli/runtime_state.pyindex 7a74b6e9d5f..9e36b0dba1e 100644--- a/hermes_cli/runtime_state.py+++ b/hermes_cli/runtime_state.py@@ -100,20 +100,26 @@ def recover_publication(project: Path) -> None:if row.get("kind") == "plugin":_recover_plugin_publication(project, row, journal)return- config = Path(row["config"])- if config.name != "config.yaml" or not config.resolve().is_relative_to(dependency_home_root().resolve()):- raise ValueError("config path is outside Hermes state")- previous = base64.b64decode(row["previous"], validate=True) if row["previous"] is not None else None+ # One row may carry several configs (a plugin eviction edits every home that enables it).+ entries = row["configs"] if "configs" in row else [row]+ configs = []+ for entry in entries:+ config = Path(entry["config"])+ if config.name != "config.yaml" or not config.resolve().is_relative_to(dependency_home_root().resolve()):+ raise ValueError("config path is outside Hermes state")+ previous = base64.b64decode(entry["previous"], validate=True) if entry["previous"] is not None else None+ configs.append((config, previous, entry.get("config_after")))if not row.get("committed") and _digest(runtime_facts_path(project)) == row["facts_before"]:- current = _digest(config)- prior = hashlib.sha256(previous).hexdigest() if previous is not None else None- if current not in (prior, row.get("config_after")):- raise ValueError("config changed after publication began; preserve it for manual recovery")+ for config, previous, after in configs:+ prior = hashlib.sha256(previous).hexdigest() if previous is not None else None+ if _digest(config) not in (prior, after):+ raise ValueError("config changed after publication began; preserve it for manual recovery")# No selection was published. Roll back before any plugin is loaded.- if previous is None:- config.unlink(missing_ok=True)- else:- _atomic_bytes(config, previous)+ for config, previous, _after in configs:+ if previous is None:+ config.unlink(missing_ok=True)+ else:+ _atomic_bytes(config, previous)journal.unlink()except (ValueError, KeyError, TypeError, OSError) as exc:raise RuntimeError(f"cannot recover dependency publication: {journal}: {exc}") from excdiff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex cd7ebc0f058..1baa5f72db3 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -149,7 +149,8 @@ def _prepare(request: dict, request_path: Path, result_path: Path) -> int:# This file runs from the new tree, so its lockfile carries the new# pins; tools (incl. bumped uv/python) land before the sync uses them.ensure_tools_for_sync()- pm.sync_venv(explicit=True, project_root=root)+ # An update never fails because of a plugin: misfits are disabled and reported.+ pm.sync_venv(explicit=True, project_root=root, evict_incompatible_plugins=True)finally:request["pm_receipt"] = receipt.last_for_update(update_id)_write_json(request_path, request)diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.pyindex 08046dcac2b..991f06fc27b 100644--- a/hermes_cli/venv_sync.py+++ b/hermes_cli/venv_sync.py@@ -119,7 +119,7 @@ def sync(project_root: Path | None = None, *, check: bool = False) -> dict:return {"state": "would-sync", "ok": True}publish_stage("Updating Python dependencies")refuse_foreign_owned_venv(root)- pm.sync_venv(explicit=True, project_root=root)+ pm.sync_venv(explicit=True, project_root=root, evict_incompatible_plugins=True)collect_superseded_generations(root)publish_launchers(root)return {"state": "synced", "ok": True}@@ -342,7 +342,7 @@ def _sync_source_dependencies(root: Path, *, arm: bool) -> None:# Same order as `hermes update`: an interrupted update or a hand-run# `git pull` leaves this tree's lockfile ahead of the installed tools.ensure_tools_for_sync()- pm.sync_venv(extras, explicit=True, project_root=root)+ pm.sync_venv(extras, explicit=True, project_root=root, evict_incompatible_plugins=True)collect_superseded_generations(root)# These can predate the swap. Once PM commits the replacement they# must not make early recovery immediately rebuild it a second time.diff --git a/pm/client.py b/pm/client.pyindex f196abadd1e..6063e79afda 100644--- a/pm/client.py+++ b/pm/client.py@@ -203,7 +203,7 @@ def ensure(name, *, base_env=None, explicit=False, progress=None, pause_event=Nodef sync_venv(extras=None, *, explicit=False, plugins: PluginInput | None = None, repair=False,- project_root: Path | None = None) -> None:+ project_root: Path | None = None, evict_incompatible_plugins: bool = False) -> None:from pm.environments import running_from_selected_environmentif extras and not explicit and not repair and not running_from_selected_environment(@@ -225,9 +225,11 @@ def sync_venv(extras=None, *, explicit=False, plugins: PluginInput | None = Noneforeign = project_root is not None and Path(project_root).resolve() != paths.repo_root().resolve()if is_runtime() and not foreign:from pm.install import sync_venv as direct- return direct(extras, explicit=explicit, plugins=plugins, repair=repair)+ return direct(extras, explicit=explicit, plugins=plugins, repair=repair,+ evict_incompatible_plugins=evict_incompatible_plugins)_request("sync_venv", {"extras": extras, "explicit": explicit, "repair": repair,- "plugins": plugin_inputs.encode(plugins)}, project_root=project_root)+ "plugins": plugin_inputs.encode(plugins),+ "evict_incompatible_plugins": evict_incompatible_plugins}, project_root=project_root)def ensure_tools_for_sync() -> None:diff --git a/pm/install.py b/pm/install.pyindex 6c7dd425c3f..f3921f8f7b5 100644--- a/pm/install.py+++ b/pm/install.py@@ -681,7 +681,8 @@ def _commit_selection(package, facts: Facts, change, *, enabled: list[str], stamdef sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False,- plugins: PluginInput | None = None, repair: bool = False) -> None:+ plugins: PluginInput | None = None, repair: bool = False,+ evict_incompatible_plugins: bool = False) -> None:"""Make the venv match uv.lock + the enabled extras. Extras union intothe installed state (one ledger); no-op when the stamp already matches.``repair`` restores the recorded dependency graph into a fresh generation,@@ -690,6 +691,9 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False,`hermes update`) — those are the remedy the lazy-install policy pointsat, so the policy does not apply to them. ``plugins`` names the onesource of plugin members (see pm.plugin_inputs); None discovers them from config.+ ``evict_incompatible_plugins`` is the update's contract: a discovered plugin that+ keeps the environment from building is disabled instead of failing the sync+ (see pm.plugin_eviction).Lazy installs OFF = the frozen feature set: whensecurity.allow_lazy_installs is false AND the bundle's@@ -710,6 +714,8 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False,try:if repair and (extras is not None or plugins is not None):raise ValueError("repair restores the recorded environment; it cannot change features or plugins")+ if evict_incompatible_plugins and (repair or plugins is not None or not explicit):+ raise ValueError("only an explicit sync of the discovered plugin selection may disable plugins")shipped, frozen = _feature_policy(extras, repair=repair)package = get_package("venv")from hermes_cli.runtime_state import recover_publication@@ -719,6 +725,12 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False,change = _publication(plugins)if isinstance(change, StagedPlugin) and not change.active:_publish_inactive(change)+ elif evict_incompatible_plugins:+ from pm.plugin_eviction import sync_evicting++ facts = Facts(paths.runtime_facts_path())+ fact = facts.get("venv") or _facts().get("venv") or {}+ sync_evicting(package, facts, fact, extras=extras, shipped=shipped, frozen=frozen, explicit=explicit)else:inputs = {"plugin_dirs": change.members} if change is not None else _member_inputs(plugins)facts = Facts(paths.runtime_facts_path(), strict=repair)diff --git a/pm/plugin_declarations.py b/pm/plugin_declarations.pyindex 2acfa1991bb..210cabe36b2 100644--- a/pm/plugin_declarations.py+++ b/pm/plugin_declarations.py@@ -57,6 +57,7 @@ class PythonDeclaration:pyproject: Path | Nonerequirements: tuple[str, ...]manifest: dict+ requires_python: str | None = None@propertydef external(self) -> bool:@@ -70,6 +71,17 @@ class PythonDeclaration:def is_member(self) -> bool:return not self.external and (self.pyproject is not None or bool(self.install_requirements))+ def python_error(self, version: str) -> str | None:+ """Why this member cannot join a workspace built for *version*; uv intersects every+ member's requires-python, so one excluding member fails the whole lock."""+ from packaging.specifiers import SpecifierSet++ if not self.is_member or not self.requires_python:+ return None+ if SpecifierSet(self.requires_python).contains(version, prereleases=True):+ return None+ return f"requires Python {self.requires_python}, but Hermes runs on Python {version}"+def __post_init__(self) -> None:if not self.external:applicable_requirements(self.requirements)@@ -129,7 +141,10 @@ def read_python_declaration(plugin_dir: Path) -> PythonDeclaration:specs = document.get("project", {}).get("dependencies", [])if not isinstance(specs, list) or any(not isinstance(v, str) for v in specs):raise ValueError(f"invalid project.dependencies: {project}")- return PythonDeclaration(tuple(files), project, tuple(specs), manifest)+ requires_python = document.get("project", {}).get("requires-python")+ if requires_python is not None and not isinstance(requires_python, str):+ raise ValueError(f"invalid project.requires-python: {project}")+ return PythonDeclaration(tuple(files), project, tuple(specs), manifest, requires_python)specs = []for key in ("pip_dependencies", "python_dependencies"):values = manifest.get(key, [])diff --git a/pm/plugin_eviction.py b/pm/plugin_eviction.pynew file mode 100644index 00000000000..295b476221e--- /dev/null+++ b/pm/plugin_eviction.py@@ -0,0 +1,163 @@+"""Keep an update alive when an enabled plugin no longer fits the new core.++Admission refuses a plugin that does not fit, because the user is choosing and can+choose again. An update has nobody to ask and must never fail because of a plugin:+core moved (a newer Python, a bumped pin, a newer manifest contract) under a plugin+that was admitted against the old core. Such a plugin is disabled in every home that+enables it, the reason reaches the operator and the receipt, and the update continues+with the rest. Only a core that cannot build on its own still fails.+"""+from __future__ import annotations++import base64+import hashlib+import io+import json+import subprocess+import sys+from pathlib import Path++from pm.environments import install_state_dir, runtime_facts_path+from pm.filesystem import durable_write_bytes, file_digest, read_bytes_or_none+from pm.package import InstallError++Entry = tuple[Path, str, Path] # (home plugins dir, selection key, plugin dir)+++def _interpreter_version() -> str:+ """The Python the generation is built for; a plugin's requires-python is judged against it."""+ from pm._uv import _toolchain++ tools = _toolchain(explicit=True)+ if tools is None:+ raise InstallError("venv", "PM's pinned toolchain is unavailable")+ probe = subprocess.run([str(tools[1]), "-I", "-c", "import platform; print(platform.python_version())"],+ capture_output=True, text=True, check=True, timeout=60)+ return probe.stdout.strip()+++def static_reasons(entries: list[Entry], python_version: str) -> dict[Path, str]:+ """Plugins that cannot join this core without running a resolver, keyed by resolved dir."""+ from pm.plugin_declarations import manifest_version_error, read_python_declaration++ reasons: dict[Path, str] = {}+ for _plugins_dir, _name, plugin_dir in entries:+ key = plugin_dir.resolve()+ if key in reasons:+ continue+ try:+ declaration = read_python_declaration(plugin_dir)+ manifest = manifest_version_error(declaration.manifest, plugin_dir.name)+ reason = (manifest.removeprefix(f"Plugin '{plugin_dir.name}' ") if manifest+ else declaration.python_error(python_version))+ except (OSError, ValueError, TypeError) as exc:+ reason = f"its dependency declaration cannot be read: {exc}"+ if reason:+ reasons[key] = reason+ return reasons+++class PluginEviction:+ """Config edits disabling the plugins in *reasons*; published like a plugin selection."""++ def __init__(self, entries: list[Entry], reasons: dict[Path, str]):+ from hermes_yaml import roundtrip_yaml+ from pm.publication import selection_snapshot++ self.configs = selection_snapshot()+ by_home: dict[Path, list[str]] = {}+ for plugins_dir, name, plugin_dir in entries:+ if plugin_dir.resolve() in reasons:+ by_home.setdefault(plugins_dir.parent, []).append(name)+ self.edits: list[tuple[Path, bytes | None, bytes]] = []+ for home, names in by_home.items():+ path = home / "config.yaml"+ previous = read_bytes_or_none(path)+ yaml = roundtrip_yaml()+ config = (yaml.load(previous.decode("utf-8-sig")) if previous else None) or {}+ # read_home_selection already proved plugins/memory are mappings and the lists are lists.+ plugins = config.get("plugins")+ if plugins is None:+ plugins = config["plugins"] = {}+ disabled = plugins.get("disabled")+ if disabled is None:+ disabled = plugins["disabled"] = []+ memory = config.get("memory")+ for name in names:+ if name not in disabled:+ disabled.append(name)+ # plugins.disabled does not veto memory.provider; the provider joins the union on its own.+ if isinstance(memory, dict) and str(memory.get("provider") or "").strip() == name:+ memory["provider"] = ""+ output = io.StringIO()+ yaml.dump(config, output)+ self.edits.append((path, previous, output.getvalue().encode("utf-8")))++ def publish(self, project: Path) -> None:+ from pm.publication import selection_snapshot++ if selection_snapshot() != self.configs:+ raise ValueError("plugin configuration changed while preparing publication; retry")+ row = {"configs": [{"config": str(path),+ "previous": base64.b64encode(previous).decode() if previous is not None else None,+ "config_after": hashlib.sha256(proposed).hexdigest()}+ for path, previous, proposed in self.edits],+ "facts_before": file_digest(runtime_facts_path(project))}+ durable_write_bytes(install_state_dir(project) / "publication.json", json.dumps(row).encode())+ for path, _previous, proposed in self.edits:+ durable_write_bytes(path, proposed)+++def sync_evicting(package, facts, fact: dict, *, extras, shipped, frozen, explicit: bool) -> None:+ """Build the discovered selection, disabling whatever plugin keeps it from building.++ Static misfits go first (no resolver needed). If the rest still fails, core alone is+ built to prove the plugins are the cause, then members are re-added in config order+ and each one that breaks the build is disabled too.+ """+ from pm import receipt+ from pm.install import _commit_selection, _runtime_state_matches, _target_selection+ from pm.workspace import _is_member_candidate, enabled_plugin_entries++ entries = enabled_plugin_entries(skip_invalid_secondary=True)+ reasons = static_reasons(entries, _interpreter_version())++ def members() -> list[Path]:+ return list(dict.fromkeys(plugin_dir for _plugins_dir, _name, plugin_dir in entries+ if plugin_dir.resolve() not in reasons and _is_member_candidate(plugin_dir)))++ def commit() -> None:+ enabled, stamp, inputs = _target_selection(package, fact, extras=extras, inputs={"plugin_dirs": members()},+ repair=False, shipped=shipped, frozen=frozen)+ receipt.record_feature_list(enabled)+ _commit_selection(package, facts, PluginEviction(entries, reasons) if reasons else None,+ enabled=enabled, stamp=stamp, inputs=inputs,+ current=_runtime_state_matches(fact, stamp), repair=False, explicit=explicit)++ kept = members()+ try:+ commit()+ except InstallError as failure:+ if not kept:+ raise+ enabled = _target_selection(package, fact, extras=extras, inputs={"plugin_dirs": []},+ repair=False, shipped=shipped, frozen=frozen)[0]+ try:+ package.apply(enabled, explicit=explicit, plugin_dirs=[])+ except InstallError:+ raise failure from None+ fitting: list[Path] = []+ for member in kept:+ try:+ package.apply(enabled, explicit=explicit, plugin_dirs=[*fitting, member])+ except InstallError as exc:+ reasons[member.resolve()] = f"the dependency environment no longer builds with it: {exc.cause[-400:]}"+ else:+ fitting.append(member)+ commit()+ for plugins_dir, name, plugin_dir in entries:+ reason = reasons.get(plugin_dir.resolve())+ if reason:+ message = f"Disabled plugin '{name}' in {plugins_dir.parent}: {reason}"+ print(f"⚠ {message}", file=sys.stderr, flush=True)+ receipt.record_warning(message)diff --git a/pm/workspace.py b/pm/workspace.pyindex 435deddfc9d..17c0f1d9f90 100644--- a/pm/workspace.py+++ b/pm/workspace.py@@ -167,16 +167,20 @@ def _is_member_candidate(plugin_dir: Path) -> bool:return read_python_declaration(plugin_dir).is_member-def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None,- installing: Path | None = None, skip_invalid_secondary: bool = False) -> list[Path]:- """Resolve the effective plugin selection without filtering dependency declarations."""+def enabled_plugin_entries(*, proposed_home=None, enabled=None, disabled=None,+ installing: Path | None = None,+ skip_invalid_secondary: bool = False) -> list[tuple[Path, str, Path]]:+ """``(home plugins dir, selection key, plugin dir)`` for every selected plugin, in config order.++ The key is what the home's config names, so a caller can edit that home's selection.+ """from pm.plugins_state import _is_directory, enabled_plugins_orderedselection = enabled_plugins_ordered(proposed_home=proposed_home, enabled=enabled, disabled=disabled, installing=installing,skip_invalid_secondary=skip_invalid_secondary,)- members = []+ entries = []for plugins_dir, names in selection.items():for name in names:relative = Path(name)@@ -187,8 +191,16 @@ def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None,if not proposed and not _is_directory(plugin_dir):plugin_dir = paths.repo_root() / "plugins" / relativeif proposed or _is_directory(plugin_dir):- members.append(plugin_dir)- return list(dict.fromkeys(members))+ entries.append((plugins_dir, name, plugin_dir))+ return entries+++def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None,+ installing: Path | None = None, skip_invalid_secondary: bool = False) -> list[Path]:+ """Resolve the effective plugin selection without filtering dependency declarations."""+ entries = enabled_plugin_entries(proposed_home=proposed_home, enabled=enabled, disabled=disabled,+ installing=installing, skip_invalid_secondary=skip_invalid_secondary)+ return list(dict.fromkeys(plugin_dir for _plugins_dir, _name, plugin_dir in entries))def enabled_member_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:diff --git a/tests/hermes_cli/test_post_update.py b/tests/hermes_cli/test_post_update.pyindex c974e6563cc..07c85c7c29a 100644--- a/tests/hermes_cli/test_post_update.py+++ b/tests/hermes_cli/test_post_update.py@@ -189,7 +189,8 @@ def test_provision_runtimes_reensures_only_what_pm_names(monkeypatch):monkeypatch.setattr(pm_ensure, "sealed", lambda: False)monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: True)monkeypatch.setattr(pm, "ensure", lambda name, explicit=False: ensured.append((name, explicit)))- monkeypatch.setattr(pm, "sync_venv", lambda explicit=False: ensured.append(("venv", explicit)))+ monkeypatch.setattr(pm, "sync_venv", lambda explicit=False, evict_incompatible_plugins=False:+ ensured.append(("venv", explicit and evict_incompatible_plugins)))result = post_update.step_provision_runtimes()diff --git a/tests/hermes_cli/test_update_completion_process.py b/tests/hermes_cli/test_update_completion_process.pyindex 617e26369ed..53b3b464f70 100644--- a/tests/hermes_cli/test_update_completion_process.py+++ b/tests/hermes_cli/test_update_completion_process.py@@ -38,8 +38,8 @@ def transition(tmp_path):# Deliberately incompatible: a cached OLD_API-only PM cannot prepare this tree.(root / "pm/__init__.py").write_text("from hermes_cli.probe import event\n"- "def sync_venv(*, explicit, project_root):\n"- " assert explicit\n"+ "def sync_venv(*, explicit, project_root, evict_incompatible_plugins):\n"+ " assert explicit and evict_incompatible_plugins\n"" event('prepare')\n")(root / "pm/receipt.py").write_text(diff --git a/tests/hermes_cli/test_update_launch_completion.py b/tests/hermes_cli/test_update_launch_completion.pyindex e48ed75e6a2..6f89f497e18 100644--- a/tests/hermes_cli/test_update_launch_completion.py+++ b/tests/hermes_cli/test_update_launch_completion.py@@ -143,7 +143,7 @@ def test_first_launch_syncs_without_marker_then_uses_completion_fact(tmp_path, m# It is obsolete after successful sync, not the trigger for that sync.(root / ".update-incomplete").write_text("pid=-1\n")assert venv_sync.prepare_launch(root, []) == Path(sys.executable)- assert calls == [(["all"], {"explicit": True, "project_root": root})]+ assert calls == [(["all"], {"explicit": True, "project_root": root, "evict_incompatible_plugins": True})]assert not (root / ".update-incomplete").exists()assert any("source_completion.py" in str(part) for cmd in completion_tail for part in cmd)assert venv_sync.prepare_launch(root, []) is Nonediff --git a/tests/hermes_cli/test_venv_sync.py b/tests/hermes_cli/test_venv_sync.pyindex 6d737ee09a5..4c174428b8c 100644--- a/tests/hermes_cli/test_venv_sync.py+++ b/tests/hermes_cli/test_venv_sync.py@@ -62,7 +62,8 @@ def _wire_pm(monkeypatch, *, current=False, error=None):calls = []monkeypatch.setattr(pm, "venv_is_current", lambda *, project_root: current)- def sync(*, explicit, project_root):+ def sync(*, explicit, project_root, evict_incompatible_plugins):+ assert evict_incompatible_plugins, "an update sync must disable misfit plugins, not fail"calls.append((project_root, explicit))if error:raise pm.InstallError("venv", error)diff --git a/tests/pm/test_plugin_survival_contract.py b/tests/pm/test_plugin_survival_contract.pyindex d71ac628a29..9cd6cd799a6 100644--- a/tests/pm/test_plugin_survival_contract.py+++ b/tests/pm/test_plugin_survival_contract.py@@ -332,6 +332,66 @@ def test_malformed_secondary_cannot_evict_recorded_member(admission_env, monkeypassert "profile-dep" in (Path(restored["resolved_lock"]).parent / "pyproject.toml").read_text()[email protected](not _uv_available(), reason="uv not on PATH")+def test_update_sync_disables_plugin_excluded_by_requires_python(admission_env):+ """An update never fails because of a plugin: a member whose requires-python excludes the+ interpreter core now runs on is disabled in every home that enables it (plugins.enabled in+ one, memory.provider in another), the rest build, and the next boot sees a current venv."""+ from pm.environments import runtime_facts_path, selected_venv+ from pm.install import sync_venv, venv_is_current+ from pm.lock import Facts+ from pm.package import InstallError++ tmp_path, home = admission_env+ core = tmp_path / "core"+ for name, requires in (("fits", ">=3.11"), ("too-old", f"<{sys.version_info[0]}.{sys.version_info[1]}")):+ plugin = home / "plugins" / name+ plugin.mkdir(parents=True)+ (plugin / "pyproject.toml").write_text(+ f'[project]\nname="{name}"\nversion="1"\nrequires-python="{requires}"\n'+ 'dependencies=[]\n[tool.uv]\npackage=false\n', encoding="utf-8",+ )+ (home / "config.yaml").write_text("# operator note\nplugins:\n enabled: [fits, too-old]\n", encoding="utf-8")+ profile = home / "profiles" / "work"+ _write_enabled(profile, [], provider="too-old")+ (profile / "plugins" / "too-old").mkdir(parents=True)+ (profile / "plugins" / "too-old" / "pyproject.toml").write_bytes(+ (home / "plugins" / "too-old" / "pyproject.toml").read_bytes().replace(b'name="too-old"', b'name="too-old-work"'))++ with pytest.raises(InstallError, match="Python requirement"):+ sync_venv(explicit=True) # admission semantics stay: an ordinary sync refuses++ sync_venv(explicit=True, evict_incompatible_plugins=True)++ workspace = Path(Facts(runtime_facts_path(core), strict=True).get("venv")["resolved_lock"]).parent+ assert selected_venv(core).is_dir()+ assert "fits" in (workspace / "pyproject.toml").read_text()+ assert "too-old" not in (workspace / "pyproject.toml").read_text()+ text = (home / "config.yaml").read_text(encoding="utf-8")+ assert "# operator note" in text+ assert "too-old" in yaml.safe_load(text)["plugins"]["disabled"]+ assert yaml.safe_load((profile / "config.yaml").read_text(encoding="utf-8"))["memory"]["provider"] == ""+ assert "too-old" in json.dumps(_latest_receipt(home).get("warnings"))+ assert venv_is_current(project_root=core) is True++[email protected](not _uv_available(), reason="uv not on PATH")+def test_update_sync_disables_later_plugin_of_unresolvable_union(admission_env):+ """Core moved under two admitted plugins that no longer co-resolve: the update keeps the+ first in config order, disables the one that breaks the build, and completes."""+ from pm.install import sync_venv, venv_is_current++ tmp_path, home = admission_env+ _local_conflict_members(home)+ _write_enabled(home, ["plug-a", "plug-b"])++ sync_venv(explicit=True, evict_incompatible_plugins=True)++ cfg = yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8"))+ assert cfg["plugins"]["disabled"] == ["plug-b"]+ assert venv_is_current(project_root=tmp_path / "core") is True++def test_active_context_home_exported_to_wrapper_subprocess(monkeypatch, tmp_path):from hermes_constants import reset_hermes_home_override, set_hermes_home_overridefrom tools.environments.local import build_subprocess_envdiff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex f803730d284..874f4e3895d 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -136,7 +136,7 @@ For an admitted source checkout, `hermes update` runs these phases:1. **Pre-update snapshot** — Hermes saves selected state files for every profile in that profile's `state-snapshots/` directory. These include pairing data, cron jobs, `config.yaml`, `.env`, and `auth.json`. Automatic quick snapshots skip individual files larger than 1 GiB. `updates.pre_update_backup` selects `quick`, `full`, or `off`. Full archives use the [backup exclusions](../reference/faq.md#hermes-backup-vs-hermes-profile-export). Recovery uses [Snapshots and rollback](../user-guide/checkpoints-and-rollback.md). Quick snapshots recover state files, not application code. The snapshot is best-effort: if it fails, the update prints a `⚠ Pre-update snapshot FAILED` warning and continues, and the receipt records `pre_update_backup` as a failed step (a deliberate `off`/`--no-backup` lands in the receipt's skips with its reason instead).2. **Code update** — applies the configured source branch or stable release tag and updates submodules.3. **Post-pull syntax validation + auto-rollback** — after the pull, Hermes compiles the nine critical files every `hermes` invocation imports at startup. If any fails to parse (e.g. an orphan merge-conflict marker, an accidentally truncated file), Hermes runs `git reset --hard <pre-pull-sha>` to roll the install back so your shell stays bootable. Re-run `hermes update` once the upstream fix lands.-4. **Dependency preparation** — PM provisions required tools and prepares a complete Python environment from the new lock, existing extras, and enabled plugin requirements. It validates that environment before publishing its selection.+4. **Dependency preparation** — PM provisions required tools and prepares a complete Python environment from the new lock, existing extras, and enabled plugin requirements. It validates that environment before publishing its selection. A plugin never fails the update: one that no longer fits the new core (its `requires-python` excludes Hermes's Python, its `requires_hermes`/`manifest_version` is out of range, or its dependencies no longer build alongside core and the plugins before it in config order) is added to `plugins.disabled` in every profile that enables it (a memory provider has `memory.provider` cleared). The update prints `⚠ Disabled plugin '<name>' in <home>: <reason>`, records it in the receipt's warnings, and continues. Re-enable it with `hermes plugins enable <name>` once the plugin ships a compatible release. Only a core that cannot build on its own fails this step.5. **Config migration** — detects new config options added since your version and prompts you to set them6. **Desktop rebuild (stage-and-swap)** — if the Hermes Desktop app was built from this checkout, it is rebuilt so the GUI matches the new code. The rebuild packs into a temporary staging directory next to `apps/desktop/release/`, verifies the staged app, and only then renames it over the previous build (on Windows a real-time scanner briefly holding `release/win-unpacked` is ridden out with a few short retries). A rebuild that fails at any point — corrupt Electron download, missing dependency, disk full — leaves the previous app untouched and launchable; the update fails at that step, and `hermes desktop --build-only --force-build` or the next `hermes update` retries the rebuild. On macOS the rebuilt bundle is then copied (with `ditto`, signature intact) over a stale `/Applications/Hermes.app` or `~/Applications/Hermes.app`, so the copy Finder and the Dock launch matches the backend; an installed copy that is currently running is left alone and the update tells you to quit it and run `hermes update` again.7. **Gateway auto-restart**: running gateways are refreshed after the update completes. Service-managed gateways (systemd on Linux, launchd on macOS) restart through the service manager. Manual gateways are relaunched when Hermes can map their PID to a profile. Manually launched `hermes serve` / `hermes dashboard` backends are different: the updater leaves them running and asks their owner to restart them. See [Manual backend restart reminders](#manual-backend-restart-reminders). Backends owned by a running Desktop app remain the app's responsibility.