Skip to content

The agent that grows with you

feat(lazy_deps): install_specs takes constraints and dry_run

teknium1e3507ef2ce93
diff --git a/tests/hermes_cli/test_plugin_python_deps.py b/tests/hermes_cli/test_plugin_python_deps.py
new file mode 100644
index 00000000000..1e2c34f78e8
--- /dev/null
+++ b/tests/hermes_cli/test_plugin_python_deps.py
@@ -0,0 +1,84 @@
+"""Invariants of the plugin Python-dependency contract (hermes_cli.plugin_python_deps):
+
+* a candidate whose declared deps conflict is REFUSED before install and nothing else changes;
+* after an update, a non-memory plugin that no longer resolves is disabled loudly while memory
+ providers survive.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import plugin_python_deps as deps
+
+
+def _plugin(root: Path, name: str, spec_lines: str, *, memory: bool = False, external: bool = False) -> Path:
+ d = root / "plugins" / name
+ d.mkdir(parents=True)
+ manifest = f"name: {name}\nversion: 1.0.0\n" + ("kind: exclusive\n" if memory else "")
+ if external:
+ manifest += "python_runtime: external\n"
+ (d / "plugin.yaml").write_text(manifest, encoding="utf-8")
+ (d / "__init__.py").write_text("def register(ctx):\n pass\n", encoding="utf-8")
+ (d / "pyproject.toml").write_text(
+ f'[project]\nname = "{name}"\nversion = "1.0"\ndependencies = [{spec_lines}]\n', encoding="utf-8")
+ return d
+
+
+def _home(tmp_path: Path, enabled: list[str]) -> Path:
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / "config.yaml").write_text(
+ "plugins:\n enabled: [" + ", ".join(enabled) + "]\n disabled: []\n", encoding="utf-8")
+ return home
+
+
+def _fake_resolver(conflicting: set[str]):
+ """Stand-in for uv: fails with a conflict whenever the spec set contains a poisoned spec."""
+ calls: list[list[str]] = []
+
+ def resolve(specs, constraints, *, dry_run, timeout=900):
+ calls.append(list(specs))
+ if conflicting & set(specs):
+ raise deps.DependencyConflict("No solution found when resolving dependencies")
+
+ return resolve, calls
+
+
+def test_conflicting_candidate_is_refused_and_enabled_plugins_are_untouched(tmp_path, monkeypatch):
+ home = _home(tmp_path, ["good"])
+ _plugin(home, "good", '"tabulate>=0.9"')
+ candidate = _plugin(tmp_path / "staging", "bad", '"tabulate<0.9"')
+ resolve, calls = _fake_resolver({"tabulate<0.9"})
+ monkeypatch.setattr(deps, "resolve", resolve)
+ monkeypatch.setattr(deps, "core_constraints", lambda root: ["httpx==0.28.1"])
+ monkeypatch.setattr(deps, "all_homes", lambda: [home])
+
+ with pytest.raises(deps.DependencyConflict):
+ deps.check_candidate(deps.read_declaration(candidate), home=home, project_root=tmp_path)
+
+ # The dry run saw the union (candidate + enabled peer) and never ran a real install.
+ assert calls == [["tabulate<0.9", "tabulate>=0.9"]]
+ assert (home / "plugins" / "good").is_dir()
+ assert "good" in (home / "config.yaml").read_text()
+
+
+def test_reapply_disables_non_memory_plugin_loudly_and_keeps_memory_provider(tmp_path, monkeypatch):
+ home = _home(tmp_path, ["memory", "weather", "sidecar"])
+ _plugin(home, "memory", '"mnemosyne-memory>=3"', memory=True)
+ _plugin(home, "weather", '"httpx<0.20"')
+ _plugin(home, "sidecar", '"torch==99"', external=True)
+ resolve, calls = _fake_resolver({"httpx<0.20"})
+ monkeypatch.setattr(deps, "resolve", resolve)
+ monkeypatch.setattr(deps, "core_constraints", lambda root: ["httpx==0.28.1"])
+ monkeypatch.setattr(deps, "all_homes", lambda: [home])
+ disabled: list[tuple[Path, str]] = []
+
+ report = deps.reapply_all(project_root=tmp_path, disable=lambda h, n: disabled.append((h, n)))
+
+ assert disabled == [(home, "weather")]
+ assert report.dropped and report.dropped[0][0] == "weather"
+ assert report.installed == ["mnemosyne-memory>=3"]
+ # External-runtime plugin never joined the union; memory provider was the survivor.
+ assert all("torch==99" not in c for c in calls)
diff --git a/tools/lazy_deps.py b/tools/lazy_deps.py
index bf057619bc0..f1b847a66c2 100644
--- a/tools/lazy_deps.py
+++ b/tools/lazy_deps.py
@@ -490,28 +490,49 @@ def _uv_binary() -> Optional[str]:
return shutil.which("uv")
-def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _InstallResult:
+def _write_constraints_file(lines: tuple[str, ...]) -> Path:
+ import tempfile
+ fd, path = tempfile.mkstemp(prefix="hermes-plugin-constraints-", suffix=".txt")
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ f.write("\n".join(lines) + "\n")
+ return Path(path)
+
+
+def _after_successful_install(specs: tuple[str, ...], target: Optional[Path], dry_run: bool) -> None:
+ """Post-install bookkeeping; a dry run installed nothing, so there is nothing to activate/warm."""
+ if dry_run:
+ return
+ if target is not None:
+ _activate_target_on_syspath(target)
+ _warm_installed_bytecode(specs, target)
+
+
+def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300, constraint_lines: tuple[str, ...] = (),
+ dry_run: bool = False) -> _InstallResult:
"""Install ``specs`` via the uv -> pip -> ensurepip ladder, venv-scoped or into the durable
``--target`` (constrained to core versions) when :data:`_LAZY_TARGET_ENV` is set. Independent of
- ``hermes_cli.tools_config._pip_install`` (no CLI dependency)."""
+ ``hermes_cli.tools_config._pip_install`` (no CLI dependency).
+
+ *constraint_lines* pins the resolver (plugin installs pass Hermes' own declared ranges so a plugin
+ can never move a core package out of range); *dry_run* resolves without installing."""
if not specs:
return _InstallResult(True, "", "")
target = _lazy_install_target()
constraints: Optional[Path] = None
- extra_args: list[str] = []
+ extra_args: list[str] = ["--dry-run"] if dry_run else []
if target is not None:
if err := _ensure_target_ready(target):
return _InstallResult(False, "", err)
constraints = _core_constraints_file()
extra_args += ["--target", str(target)]
- if constraints is not None:
- extra_args += ["--constraint", str(constraints)]
+ elif constraint_lines:
+ constraints = _write_constraints_file(constraint_lines)
+ if constraints is not None:
+ extra_args += ["--constraint", str(constraints)]
def _finish(r: subprocess.CompletedProcess) -> _InstallResult:
if r.returncode == 0:
- if target is not None:
- _activate_target_on_syspath(target)
- _warm_installed_bytecode(specs, target)
+ _after_successful_install(specs, target, dry_run)
return _InstallResult(r.returncode == 0, r.stdout or "", r.stderr or "")
try:
@@ -650,10 +671,12 @@ class InstallSpecsResult:
stderr: str = ""
-def install_specs(specs: list[str] | tuple[str, ...], *, timeout: int = 300) -> InstallSpecsResult:
+def install_specs(specs: list[str] | tuple[str, ...], *, timeout: int = 300,
+ constraints: list[str] | tuple[str, ...] = (), dry_run: bool = False) -> InstallSpecsResult:
"""Install data-driven pip specs (plugin manifest ``pip_dependencies``) with the same routing and
gating as :func:`ensure`, but unknown packages are allowed — the caller owns manifest trust, this
- owns spec hygiene. Never raises; inspect the :class:`InstallSpecsResult`."""
+ owns spec hygiene. *constraints* are requirement lines the resolver must honour; *dry_run* only
+ resolves. Never raises; inspect the :class:`InstallSpecsResult`."""
cleaned = tuple(str(s).strip() for s in specs if str(s).strip())
if not cleaned:
return InstallSpecsResult(ok=True, command="")
@@ -668,9 +691,9 @@ def install_specs(specs: list[str] | tuple[str, ...], *, timeout: int = 300) ->
) if sealed else "runtime installs disabled (security.allow_lazy_installs=false)"
return InstallSpecsResult(ok=False, blocked=True, reason=reason)
display = "uv pip install " + (f"--target {target} " if target is not None else "") + " ".join(cleaned)
- logger.info("Installing pip specs %s (target=%s)", " ".join(cleaned), target or "venv")
+ logger.info("%s pip specs %s (target=%s)", "Resolving" if dry_run else "Installing", " ".join(cleaned), target or "venv")
try:
- result = _venv_pip_install(cleaned, timeout=timeout)
+ result = _venv_pip_install(cleaned, timeout=timeout, constraint_lines=tuple(constraints), dry_run=dry_run)
except Exception as exc:
logger.warning("install_specs failed unexpectedly: %s", exc)
return InstallSpecsResult(ok=False, command=display, stderr=f"install failed: {exc}")