Skip to content

The agent that grows with you

fix(memory): admit provider dependencies before setup

ethernet534f3226977f
diff --git a/hermes_cli/memory_setup.py b/hermes_cli/memory_setup.py
index 299450d7e09..20e3509748e 100644
--- a/hermes_cli/memory_setup.py
+++ b/hermes_cli/memory_setup.py
@@ -12,19 +12,6 @@ from hermes_cli.secret_prompt import masked_secret_prompt
_CANCELLED = -1
-# pip name → import name mapping for packages where they differ
-_IMPORT_NAMES = {
- "honcho-ai": "honcho",
- "mem0ai": "mem0",
- "hindsight-client": "hindsight_client",
- "hindsight-all": "hindsight"}
-
-
-def _provider_extras(provider_name: str, manifest: dict, plugin_dir=None) -> list[str]:
- """The declared core extra; manifest requirements join the staged union."""
- declared = manifest.get("extra")
- return [declared] if isinstance(declared, str) and declared else []
-
def _curses_select(
title: str, items: list[tuple[str, str]], default: int = 0, *, cancel_returns: int | None = None
@@ -65,49 +52,40 @@ def _prompt(label: str, default: str | None = None, secret: bool = False) -> str
def _install_dependencies(provider_name: str, *, force: bool = False) -> None:
- """Install pip dependencies declared in ``plugin.yaml``.
+ """Prepare provider dependencies without narrowing the active plugin union.
- With ``force`` every declared dependency goes to the installer even if it imports (the resolver
- no-ops when nothing drifted) — how ``hermes update`` heals a provider after a venv rebuild.
-
- When ``force`` is true, every declared dependency is handed to the installer even if its import
- currently succeeds — the resolver then reinstalls anything missing or version-drifted and no-ops on
- satisfied ranges. This is how ``hermes update`` heals the active memory provider after a venv
- rebuild/sync removed or downgraded its bridge packages (#53272, #70636).
+ A new provider is not selected in config yet. Include its directory with
+ every active member, and propagate failure before setup saves it.
"""
import subprocess
+
+ import pm
+ from hermes_cli.plugins_admission import candidate_member_dirs
+ from hermes_cli.plugins_cmd import PluginOperationError, _read_manifest_for_install
+ from pm.package import InstallError
+ from pm.workspace import _is_member_candidate
from plugins.memory import find_provider_dir
plugin_dir = find_provider_dir(provider_name)
if not plugin_dir:
return
- yaml_path = plugin_dir / "plugin.yaml"
- if not yaml_path.exists():
- return
try:
- import yaml
- with open(yaml_path, encoding="utf-8-sig") as f:
- meta = yaml.safe_load(f) or {}
- except Exception:
- return
-
- extras = _provider_extras(provider_name, meta, plugin_dir=plugin_dir)
- if not extras:
- return
-
- import pm
+ meta = _read_manifest_for_install(plugin_dir)
+ member = _is_member_candidate(plugin_dir)
+ except (PluginOperationError, OSError, ValueError) as exc:
+ raise InstallError(provider_name, str(exc)) from exc
+ extra = meta.get("extra")
+ extras = [extra] if isinstance(extra, str) and extra else []
missing = [e for e in extras if force or not pm.available(e)]
- if not missing:
+ if not missing and not member:
return
- print(f"\n Installing dependencies: {', '.join(missing)}")
- try:
- pm.sync_venv(missing, explicit=True)
- print(f" ✓ Installed {', '.join(missing)}")
- except Exception as e:
- print(f" ⚠ Install failed: {e}")
- print(" Run manually: hermes pm install")
+ print(f"\n Preparing dependencies for {provider_name}")
+ # Without a proposed home, selection retains every configured member.
+ inputs = {"plugin_dirs": lambda: candidate_member_dirs((), extra_dirs=[plugin_dir])} if member else {}
+ pm.sync_venv(missing, explicit=True, **inputs)
+ print(f" ✓ Dependencies prepared for {provider_name}")
# Also show external (non-pip) dependencies that are missing.
for dep in meta.get("external_dependencies", []):
@@ -432,10 +410,17 @@ def cmd_status(args) -> None:
def memory_command(args) -> None:
"""Route memory subcommands."""
if getattr(args, "memory_command", None) == "setup":
+ from pm.package import InstallError
+
provider = getattr(args, "provider", None)
- if provider:
- cmd_setup_provider(provider)
- else:
- cmd_setup(args)
+ try:
+ if provider:
+ cmd_setup_provider(provider)
+ else:
+ cmd_setup(args)
+ except InstallError as exc:
+ print(f"Memory setup failed: {exc}", file=sys.stderr)
+ print("Correct the dependency error and retry setup.", file=sys.stderr)
+ raise SystemExit(1) from exc
else:
cmd_status(args)
diff --git a/tests/hermes_cli/test_memory_dependency_admission.py b/tests/hermes_cli/test_memory_dependency_admission.py
new file mode 100644
index 00000000000..5398a5e4298
--- /dev/null
+++ b/tests/hermes_cli/test_memory_dependency_admission.py
@@ -0,0 +1,130 @@
+"""Memory setup admits a complete candidate before saving its selection."""
+import importlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+from types import SimpleNamespace
+
+import pytest
+import yaml
+
+import pm
+from hermes_cli import memory_setup
+from hermes_cli.runtime_paths import selected_venv
+from pm import paths
+from tests.pm.test_workspace_build_inputs import _wheel
+
+
[email protected]('picker', [False, True])
+def test_setup_requires_dependencies_and_keeps_the_existing_union(tmp_path, monkeypatch, picker):
+ uv = shutil.which('uv')
+ assert uv, 'uv is required for the real admission contract'
+ core, home, wheels = (tmp_path / name for name in ('core', 'home', 'wheels'))
+ for directory in (core, home, wheels):
+ directory.mkdir()
+ for name in ('existing_dep', 'provider_dep', 'modern_dep', 'other_dep'):
+ _wheel(wheels, name, '1.0')
+ (core / 'pyproject.toml').write_text(
+ '[project]\nname="core"\nversion="1"\nrequires-python=">=3.14"\n'
+ '[tool.uv]\npackage=false\nno-index=true\n'
+ f'find-links=[{json.dumps(wheels.as_posix())}]\n', encoding='utf-8')
+ env = {**os.environ, 'UV_OFFLINE': '1', 'UV_PYTHON_DOWNLOADS': 'never',
+ 'UV_CACHE_DIR': str(tmp_path / 'cache')}
+ subprocess.run([uv, 'lock', '--python', sys.executable], cwd=core, env=env,
+ capture_output=True, check=True, timeout=60)
+ plugins = home / 'plugins'
+ incumbent, candidate = plugins / 'incumbent', plugins / 'candidate'
+ for plugin in (incumbent, candidate):
+ plugin.mkdir(parents=True)
+ (plugin / '__init__.py').write_text('# MemoryProvider fixture\n', encoding='utf-8')
+ (incumbent / 'plugin.yaml').write_text(
+ 'name: incumbent\npython_dependencies: ["existing_dep==1.0"]\n', encoding='utf-8')
+ candidate_manifest = candidate / 'plugin.yaml'
+ candidate_manifest.write_text(
+ 'name: candidate\npip_dependencies: ["provider_dep==1.0", "provider_dep==2.0"]\n',
+ encoding='utf-8')
+ config = home / 'config.yaml'
+ config.write_text(yaml.safe_dump({'plugins': {'enabled': ['incumbent']},
+ 'memory': {'provider': 'incumbent', 'setting': 'keep'}}), encoding='utf-8')
+ other_home = home / 'profiles' / 'other'
+ other_plugin = other_home / 'plugins' / 'other-plugin'
+ other_plugin.mkdir(parents=True)
+ (other_plugin / 'plugin.yaml').write_text(
+ 'name: other-plugin\npython_dependencies: ["other_dep==1.0"]\n', encoding='utf-8')
+ other_config = other_home / 'config.yaml'
+ other_config.write_text('plugins:\n enabled: [other-plugin]\n', encoding='utf-8')
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ monkeypatch.setenv('HERMES_RUNTIME_DIR', str(tmp_path / 'tools'))
+ monkeypatch.setattr(paths, 'repo_root', lambda: core)
+ ensure = importlib.import_module('pm.ensure')
+ monkeypatch.setattr(ensure, 'lazy_installs_allowed', lambda: True)
+ from pm.packages import uv_env
+
+ monkeypatch.setattr(ensure, 'uv', lambda **kwargs: (
+ uv, {**uv_env(kwargs.get('base_env')), 'UV_PYTHON': sys.executable,
+ 'UV_OFFLINE': '1', 'UV_CACHE_DIR': str(tmp_path / 'cache')},
+ ))
+ pm.sync_venv(explicit=True)
+ original_environment = selected_venv(core)
+ before = {file: file.read_bytes() for file in (config, other_config, paths.runtime_facts_path())}
+ post_calls = []
+
+ class Provider:
+ def post_setup(self, actual_home, proposal):
+ assert Path(actual_home) == home
+ post_calls.append(proposal)
+
+ monkeypatch.setattr(memory_setup, '_get_available_providers', lambda: [('candidate', 'local', Provider())])
+ monkeypatch.setattr(memory_setup, '_curses_select', lambda *args, **kwargs: 0)
+
+ def setup():
+ from hermes_cli.main_agent_cmds import cmd_memory
+
+ cmd_memory(SimpleNamespace(memory_command='setup', provider=None if picker else 'candidate'))
+
+ with pytest.raises(SystemExit) as refused:
+ setup()
+ assert refused.value.code == 1
+ assert not post_calls
+ assert {file: file.read_bytes() for file in before} == before
+ assert selected_venv(core) == original_environment
+
+ for malformed in ('name: [broken', 'name: candidate\npython_dependencies: 9\n'):
+ candidate_manifest.write_text(malformed, encoding='utf-8')
+ with pytest.raises(SystemExit) as refused:
+ setup()
+ assert refused.value.code == 1
+ assert {file: file.read_bytes() for file in before} == before
+ assert not post_calls
+
+ candidate_manifest.write_text('name: candidate\npip_dependencies: ["provider_dep==1.0"]\n', encoding='utf-8')
+ # Generic setup saves the selection only after the real sync completes.
+ monkeypatch.setattr(memory_setup, '_get_available_providers', lambda: [('candidate', 'local', SimpleNamespace())])
+ setup()
+ assert yaml.safe_load(config.read_text(encoding='utf-8'))['memory']['provider'] == 'candidate'
+ selected = selected_venv(core)
+ python = selected / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')
+ result = subprocess.run([str(python), '-I', '-c', 'import existing_dep, provider_dep, other_dep; print("both")'],
+ env=env, cwd=tmp_path, capture_output=True, text=True, check=True, timeout=30)
+ assert result.stdout.strip() == 'both'
+ assert not (candidate / 'pyproject.toml').exists()
+ assert other_config.read_bytes() == before[other_config]
+
+ modern = plugins / 'modern'
+ modern.mkdir()
+ (modern / '__init__.py').write_text('# MemoryProvider fixture\n', encoding='utf-8')
+ (modern / 'plugin.yaml').write_text('name: modern\n', encoding='utf-8')
+ (modern / 'pyproject.toml').write_text(
+ '[project]\nname="modern-provider"\nversion="1"\nrequires-python=">=3.14"\n'
+ 'dependencies=["modern_dep==1.0"]\n[tool.uv]\npackage=false\n', encoding='utf-8')
+ monkeypatch.setattr(memory_setup, '_get_available_providers', lambda: [('modern', 'local', SimpleNamespace())])
+ memory_setup.cmd_setup_provider('modern')
+ selected = selected_venv(core)
+ python = selected / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')
+ result = subprocess.run([str(python), '-I', '-c', 'import existing_dep, provider_dep, modern_dep, other_dep; print("all")'],
+ env=env, cwd=tmp_path, capture_output=True, text=True, check=True, timeout=30)
+ assert result.stdout.strip() == 'all'
+ assert other_config.read_bytes() == before[other_config]