Skip to content

The agent that grows with you

feat(pm): assert plugin survival contracts through public admission

ethernet7964d7705906
diff --git a/pm/plugins_state.py b/pm/plugins_state.py
index 651e4f4e769..0039183b4d7 100644
--- a/pm/plugins_state.py
+++ b/pm/plugins_state.py
@@ -85,8 +85,12 @@ def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None)
The ACTIVE MEMORY PROVIDER joins its home's list: providers install
via ``memory.provider`` (mnemosyne's documented path), not via
plugins.enabled — without this, a provider's dep plugin never joins
- the union. The provider rides LAST (newest — the bisect's
- incumbent-wins tiebreak disables it before older plugins)."""
+ the union. GAP, stated honestly: pm has NO automatic bisect or
+ disable decision today — a resolver conflict fails loud and the
+ admission authority refuses the candidate; nothing disables plugins
+ on its own, so "prefer the memory provider" is not yet implemented
+ by any code path. When such a decision exists it must keep the
+ active memory provider over ordinary plugins."""
out: dict[Path, list[str]] = {}
for home in _all_homes():
# ONE parse per home feeds both queries (enabled + provider).
@@ -119,9 +123,10 @@ def _provider_from_config(home: Path, config: dict[str, Any]) -> Optional[str]:
def disable_plugins(names: list[str]) -> dict[str, list[str]]:
- """Remove names from EVERY home's enabled list (a bisect decision
- names the plugin, not the profile — disable where it's enabled).
- Returns per-home what was removed.
+ """Remove names from EVERY home's enabled list (an operator or
+ caller decision names the plugin, not the profile — disable where
+ it's enabled). There is NO automatic bisect in pm today; this is
+ the explicit write-back path. Returns per-home what was removed.
Writes go through utils.atomic_roundtrip_yaml_update — the same
atomic, comment-preserving round-trip writer the plugins CLI's
diff --git a/pm/workspace.py b/pm/workspace.py
index 500f333aa99..41289d98377 100644
--- a/pm/workspace.py
+++ b/pm/workspace.py
@@ -30,6 +30,7 @@ class ResolutionConflict(InstallError):
_RESOLVER_MARKERS = (
"no solution found",
"conflicting requirements",
+ "conflicting urls",
"because only the following versions",
"and your pyproject depends on",
)
diff --git a/tests/pm/test_plugin_survival_contract.py b/tests/pm/test_plugin_survival_contract.py
new file mode 100644
index 00000000000..9db256c2181
--- /dev/null
+++ b/tests/pm/test_plugin_survival_contract.py
@@ -0,0 +1,296 @@
+"""Plugin survival + upgrade contracts (mnemosyne-oss/mnemosyne#859).
+
+Hermes-side contracts an external memory-provider wrapper can hold us to,
+exercised through PUBLIC paths (no source inspection, no network — uv
+resolves offline local path-source fixtures):
+
+1. Sidecar isolation. A wrapper plugin exposes NO dependency surface at
+ the scanned plugin root (no pyproject.toml, no legacy dep keys); a
+ pyproject belonging to a nested or external sidecar dir must NOT
+ join the pm workspace union, because pm scans only plugin roots.
+2. Conflict admission. Through the PUBLIC admission authority
+ (hermes_cli.plugins_admission.admit_plugin_set_change — the one path
+ `hermes plugins enable/install` use), a candidate union with no
+ valid solution is REFUSED before anything is published: the
+ candidate stays unenabled (so the loader never imports it), the
+ plugin trees and every home's config.yaml survive untouched, the
+ refusal message carries the plugin identity + the resolver's
+ reason, and a machine-readable pm receipt records the failure.
+ The retry path — re-admitting only the resolvable candidate —
+ commits through the same public function.
+3. GAP, documented honestly in pm/plugins_state.py: pm has NO
+ automatic bisect/disable decision today, so "prefer the active
+ memory provider over ordinary plugins" is not implemented anywhere.
+ When such a decision exists it must keep the memory provider.
+4. Active-home propagation. The active CONTEXT home
+ (hermes_constants.set_hermes_home_override) is what wrapper/sidecar
+ subprocess launches must inherit: the detached respawn spec exports
+ the active home as HERMES_HOME, and a child process launched with
+ that overlay observes it.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+import yaml
+
+import pm.plugins_state as pstate
+import pm.workspace as ws
+
+
+def _write_enabled(home: Path, enabled: list, provider: str | None = None) -> None:
+ home.mkdir(parents=True, exist_ok=True)
+ cfg: dict = {"plugins": {"enabled": enabled}}
+ if provider:
+ cfg["memory"] = {"provider": provider}
+ with (home / "config.yaml").open("w", encoding="utf-8") as f:
+ yaml.safe_dump(cfg, f)
+
+
+def _uv_available() -> bool:
+ return shutil.which("uv") is not None
+
+
+# ---------------------------------------------------------------------------
+# 1. Sidecar with no root dependency surface never joins the union
+# ---------------------------------------------------------------------------
+
+def test_sidecar_no_root_pyproject_excludes_nested_and_external(tmp_path, monkeypatch):
+ """The mnemosyne-wrapper shape: plugin root has ONLY plugin.yaml +
+ marker; its runtime lives in sidecar dirs with their own pyprojects.
+ Neither the nested subdir pyproject nor the external one may join
+ the workspace union."""
+ home = tmp_path / "home"
+ _write_enabled(home, ["mnemosyne-wrapper"])
+ plugins_dir = home / "plugins"
+
+ wrapper = plugins_dir / "mnemosyne-wrapper"
+ wrapper.mkdir(parents=True)
+ (wrapper / "plugin.yaml").write_text("name: mnemosyne-wrapper\n", encoding="utf-8")
+ (wrapper / "mnemosyne-wrapper.json").write_text('{"wrapper": true}\n', encoding="utf-8")
+ # a nested pyproject INSIDE the plugin dir (below the scanned root)
+ nested = wrapper / "runtime"
+ nested.mkdir()
+ (nested / "pyproject.toml").write_text(
+ '[project]\nname = "mnemosyne-runtime"\nversion = "1.0.0"\n', encoding="utf-8"
+ )
+ # an EXTERNAL sidecar next to the plugin (the wrapper's own venv project)
+ external = plugins_dir / ".mnemosyne-sidecar"
+ external.mkdir()
+ (external / "pyproject.toml").write_text(
+ '[project]\nname = "mnemosyne-sidecar"\nversion = "1.0.0"\n', encoding="utf-8"
+ )
+
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ assert ws._is_member_candidate(wrapper) is False, (
+ "a wrapper root without pyproject/dep keys must never be a member candidate"
+ )
+ scan = ws.scan_plugin(wrapper)
+ assert scan["pyproject"] is False and scan["legacy_deps"] is False
+
+ members = ws.enabled_member_dirs()
+ member_names = [p.name for p in members]
+ assert "mnemosyne-wrapper" not in member_names
+ assert "mnemosyne-sidecar" not in member_names, (
+ "an external sidecar pyproject must not join the union — pm scans "
+ "only plugin roots, and the wrapper owns its runtime"
+ )
+ assert all("runtime" not in str(p) for p in members)
+
+
+# ---------------------------------------------------------------------------
+# 2. Conflict through the PUBLIC admission path: refused, preserved, retry
+# ---------------------------------------------------------------------------
+
+def _local_conflict_members(home: Path) -> tuple[Path, Path, Path, Path]:
+ """plug-a and plug-b both need a local project named sharedlib, but
+ map it to DIFFERENT path sources (v1 vs v2) — a union with NO valid
+ solution, resolvable by uv fully OFFLINE."""
+ shared1 = home / "sidecars" / "sharedlib-v1"
+ shared2 = home / "sidecars" / "sharedlib-v2"
+ for path, version in ((shared1, "1.0.0"), (shared2, "2.0.0")):
+ path.mkdir(parents=True)
+ (path / "pyproject.toml").write_text(
+ "[project]\nname = \"sharedlib\"\n"
+ f'version = "{version}"\nrequires-python = ">=3.11"\n',
+ encoding="utf-8",
+ )
+ plugins_dir = home / "plugins"
+ members = []
+ for name, pin, shared in (("plug-a", "1.0.0", shared1), ("plug-b", "2.0.0", shared2)):
+ plug = plugins_dir / name
+ plug.mkdir(parents=True)
+ (plug / "plugin.yaml").write_text(f"name: {name}\n", encoding="utf-8")
+ (plug / "pyproject.toml").write_text(
+ "[project]\n"
+ f'name = "{name}"\nversion = "0.1.0"\n'
+ 'requires-python = ">=3.11"\n'
+ f'dependencies = ["sharedlib=={pin}"]\n'
+ "\n[tool.uv.sources]\n"
+ f'sharedlib = {{ path = "{shared.as_posix()}" }}\n',
+ encoding="utf-8",
+ )
+ members.append(plug)
+ return members[0], members[1], shared1, shared2
+
+
+def admission_env(tmp_path, monkeypatch):
+ """Fake core repo + temp HERMES_HOME so the REAL pm.ensure.sync_venv
+ transaction (lock, receipts, config publication) runs entirely under
+ tmp — the production path, temp homes."""
+ core = tmp_path / "core"
+ core.mkdir()
+ (core / "pyproject.toml").write_text(
+ "[project]\n"
+ 'name = "fake-core"\nversion = "0.1.0"\n'
+ 'requires-python = ">=3.11"\ndependencies = []\n',
+ encoding="utf-8",
+ )
+ # the venv package's stamp digest + lock seed read core/uv.lock —
+ # produce a real one (no deps: uv lock resolves offline)
+ subprocess.run(
+ [shutil.which("uv"), "lock"], cwd=core, check=True,
+ capture_output=True, text=True, timeout=120,
+ )
+ home = tmp_path / "home"
+ _write_enabled(home, []) # nothing enabled yet — the candidate must move it
+
+ import importlib
+
+ ensure = importlib.import_module("pm.ensure")
+ import pm.paths
+
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(pm.paths, "repo_root", lambda: core)
+ monkeypatch.setattr(ws.paths, "repo_root", lambda: core)
+ monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: True)
+ monkeypatch.setattr(ensure, "_facts", lambda: {})
+ # pm's store uv realization is a package-manager concern; the store
+ # is empty under tmp, so pin the resolution to the PATH uv (same
+ # precedence _uv_binary applies on dev machines).
+ monkeypatch.setattr(ensure, "uv", lambda *a, **k: (shutil.which("uv"), os.environ.copy()))
+ return tmp_path, home
+
+
+def _latest_receipt(home: Path) -> dict:
+ receipts = sorted((home / "logs" / "update_receipts").glob("*.json"))
+ assert receipts, "no pm receipt written"
+ return json.loads(receipts[-1].read_text(encoding="utf-8-sig"))
+
+
[email protected](not _uv_available(), reason="uv not on PATH")
+def test_conflicting_candidate_refused_unenabled_and_unimported(admission_env):
+ """Public admission of an unsatisfiable union: AdmissionRefused with
+ plugin identity + resolver reason; the candidate is NOT published to
+ config (so the plugin loader never imports it); plugin trees and
+ configs survive; the receipt records the failure."""
+ from hermes_cli import plugins_admission as admission
+
+ tmp_path, home = admission_env
+ plug_a, plug_b, *_ = _local_conflict_members(home)
+ config_before = (home / "config.yaml").read_bytes()
+ tree_before = {p: sorted(str(f) for f in p.rglob("*")) for p in (plug_a, plug_b)}
+
+ with pytest.raises(admission.AdmissionRefused) as excinfo:
+ admission.admit_plugin_set_change(
+ {"plug-a", "plug-b"}, set(), active_plugins_dir=home / "plugins"
+ )
+ message = str(excinfo.value)
+ assert "plug-b" in message or "plug-a" in message, (
+ f"refusal must carry the plugin identity, got: {message}"
+ )
+ assert "sharedlib" in message.lower() or "conflict" in message.lower(), (
+ f"refusal must carry the resolver's reason, got: {message}"
+ )
+
+ # unenabled → unimported: the candidate never reached the enabled list
+ with (home / "config.yaml").open(encoding="utf-8-sig") as f:
+ cfg = yaml.safe_load(f)
+ assert cfg["plugins"]["enabled"] == [], (
+ "a refused candidate must stay unenabled — config published a set that never resolved"
+ )
+ assert (home / "config.yaml").read_bytes() == config_before
+
+ # no plugin tree was deleted or mutated by the failed resolution
+ for plug, listing in tree_before.items():
+ assert plug.is_dir(), f"failed resolution deleted plugin tree {plug}"
+ assert sorted(str(f) for f in plug.rglob("*")) == listing
+
+ # the machine-readable receipt records the failed sync
+ receipt = _latest_receipt(home)
+ assert receipt.get("outcome") == "failed"
+ flattened = json.dumps(receipt)
+ assert "plug-b" in flattened or "sharedlib" in flattened, (
+ "receipt must carry the conflict identity/reason"
+ )
+
+
[email protected](not _uv_available(), reason="uv not on PATH")
+def test_retry_after_conflict_enables_resolvable_candidate(admission_env):
+ """The retry path: re-admitting ONLY the resolvable candidate through
+ the same public admission commits config + environment together; the
+ conflicting plugin stays unenabled (never imported)."""
+ from hermes_cli import plugins_admission as admission
+
+ tmp_path, home = admission_env
+ plug_a, plug_b, *_ = _local_conflict_members(home)
+
+ with pytest.raises(admission.AdmissionRefused):
+ admission.admit_plugin_set_change(
+ {"plug-a", "plug-b"}, set(), active_plugins_dir=home / "plugins"
+ )
+
+ # retry: drop the conflicting candidate, keep the good one
+ admission.admit_plugin_set_change(
+ {"plug-a"}, set(), active_plugins_dir=home / "plugins"
+ )
+
+ with (home / "config.yaml").open(encoding="utf-8-sig") as f:
+ cfg = yaml.safe_load(f)
+ assert cfg["plugins"]["enabled"] == ["plug-a"]
+ assert "plug-b" not in cfg["plugins"]["enabled"], (
+ "the conflicting candidate must remain unenabled after the retry"
+ )
+
+
+# ---------------------------------------------------------------------------
+# 4. Active context home propagates to wrapper subprocess launches
+# ---------------------------------------------------------------------------
+
[email protected](sys.platform != "win32", reason="detached respawn spec is Windows")
+def test_active_context_home_exported_to_wrapper_subprocess(monkeypatch, tmp_path):
+ """Hermes subprocess launchers must pass HERMES_HOME explicitly (the
+ context-local override never crosses a process boundary on its own).
+ The detached respawn spec exports the ACTIVE context home, and a
+ child launched with that overlay observes it."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from hermes_cli.gateway_windows import windowless_gateway_restart_spec
+
+ active = tmp_path / "profiles" / "worker"
+ active.mkdir(parents=True)
+ token = set_hermes_home_override(active)
+ try:
+ argv, _cwd, overlay = windowless_gateway_restart_spec([sys.executable, "-c", "pass"])
+ assert overlay.get("HERMES_HOME") == str(active), (
+ "the respawn overlay must export the ACTIVE context home as HERMES_HOME"
+ )
+ finally:
+ reset_hermes_home_override(token)
+
+ # and a real subprocess launched with that overlay sees it
+ child_env = {**os.environ, **overlay}
+ out = subprocess.run(
+ [sys.executable, "-c",
+ "import os; print(os.environ['HERMES_HOME'], end='')"],
+ env=child_env, capture_output=True, text=True, timeout=60,
+ )
+ assert out.returncode == 0 and out.stdout == str(active)
diff --git a/website/docs/developer-guide/memory-provider-plugin.md b/website/docs/developer-guide/memory-provider-plugin.md
index bda90a9decd..75ceb2eb6ab 100644
--- a/website/docs/developer-guide/memory-provider-plugin.md
+++ b/website/docs/developer-guide/memory-provider-plugin.md
@@ -412,3 +412,13 @@ plugins/memory/my-provider/
## Single Provider Rule
Only **one** external memory provider can be active at a time. If a user tries to register a second, the MemoryManager rejects it with a warning. This prevents tool schema bloat and conflicting backends.
+
+## `HERMES_HOME` survival contract (what wrappers can rely on)
+
+For wrapper-style providers that keep their runtime in a sidecar venv outside Hermes-managed Python (no dependency surface — no `pyproject.toml`, `pip_dependencies`, or `python_dependencies` — at the scanned plugin root; a `pyproject.toml` belonging solely to an external or nested sidecar is not scanned):
+
+- **Location.** `$HERMES_HOME/plugins/<name>/` is the profile-scoped plugin location, and `HERMES_HOME` follows the active context override, then `$HERMES_HOME`, then the platform default. Propagate `HERMES_HOME` when launching the wrapper or sidecar so profile isolation holds; `MemoryManager.initialize_all` injects the active `hermes_home` into every provider.
+- **Survival.** Ordinary Hermes updates — including managed-venv rebuild/replacement by pm — do not delete or rewrite `$HERMES_HOME/plugins/**`. An installed wrapper directory and its marker file (e.g. `mnemosyne-wrapper.json`) survive. Explicit deletion flows (`hermes uninstall`, `hermes plugins remove`, profile deletion, user deletion) are excluded from this guarantee.
+- **Sidecar isolation.** A plugin root with no dependency surface never joins the pm workspace dependency union; a resync or venv rebuild neither provisions deps for it nor touches its tree.
+- **Conflicts.** For native shared-venv plugins, an unsatisfiable dependency union fails loudly: the candidate plugin stays unenabled and unimported (the admission authority refuses before publishing config, reporting the plugin identity plus the resolver's reason, with a re-enable/retry path and a machine-readable pm receipt). Nothing disables plugins automatically today — there is no automatic bisect. A future automatic-disable decision, if one is added, must prefer the active memory provider over ordinary plugins.
+