Skip to content

The agent that grows with you

refactor(pm): one plugin-input request for sync_venv and venv_is_current

ethernet9b4ed5f5ec24
diff --git a/hermes_cli/memory_setup.py b/hermes_cli/memory_setup.py
index 6405d7e3874..f4859289e8b 100644
--- a/hermes_cli/memory_setup.py
+++ b/hermes_cli/memory_setup.py
@@ -55,6 +55,7 @@ def memory_provider_dependency_inputs(provider_name: str) -> tuple[dict, dict]:
"""Read one candidate declaration for preparation and passive readiness."""
from hermes_cli.plugins_cmd import PluginOperationError, _read_manifest_for_install
from pm.package import InstallError
+ from pm.plugin_inputs import Candidates
from pm.workspace import _is_member_candidate
from plugins.memory import find_provider_dir
@@ -73,7 +74,7 @@ def memory_provider_dependency_inputs(provider_name: str) -> tuple[dict, dict]:
return meta, {}
# Without a proposed home, selection retains every configured member.
- inputs = {"extra_plugin_dirs": [plugin_dir]} if member else {}
+ inputs = {"plugins": Candidates([plugin_dir])} if member else {}
return meta, {"extras": extras, **inputs}
diff --git a/hermes_cli/plugins_admission.py b/hermes_cli/plugins_admission.py
index 9df8dc3729c..0b2d42fbba5 100644
--- a/hermes_cli/plugins_admission.py
+++ b/hermes_cli/plugins_admission.py
@@ -63,14 +63,15 @@ def admit_plugin_set_change(
"""
from hermes_constants import get_hermes_home
from pm.client import sync_venv
+ from pm.plugin_inputs import Selection
home = Path(active_plugins_dir).parent if active_plugins_dir is not None else get_hermes_home()
try:
- sync_venv(explicit=True, selection={
+ sync_venv(explicit=True, plugins=Selection({
"home": str(home.resolve()), "enabled": sorted(candidate_enabled),
"disabled": sorted(candidate_disabled), "extra_dirs": [str(Path(d).resolve()) for d in extra_dirs],
**({"expected_config": expected_config} if expected_config is not None else {}),
- })
+ }))
except Exception as exc:
from pm.workspace import ResolutionConflict
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index f866fdfd6b6..8066588e87c 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -614,8 +614,9 @@ def cmd_validate(path: str, as_json: bool = False, install_deps: bool = False) -
from hermes_cli.plugins_cmd import _console
if install_deps:
import pm
+ from pm.plugin_inputs import Candidates
try:
- pm.sync_venv(extra_plugin_dirs=[Path(path)])
+ pm.sync_venv(plugins=Candidates([Path(path)]))
except Exception as exc: # validation still runs; the probe reports what is missing
print(f"dependency preparation failed: {exc}", file=sys.stderr)
report = validate_plugin_dir(Path(path))
diff --git a/hermes_cli/plugins_transaction.py b/hermes_cli/plugins_transaction.py
index 9dfdef3ae04..f95936e7c8d 100644
--- a/hermes_cli/plugins_transaction.py
+++ b/hermes_cli/plugins_transaction.py
@@ -15,6 +15,7 @@ def recover_plugin_publication(project: Path, row: dict, journal: Path) -> None:
def publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata: dict,
*, target_digest: str | None = None, require_consent: bool = False) -> None:
from pm.client import sync_venv
+ from pm.plugin_inputs import StagedUpdate
from pm.store import tree_digest
if require_consent:
@@ -28,11 +29,11 @@ def publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata:
raise plugins_cmd.PluginOperationError(
f"Reinstall declined: {reason}. The installed plugin and active environment are unchanged.")
- sync_venv(explicit=True, staged_plugin={
+ sync_venv(explicit=True, plugins=StagedUpdate({
"staged": str(staged.resolve()), "target": str(target.absolute()),
"old_metadata": old_metadata, "new_metadata": new_metadata,
"target_digest": target_digest if target_digest is not None else (tree_digest(target) if target.exists() else None),
- })
+ }))
def _refresh_declared_dependencies(target: Path, staged: Path, manifest: dict, *, interactive: bool) -> None:
diff --git a/pm/client.py b/pm/client.py
index 54af0488e0f..fee428c82e2 100644
--- a/pm/client.py
+++ b/pm/client.py
@@ -9,21 +9,13 @@ import sys
import threading
import uuid
-from pm import paths
+from pm import paths, plugin_inputs
from pm.package import InstallError, Runner, StatePackage
+from pm.plugin_inputs import Candidates, Members, PluginInput, Selection
from pm.runtime import is_runtime, runtime_command, runtime_environment
from pm.worker_operations import OPERATIONS
-def _members(value):
- if value is None:
- return None
- if isinstance(value, Mapping):
- return {"sources": [[str(Path(key).absolute()), str(Path(source).absolute())]
- for key, source in value.items()]}
- return {"paths": [str(Path(path).absolute()) for path in value]}
-
-
def _missing_or_refuse(name):
from pm.install import _refuse_lazy, is_installed, lazy_installs_allowed
from pm.registry import walk
@@ -190,7 +182,7 @@ def ensure(name, *, base_env=None, explicit=False, progress=None, pause_event=No
return Runner(name, env_for(name, base_env=base_env))
-def sync_venv(extras=None, *, explicit=False, plugin_dirs=None, extra_plugin_dirs=(), selection=None, staged_plugin=None, repair=False,
+def sync_venv(extras=None, *, explicit=False, plugins: PluginInput | None = None, repair=False,
project_root: Path | None = None) -> None:
from pm.environments import running_from_selected_environment
@@ -206,17 +198,16 @@ def sync_venv(extras=None, *, explicit=False, plugin_dirs=None, extra_plugin_dir
f"{list(extras)}: this process is not running from the install's dependency environment "
f"({sys.prefix}); only an explicit install may change what later processes boot into",
)
- if selection is not None and "expected_config" not in selection:
+ if isinstance(plugins, Selection) and "expected_config" not in plugins.data:
from pm.filesystem import file_digest
- selection = {**selection, "expected_config": file_digest(Path(selection["home"]) / "config.yaml") or "missing"}
+ plugins = Selection({**plugins.data,
+ "expected_config": file_digest(Path(plugins.data["home"]) / "config.yaml") or "missing"})
foreign = 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, plugin_dirs=plugin_dirs,
- selection=selection, staged_plugin=staged_plugin, extra_plugin_dirs=extra_plugin_dirs, repair=repair)
+ return direct(extras, explicit=explicit, plugins=plugins, repair=repair)
_request("sync_venv", {"extras": extras, "explicit": explicit, "repair": repair,
- "plugin_dirs": _members(plugin_dirs), "selection": selection, "staged_plugin": staged_plugin,
- "extra_plugin_dirs": [str(Path(p).absolute()) for p in extra_plugin_dirs]}, project_root=project_root)
+ "plugins": plugin_inputs.encode(plugins)}, project_root=project_root)
def stage_only(name, target, *, progress=None) -> Path:
@@ -314,16 +305,14 @@ def ensure_python_tool(
}))
-def venv_is_current(*, extras: list[str] | None = None, plugin_dirs=None, extra_plugin_dirs=(),
+def venv_is_current(*, extras: list[str] | None = None, plugins: Members | Candidates | None = None,
project_root: Path | None = None) -> bool:
"""Check through a ready PM, never bootstrap dependencies for a probe."""
if is_runtime() and (project_root is None or Path(project_root).resolve() == paths.repo_root().resolve()):
from pm.install import venv_is_current as direct
- return direct(extras=extras, plugin_dirs=plugin_dirs, extra_plugin_dirs=extra_plugin_dirs, project_root=project_root)
- members = plugin_dirs
+ return direct(extras=extras, plugins=plugins, project_root=project_root)
try:
- return bool(_request("venv_is_current", {"extras": extras, "plugin_dirs": _members(members),
- "extra_plugin_dirs": [str(Path(p).absolute()) for p in extra_plugin_dirs]},
+ return bool(_request("venv_is_current", {"extras": extras, "plugins": plugin_inputs.encode(plugins)},
project_root=project_root))
except InstallError as exc:
if exc.package == "pm-runtime":
diff --git a/pm/install.py b/pm/install.py
index a797e43a16c..8f51e224a10 100644
--- a/pm/install.py
+++ b/pm/install.py
@@ -16,6 +16,7 @@ from pm import paths
from pm.downloader import DownloadPaused, ProgressFn
from pm.lock import Facts, Lockfile
from pm.package import InstallError, Package, Runner, StatePackage, compose_env
+from pm.plugin_inputs import Candidates, Members, PluginInput, Selection, StagedUpdate
from pm.registry import get_package, walk
from pm.store import Store, current_target, merge_tree, tree_digest
@@ -514,7 +515,20 @@ def _runtime_state_matches(fact: dict, stamp: str, *, project_root: Path | None
return (environment / "pyvenv.cfg").is_file()
-def venv_is_current(*, extras: list[str] | None = None, plugin_dirs=None, extra_plugin_dirs=(),
+def _member_inputs(plugins: PluginInput | None) -> dict:
+ """The ``plugin_dirs`` argument of the venv package; empty means config discovery."""
+ from pm.publication import candidate_members
+
+ if isinstance(plugins, Candidates):
+ return {"plugin_dirs": candidate_members(plugins.dirs)}
+ if isinstance(plugins, Members):
+ return {"plugin_dirs": plugins.dirs}
+ if plugins is None:
+ return {}
+ raise TypeError(f"{type(plugins).__name__} changes plugin state; only a sync may carry it")
+
+
+def venv_is_current(*, extras: list[str] | None = None, plugins: Members | Candidates | None = None,
project_root: Path | None = None) -> bool:
"""Probe the requested union without changing recorded dependency state."""
from pm.environments import runtime_facts_path
@@ -532,23 +546,136 @@ def venv_is_current(*, extras: list[str] | None = None, plugin_dirs=None, extra_
or any(not isinstance(extra, str) for extra in fact["extras"])):
raise ValueError("invalid recorded dependency state")
enabled = sorted(set(fact["extras"]) | set(extras or []))
- from pm.publication import candidate_members
- if extra_plugin_dirs and plugin_dirs is not None:
- raise ValueError("additional candidates require member discovery")
- members = candidate_members(extra_plugin_dirs) if extra_plugin_dirs else plugin_dirs
- inputs = {} if members is None else {"plugin_dirs": members}
- stamp = package.expected_stamp(enabled, **inputs)
+ stamp = package.expected_stamp(enabled, **_member_inputs(plugins))
return _runtime_state_matches(fact, stamp, project_root=root)
-def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plugin_dirs=None, extra_plugin_dirs=(), selection=None, staged_plugin=None, repair: bool = False) -> None:
+def _feature_policy(extras: Optional[list[str]], *, repair: bool) -> tuple[list[str] | None, list[str] | None]:
+ """Refuse extras this platform or a frozen bundle cannot carry; return (shipped, frozen)."""
+ from pm.features import read_features
+
+ if extras:
+ from pm.extras import extra_supported
+ unsupported = [extra for extra in extras
+ if not extra_supported(extra, importable=lambda _: False)]
+ if unsupported:
+ raise InstallError("venv", f"extras {unsupported} are not supported by this Python/platform",
+ "choose a supported provider; no dependency environment was changed")
+ shipped = read_features()
+ frozen = shipped
+ # Without a frozen declaration, explicit source setup needs no policy
+ # read: the config loader initializes/chmods unrelated user state.
+ if frozen is not None and not repair and lazy_installs_allowed():
+ frozen = None
+ if frozen is not None and extras:
+ outside = sorted(set(extras) - set(frozen))
+ if outside:
+ raise _refuse_lazy(
+ "venv",
+ f"extras {outside} are outside this bundle's frozen feature "
+ "set (security.allow_lazy_installs is false)",
+ )
+ return shipped, frozen
+
+
+@contextmanager
+def _venv_install_lock(*, patient: bool):
+ """Hold the dependency lock, or refuse when an impatient caller would queue."""
+ from pm import receipt
+ from hermes_cli.runtime_state import INSTALL_LOCK_TIMEOUT_SECONDS, runtime_lock
+
+ # Holding this lock means rebuilding the whole dependency environment, which takes tens of
+ # seconds on a bundle. Only an install the user asked for may queue for it; an opportunistic
+ # one (a lazy extra at first use, the only non-explicit caller) refuses instead of holding
+ # a sibling profile's backend off its port behind a rebuild it did not request.
+ with runtime_lock(paths.repo_root(), timeout=None if patient else INSTALL_LOCK_TIMEOUT_SECONDS) as held:
+ if not held:
+ error = InstallError(
+ "venv",
+ f"another Hermes process is installing dependencies (waited {INSTALL_LOCK_TIMEOUT_SECONDS:.0f}s)",
+ "retry in a moment, or run `hermes pm install` to install explicitly",
+ )
+ receipt.record_refusal("install-busy", str(error))
+ raise error
+ yield
+
+
+def _publication(plugins: PluginInput | None):
+ """Snapshot a plugin state change under the held lock, or None for member-only inputs."""
+ from pm.publication import PluginSelection, StagedPlugin
+
+ if isinstance(plugins, Selection):
+ return PluginSelection(dict(plugins.data))
+ if isinstance(plugins, StagedUpdate):
+ return StagedPlugin(dict(plugins.data))
+ return None
+
+
+def _publish_inactive(change) -> None:
+ """A disabled plugin's code changes without touching the dependency environment."""
+ from pm import receipt
+ from hermes_cli.runtime_state import finish_publication, recover_publication
+
+ try:
+ change.publish(paths.repo_root())
+ finish_publication(paths.repo_root())
+ except BaseException:
+ recover_publication(paths.repo_root())
+ raise
+ receipt.record_venv_rebuild(False, "inactive plugin")
+
+
+def _target_selection(package, fact: dict, *, extras, inputs: dict, repair: bool, shipped, frozen):
+ """Return (enabled extras, expected stamp, package inputs) this sync must reach."""
+ if repair:
+ if fact and (not isinstance(fact.get("extras"), list)
+ or any(not isinstance(extra, str) for extra in fact["extras"])
+ or not isinstance(fact.get("stamp"), str) or not fact["stamp"]):
+ raise InstallError("venv", "recorded dependency selection is incomplete; refusing to change its graph")
+ enabled = list(fact.get("extras", frozen if frozen is not None else ["all"]))
+ stamp = fact.get("stamp") or package.expected_stamp(enabled, plugin_dirs=[])
+ return enabled, stamp, {"repair": True}
+ # The first writable generation replaces, rather than layers on,
+ # the payload. Retain its extras until a recorded selection owns them.
+ enabled = sorted(set(fact.get("extras", shipped or [])) | set(extras or []))
+ return enabled, package.expected_stamp(enabled, **inputs), inputs
+
+
+def _commit_selection(package, facts: Facts, change, *, enabled: list[str], stamp: str, inputs: dict,
+ current: bool, repair: bool, explicit: bool) -> None:
+ """Build (unless current), publish the plugin change, then record the selection."""
+ from pm import receipt
+ from hermes_cli.runtime_state import finish_publication, recover_publication
+
+ try:
+ result = {} if current else (package.apply(enabled, explicit=explicit, **inputs) or {})
+ if not repair and package.expected_stamp(enabled, **inputs) != stamp:
+ raise ValueError("Dependency inputs changed while preparing publication; retry.")
+ if change is not None:
+ change.publish(paths.repo_root())
+ if not current:
+ if result.get("environment") is not None:
+ from pm.environments import flush_before_selecting
+ flush_before_selecting()
+ facts.record_state("venv", stamp, enabled, **result)
+ if change is not None:
+ finish_publication(paths.repo_root())
+ receipt.record_venv_rebuild(not current, "already in sync" if current else "")
+ except BaseException:
+ recover_publication(paths.repo_root())
+ raise
+
+
+def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False,
+ plugins: PluginInput | None = None, repair: bool = False) -> None:
"""Make the venv match uv.lock + the enabled extras. Extras union into
the installed state (one ledger); no-op when the stamp already matches.
``repair`` restores the recorded dependency graph into a fresh generation,
bypassing both that shortcut and config discovery. It cannot add features.
``explicit`` marks a deliberate install command (`hermes pm install`,
`hermes update`) — those are the remedy the lazy-install policy points
- at, so the policy does not apply to them.
+ at, so the policy does not apply to them. ``plugins`` names the one
+ source of plugin members (see pm.plugin_inputs); None discovers them from config.
Lazy installs OFF = the frozen feature set: when
security.allow_lazy_installs is false AND the bundle's
@@ -563,107 +690,33 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plu
a receipt. Plugin selection data is discovered and published by the worker
under this lock; no executable transaction phases cross the process boundary."""
from pm import receipt
- from pm.features import read_features
token = receipt.begin("sync")
outcome = "failed"
try:
- if repair and (extras is not None or plugin_dirs is not None or selection is not None or staged_plugin is not None or extra_plugin_dirs):
+ 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 extras:
- from pm.extras import extra_supported
- unsupported = [extra for extra in extras
- if not extra_supported(extra, importable=lambda _: False)]
- if unsupported:
- raise InstallError("venv", f"extras {unsupported} are not supported by this Python/platform",
- "choose a supported provider; no dependency environment was changed")
- shipped = read_features()
- frozen = shipped
- # Without a frozen declaration, explicit source setup needs no policy
- # read: the config loader initializes/chmods unrelated user state.
- if frozen is not None and not repair and lazy_installs_allowed():
- frozen = None
- if frozen is not None and extras:
- outside = sorted(set(extras) - set(frozen))
- if outside:
- raise _refuse_lazy(
- "venv",
- f"extras {outside} are outside this bundle's frozen feature "
- "set (security.allow_lazy_installs is false)",
- )
-
+ shipped, frozen = _feature_policy(extras, repair=repair)
package = get_package("venv")
- from hermes_cli.runtime_state import (
- INSTALL_LOCK_TIMEOUT_SECONDS, runtime_lock, recover_publication, finish_publication)
- from pm.publication import PluginSelection, StagedPlugin, candidate_members
- # Holding this lock means rebuilding the whole dependency environment, which takes tens of
- # seconds on a bundle. Only an install the user asked for may queue for it; an opportunistic
- # one (a lazy extra at first use, the only non-explicit caller) refuses instead of holding
- # a sibling profile's backend off its port behind a rebuild it did not request.
- lock_timeout = None if (explicit or repair) else INSTALL_LOCK_TIMEOUT_SECONDS
- with runtime_lock(paths.repo_root(), timeout=lock_timeout) as held:
- if not held:
- error = InstallError(
- "venv",
- f"another Hermes process is installing dependencies (waited {INSTALL_LOCK_TIMEOUT_SECONDS:.0f}s)",
- "retry in a moment, or run `hermes pm install` to install explicitly",
- )
- receipt.record_refusal("install-busy", str(error))
- raise error
+ from hermes_cli.runtime_state import recover_publication
+ from pm.publication import StagedPlugin
+ with _venv_install_lock(patient=explicit or repair):
recover_publication(paths.repo_root())
- if sum(value is not None for value in (selection, staged_plugin, plugin_dirs)) + bool(extra_plugin_dirs) > 1:
- raise ValueError("publication owns plugin member discovery")
- change = (PluginSelection(selection) if selection is not None else
- StagedPlugin(staged_plugin) if staged_plugin is not None else None)
+ change = _publication(plugins)
if isinstance(change, StagedPlugin) and not change.active:
- try:
- change.publish(paths.repo_root())
- finish_publication(paths.repo_root())
- except BaseException:
- recover_publication(paths.repo_root())
- raise
- receipt.record_venv_rebuild(False, "inactive plugin")
- outcome = "ok"
- return
- members = (change.members if change is not None else
- candidate_members(extra_plugin_dirs) if extra_plugin_dirs else plugin_dirs)
- inputs = {} if members is None else {"plugin_dirs": members}
- facts = Facts(paths.runtime_facts_path(), strict=repair)
- fact = facts.get("venv") or _facts().get("venv") or {}
- if repair:
- if fact and (not isinstance(fact.get("extras"), list)
- or any(not isinstance(extra, str) for extra in fact["extras"])
- or not isinstance(fact.get("stamp"), str) or not fact["stamp"]):
- raise InstallError("venv", "recorded dependency selection is incomplete; refusing to change its graph")
- enabled = list(fact.get("extras", frozen if frozen is not None else ["all"]))
- stamp = fact.get("stamp") or package.expected_stamp(enabled, plugin_dirs=[])
- inputs = {"repair": True}
+ _publish_inactive(change)
else:
- # The first writable generation replaces, rather than layers on,
- # the payload. Retain its extras until a recorded selection owns them.
- enabled = sorted(set(fact.get("extras", shipped or [])) | set(extras or []))
- stamp = package.expected_stamp(enabled, **inputs)
- if not repair and not explicit and not lazy_installs_allowed() and not _runtime_state_matches(fact, stamp):
- raise _refuse_lazy("venv", str(extras) if extras else "venv out of sync")
- current = not repair and _runtime_state_matches(fact, stamp)
- receipt.record_feature_list(enabled)
- try:
- result = {} if current else (package.apply(enabled, explicit=explicit, **inputs) or {})
- if not repair and package.expected_stamp(enabled, **inputs) != stamp:
- raise ValueError("Dependency inputs changed while preparing publication; retry.")
- if change is not None:
- change.publish(paths.repo_root())
- if not current:
- if result.get("environment") is not None:
- from pm.environments import flush_before_selecting
- flush_before_selecting()
- facts.record_state("venv", stamp, enabled, **result)
- if change is not None:
- finish_publication(paths.repo_root())
- receipt.record_venv_rebuild(not current, "already in sync" if current else "")
- except BaseException:
- recover_publication(paths.repo_root())
- raise
+ inputs = {"plugin_dirs": change.members} if change is not None else _member_inputs(plugins)
+ facts = Facts(paths.runtime_facts_path(), strict=repair)
+ fact = facts.get("venv") or _facts().get("venv") or {}
+ enabled, stamp, inputs = _target_selection(package, fact, extras=extras, inputs=inputs,
+ repair=repair, shipped=shipped, frozen=frozen)
+ current = not repair and _runtime_state_matches(fact, stamp)
+ if not current and not repair and not explicit and not lazy_installs_allowed():
+ raise _refuse_lazy("venv", str(extras) if extras else "venv out of sync")
+ receipt.record_feature_list(enabled)
+ _commit_selection(package, facts, change, enabled=enabled, stamp=stamp, inputs=inputs,
+ current=current, repair=repair, explicit=explicit)
outcome = "ok"
except BaseException as exc:
receipt.record_step("dependency-sync", False, f"{type(exc).__name__}: {exc}")
diff --git a/pm/plugin_inputs.py b/pm/plugin_inputs.py
new file mode 100644
index 00000000000..cead592325a
--- /dev/null
+++ b/pm/plugin_inputs.py
@@ -0,0 +1,71 @@
+"""What a venv sync or currency probe should take as its plugin members.
+
+Each request names exactly one source, so conflicting member inputs cannot be
+expressed. Stdlib only: the client, the worker and the engine all import it.
+"""
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+
+
+@dataclass(frozen=True)
+class Members:
+ """Build exactly these members and skip config discovery.
+
+ A mapping keys each member's installed identity to the tree that supplies it."""
+ dirs: Sequence[Path] | Mapping[Path, Path]
+
+
+@dataclass(frozen=True)
+class Candidates:
+ """Discover the enabled members and add these candidate directories."""
+ dirs: Sequence[Path]
+
+
+@dataclass(frozen=True)
+class Selection:
+ """Publish a proposed plugin enablement with the members it implies."""
+ data: Mapping
+
+
+@dataclass(frozen=True)
+class StagedUpdate:
+ """Publish a staged plugin tree over its install."""
+ data: Mapping
+
+
+PluginInput = Members | Candidates | Selection | StagedUpdate
+
+
+def encode(plugins: PluginInput | None) -> dict | None:
+ """JSON form for the worker request; paths become absolute strings."""
+ if plugins is None:
+ return None
+ if isinstance(plugins, Members):
+ if isinstance(plugins.dirs, Mapping):
+ return {"kind": "members", "sources": [[str(Path(key).absolute()), str(Path(source).absolute())]
+ for key, source in plugins.dirs.items()]}
+ return {"kind": "members", "paths": [str(Path(path).absolute()) for path in plugins.dirs]}
+ if isinstance(plugins, Candidates):
+ return {"kind": "candidates", "paths": [str(Path(path).absolute()) for path in plugins.dirs]}
+ kind = "selection" if isinstance(plugins, Selection) else "staged"
+ return {"kind": kind, "data": dict(plugins.data)}
+
+
+def decode(value: dict | None) -> PluginInput | None:
+ if value is None:
+ return None
+ kind = value["kind"]
+ if kind == "members":
+ if "sources" in value:
+ return Members({Path(identity): Path(source) for identity, source in value["sources"]})
+ return Members([Path(path) for path in value["paths"]])
+ if kind == "candidates":
+ return Candidates([Path(path) for path in value["paths"]])
+ if kind == "selection":
+ return Selection(value["data"])
+ if kind == "staged":
+ return StagedUpdate(value["data"])
+ raise ValueError(f"unknown plugin input kind: {kind!r}")
diff --git a/pm/worker.py b/pm/worker.py
index 6d56f05dddb..7b49ce305d6 100644
--- a/pm/worker.py
+++ b/pm/worker.py
@@ -9,14 +9,6 @@ import sys
import threading
-def _members(value):
- if value is None:
- return None
- if "sources" in value:
- return {Path(identity): Path(source) for identity, source in value["sources"]}
- return [Path(path) for path in value["paths"]]
-
-
def _read_controls(messages, pause, fd):
# Raw reads avoid a daemon thread holding sys.stdin's buffered lock at exit.
pending = b""
@@ -70,7 +62,7 @@ def main():
return message
request = receive()
- from pm import paths, receipt
+ from pm import paths, plugin_inputs, receipt
from pm.package import InstallError
from pm.registry import load_package_definitions
from pm.runtime import lease_current_runtime
@@ -108,7 +100,7 @@ def main():
implementation = OPERATIONS[operation].resolve(operation)
arguments = request["arguments"]
if request["operation"] in ("sync_venv", "venv_is_current"):
- arguments["plugin_dirs"] = _members(arguments.get("plugin_dirs"))
+ arguments["plugins"] = plugin_inputs.decode(arguments.get("plugins"))
if request["operation"] == "ensure":
arguments["pause_event"] = pause
for name in ("progress", "download_progress"):
diff --git a/scripts/ci/setup_toolchain.py b/scripts/ci/setup_toolchain.py
index d4c515168a4..d47589a8a3b 100644
--- a/scripts/ci/setup_toolchain.py
+++ b/scripts/ci/setup_toolchain.py
@@ -189,6 +189,7 @@ def dependencies(args) -> None:
from pm.environments import selected_venv
from pm import check_project_lock, sync_venv
+ from pm.plugin_inputs import Members
from pm.paths import repo_root
project = repo_root()
@@ -206,7 +207,7 @@ def dependencies(args) -> None:
python = ensure_testenv(project, extras)
venv = python.parent.parent
else:
- sync_venv(extras, explicit=True, plugin_dirs=[])
+ sync_venv(extras, explicit=True, plugins=Members([]))
venv = selected_venv(project)
bindir = venv / ("Scripts" if os.name == "nt" else "bin")
python = bindir / ("python.exe" if os.name == "nt" else "python")
diff --git a/tests/hermes_cli/test_plugins_cmd_catalog.py b/tests/hermes_cli/test_plugins_cmd_catalog.py
index 8b64a5d4dde..2f308f1791a 100644
--- a/tests/hermes_cli/test_plugins_cmd_catalog.py
+++ b/tests/hermes_cli/test_plugins_cmd_catalog.py
@@ -49,19 +49,17 @@ def world(client, tmp_path, monkeypatch):
monkeypatch.setattr(pc, "_scan_on_install_enabled", lambda: False)
monkeypatch.setattr(pc, "_console", lambda: type("C", (), {"print": lambda *a, **k: None})())
- def publish_without_environment(
- *_args, staged_plugin=None, selection=None, **_kwargs
- ):
+ def publish_without_environment(*_args, plugins=None, **_kwargs):
from hermes_cli.runtime_state import finish_publication
from pm import paths
+ from pm.plugin_inputs import Selection, StagedUpdate
from pm.publication import PluginSelection, StagedPlugin
- assert (staged_plugin is None) != (selection is None)
- if staged_plugin is not None:
- change = StagedPlugin(staged_plugin)
+ if isinstance(plugins, StagedUpdate):
+ change = StagedPlugin(dict(plugins.data))
else:
- assert selection is not None
- change = PluginSelection(selection)
+ assert isinstance(plugins, Selection)
+ change = PluginSelection(dict(plugins.data))
change.publish(paths.repo_root())
finish_publication(paths.repo_root())
diff --git a/tests/hermes_cli/test_tools_config_post_setup.py b/tests/hermes_cli/test_tools_config_post_setup.py
index d3177b51cb1..67451f022d0 100644
--- a/tests/hermes_cli/test_tools_config_post_setup.py
+++ b/tests/hermes_cli/test_tools_config_post_setup.py
@@ -133,7 +133,7 @@ def test_langfuse_setup_uses_plugin_admission_and_preserves_config_on_refusal(
def resolve_candidate(**kwargs):
assert kwargs["explicit"] is True
- assert kwargs["selection"]["enabled"]
+ assert kwargs["plugins"].data["enabled"]
if failure == "admission":
raise pm.InstallError("venv", "candidate refused")
# The real admission publisher must commit both lists, not a second UI writer.
@@ -141,7 +141,7 @@ def test_langfuse_setup_uses_plugin_admission_and_preserves_config_on_refusal(
from pm.paths import repo_root
from hermes_cli.runtime_state import runtime_lock, finish_publication
with runtime_lock(repo_root()):
- PluginSelection(kwargs["selection"]).publish(repo_root())
+ PluginSelection(dict(kwargs["plugins"].data)).publish(repo_root())
finish_publication(repo_root())
with (
diff --git a/tests/pm/test_environment_build.py b/tests/pm/test_environment_build.py
index bcbde04ab38..72408842f3a 100644
--- a/tests/pm/test_environment_build.py
+++ b/tests/pm/test_environment_build.py
@@ -9,6 +9,8 @@ import subprocess
import sys
import pytest
+
+from pm.plugin_inputs import Members
from tests.pm._fixtures import (
_run,
_wheel,
@@ -218,7 +220,7 @@ def test_first_bundle_extension_preserves_shipped_extras(locked_project, build_w
locked = (source / "uv.lock").read_bytes()
# Admission adds only a plugin, not a list of the bundle's optional extras.
- pm.sync_venv(explicit=True, plugin_dirs=[source / "member"])
+ pm.sync_venv(explicit=True, plugins=Members([source / "member"]))
first = selected_venv(source)
assert first != base
executable = first / python_relative
@@ -233,7 +235,7 @@ def test_first_bundle_extension_preserves_shipped_extras(locked_project, build_w
_wheel(tmp_path / "wheels", "member_dep", "1.1")
member = source / "member" / "pyproject.toml"
member.write_text(member.read_text(encoding="utf-8-sig").replace("member-dep==1.0", "member-dep==1.1"), encoding="utf-8")
- pm.sync_venv(explicit=True, plugin_dirs=[source / "member"])
+ pm.sync_venv(explicit=True, plugins=Members([source / "member"]))
second = selected_venv(source)
assert second != first
second_fact = Facts(runtime_facts_path(source)).get("venv")
@@ -261,21 +263,21 @@ def test_worker_sync_reuses_unions_and_reports_real_lock_drift(locked_project, b
# The worker imports its own class; this trap affects only inline installs.
monkeypatch.setattr("pm.packages.Venv.apply", lambda *a, **kw: pytest.fail("venv apply ran in caller"))
- pm.sync_venv(["chosen"], explicit=True, plugin_dirs=[])
+ pm.sync_venv(["chosen"], explicit=True, plugins=Members([]))
first = selected_venv(source)
first_fact = Facts(runtime_facts_path(source)).get("venv")
- pm.sync_venv(["chosen"], explicit=True, plugin_dirs=[])
+ pm.sync_venv(["chosen"], explicit=True, plugins=Members([]))
assert selected_venv(source) == first
assert Facts(runtime_facts_path(source)).get("venv") == first_fact
assert _run([str(first / ("Scripts/python.exe" if os.name == "nt" else "bin/python")), "-I", "-c",
"import base_dep, chosen_dep, importlib.util; assert importlib.util.find_spec('other_dep') is None; print(chosen_dep.__version__)"],
cwd=tmp_path, env=env) == "1.0"
- pm.sync_venv(["other"], explicit=True, plugin_dirs=[])
+ pm.sync_venv(["other"], explicit=True, plugins=Members([]))
second = selected_venv(source)
assert second != first
assert Facts(runtime_facts_path(source)).get("venv")["extras"] == ["chosen", "other"]
- pm.sync_venv(["chosen"], explicit=True, plugin_dirs=[])
+ pm.sync_venv(["chosen"], explicit=True, plugins=Members([]))
assert selected_venv(source) == second
assert _run([str(second / ("Scripts/python.exe" if os.name == "nt" else "bin/python")), "-I", "-c",
"import chosen_dep, other_dep; print(chosen_dep.__version__, other_dep.__version__)"],
@@ -687,7 +689,7 @@ def test_real_sync_retains_selection_until_commit(locked_project, tmp_path, monk
monkeypatch.setattr("pm._uv._toolchain", lambda **kw: (uv, Path(sys.executable)))
engine = importlib.import_module("pm.install")
monkeypatch.setattr(engine, "lazy_installs_allowed", lambda: True)
- engine.sync_venv(["chosen"], plugin_dirs=[], explicit=True)
+ engine.sync_venv(["chosen"], plugins=Members([]), explicit=True)
old = selected_venv(source)
facts = paths.runtime_facts_path().read_bytes()
home = Path(os.environ["HERMES_HOME"])
@@ -700,12 +702,12 @@ def test_real_sync_retains_selection_until_commit(locked_project, tmp_path, monk
with monkeypatch.context() as fault:
fault.setattr(Facts, "record_state", refuse)
with pytest.raises(OSError, match="facts disk full"):
- engine.sync_venv(["other"], plugin_dirs=[], explicit=True)
+ engine.sync_venv(["other"], plugins=Members([]), explicit=True)
assert selected_venv(source) == old
assert paths.runtime_facts_path().read_bytes() == facts
elif failure == "missing-cfg":
(old / "pyvenv.cfg").unlink()
- engine.sync_venv(["chosen"], plugin_dirs=[], explicit=True)
+ engine.sync_venv(["chosen"], plugins=Members([]), explicit=True)
assert selected_venv(source) != old
assert (selected_venv(source) / "pyvenv.cfg").is_file()
else:
diff --git a/tests/pm/test_plugin_inputs.py b/tests/pm/test_plugin_inputs.py
new file mode 100644
index 00000000000..ec73f88d118
--- /dev/null
+++ b/tests/pm/test_plugin_inputs.py
@@ -0,0 +1,25 @@
+"""The worker receives the same plugin input the caller built."""
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from pm.plugin_inputs import Candidates, Members, Selection, StagedUpdate, decode, encode
+
+
+ lambda root: None,
+ lambda root: Members([]),
+ lambda root: Members([root / "plugins/a", root / "plugins/b"]),
+ lambda root: Members({root / "home/plugins/a": root / "staged/a"}),
+ lambda root: Candidates([root / "plugins/candidate"]),
+ lambda root: Selection({"home": str(root / "home"), "enabled": ["a"], "disabled": [],
+ "expected_config": "missing"}),
+ lambda root: StagedUpdate({"target": str(root / "home/plugins/a"), "staged": str(root / "staged/a"),
+ "target_digest": None, "old_metadata": {},
+ "new_metadata": {"a": {"revision": "new"}}}),
+])
+def test_plugin_input_survives_the_worker_wire(build, tmp_path):
+ plugins = build(tmp_path)
+ assert decode(json.loads(json.dumps(encode(plugins)))) == plugins
diff --git a/tests/pm/test_plugin_survival_contract.py b/tests/pm/test_plugin_survival_contract.py
index 49ebff19cd1..d71ac628a29 100644
--- a/tests/pm/test_plugin_survival_contract.py
+++ b/tests/pm/test_plugin_survival_contract.py
@@ -36,6 +36,7 @@ import pytest
import hermes_yaml as yaml
import pm.workspace as ws
+from pm.plugin_inputs import Members
def _write_enabled(home: Path, enabled: list, provider: str | None = None) -> None:
@@ -309,7 +310,7 @@ def test_malformed_secondary_cannot_evict_recorded_member(admission_env, monkeyp
assert selected_venv(core) == selected
# Even a precomputed member list cannot bypass a newly broken profile.
with pytest.raises(ValueError, match="config.yaml"):
- sync_venv(explicit=True, plugin_dirs=[])
+ sync_venv(explicit=True, plugins=Members([]))
assert Facts(runtime_facts_path(core), strict=True).get("venv") == recorded
home_b = tmp_path / "home-b"
diff --git a/tests/pm/test_startup_recovery.py b/tests/pm/test_startup_recovery.py
index 63d067f4e7a..bc56a79a403 100644
--- a/tests/pm/test_startup_recovery.py
+++ b/tests/pm/test_startup_recovery.py
@@ -17,6 +17,7 @@ import sys
import pytest
from pm.lock import Facts, Lockfile
+from pm.plugin_inputs import Members
from pm.runtime import runtime_environment
from pm.store import current_target, tree_digest
from tests.pm._fixtures import _wheel
@@ -74,7 +75,7 @@ def test_bootstrap_repairs_before_dependency_activation(tmp_path, monkeypatch, m
clean.pop("UV_NO_CONFIG", None)
subprocess.run([uv, "lock"], cwd=core, env=clean, capture_output=True, check=True, timeout=60)
extras = ["startup-extra"]
- engine.sync_venv(extras, explicit=True, plugin_dirs=[])
+ engine.sync_venv(extras, explicit=True, plugins=Members([]))
old = selected_venv(core)
recorded = Facts(paths.runtime_facts_path(), strict=True).get("venv")
assert recorded is not None
diff --git a/tests/pm/test_worker.py b/tests/pm/test_worker.py
index 0bfdb7cdc7c..4cfb6390f9e 100644
--- a/tests/pm/test_worker.py
+++ b/tests/pm/test_worker.py
@@ -11,6 +11,7 @@ import pytest
from pm import paths
from pm.package import InstallError
+from pm.plugin_inputs import Members, Selection
from pm.runtime import runtime_python
from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
from tests.pm.test_runtime_wheelhouse import locked_wheelhouse # noqa: F401
@@ -117,22 +118,22 @@ def test_currency_probe_preserves_union_and_candidate_inputs(client, tmp_path, m
Facts(facts_path).record_state("venv", Venv(repo).expected_stamp(recorded, plugin_dirs=members), recorded,
environment=environment)
before = snapshot()
- assert client.venv_is_current(extras=["provider-extra"], plugin_dirs=members, **root_args)
- assert client.venv_is_current(extras=[], plugin_dirs=members, **root_args)
- assert not client.venv_is_current(extras=["new-extra"], plugin_dirs=members, **root_args)
- assert not client.venv_is_current(extras=recorded, plugin_dirs=[], **root_args)
+ assert client.venv_is_current(extras=["provider-extra"], plugins=Members(members), **root_args)
+ assert client.venv_is_current(extras=[], plugins=Members(members), **root_args)
+ assert not client.venv_is_current(extras=["new-extra"], plugins=Members(members), **root_args)
+ assert not client.venv_is_current(extras=recorded, plugins=Members([]), **root_args)
assert snapshot() == before, "currency queries changed dependency state"
assert bool(acquisitions) is (route != "direct")
pins.set_pin("uv", "unrelated", {"any": {"url": "https://example.invalid/uv", "sha256": "3" * 64}})
pins.save()
unchanged = snapshot()
- assert client.venv_is_current(extras=[], plugin_dirs=members, **root_args)
+ assert client.venv_is_current(extras=[], plugins=Members(members), **root_args)
assert snapshot() == unchanged
for version, digest in [("test.1", "2" * 64), ("test.2", "1" * 64)]:
pins.set_pin("python", version, {"any": {"url": "https://example.invalid/python", "sha256": digest}})
pins.save()
changed = snapshot()
- assert not client.venv_is_current(plugin_dirs=members, **root_args)
+ assert not client.venv_is_current(plugins=Members(members), **root_args)
assert snapshot() == changed
pins.set_pin("python", "test.1", {"any": {"url": "https://example.invalid/python", "sha256": "1" * 64}})
pins.save()
@@ -140,14 +141,14 @@ def test_currency_probe_preserves_union_and_candidate_inputs(client, tmp_path, m
contents = marker.read_bytes()
marker.unlink()
changed = snapshot()
- assert not client.venv_is_current(plugin_dirs=members, **root_args)
+ assert not client.venv_is_current(plugins=Members(members), **root_args)
assert snapshot() == changed
marker.write_bytes(contents)
- assert client.venv_is_current(plugin_dirs=members, **root_args)
+ assert client.venv_is_current(plugins=Members(members), **root_args)
manifest.write_text('name: candidate\npython_dependencies: ["candidate-dep==2"]\n')
changed = snapshot()
- assert not client.venv_is_current(extras=["provider-extra"], plugin_dirs=members, **root_args)
+ assert not client.venv_is_current(extras=["provider-extra"], plugins=Members(members), **root_args)
assert snapshot() == changed
assert selected_venv(repo) == environment
# Corruption must not be mistaken for a missing or current environment.
@@ -156,7 +157,7 @@ def test_currency_probe_preserves_union_and_candidate_inputs(client, tmp_path, m
facts_path.write_text(json.dumps(data))
malformed = snapshot()
with pytest.raises(ValueError, match="invalid recorded dependency state"):
- client.venv_is_current(extras=[], plugin_dirs=members, **root_args)
+ client.venv_is_current(extras=[], plugins=Members(members), **root_args)
assert snapshot() == malformed
@@ -187,9 +188,9 @@ def test_sync_discovers_profile_members_after_worker_acquires_lock(client, tmp_p
" with original(project, **kwargs) as held:\n yield held\nstate.runtime_lock = lock\n")
with ThreadPoolExecutor() as executor:
with runtime_lock(repo):
- future = executor.submit(client.sync_venv, explicit=explicit, selection={
+ future = executor.submit(client.sync_venv, explicit=explicit, plugins=Selection({
"home": str(tmp_path / "home"), "enabled": ["plain"], "disabled": [],
- })
+ }))
deadline = time.monotonic() + 15
while not ready.exists() and time.monotonic() < deadline:
time.sleep(0.01)
@@ -227,7 +228,7 @@ def test_lazy_disabled_sync_does_not_bootstrap_tools(client, tmp_path, monkeypat
lambda *a, **kw: pytest.fail("lazy-disabled sync prepared PM runtime"))
with receipt.worker_context("lazy-disabled-sync"):
with pytest.raises(InstallError, match="lazy installs are disabled") as caught:
- client.sync_venv([], plugin_dirs=[])
+ client.sync_venv([], plugins=Members([]))
result = receipt.last_for_update("lazy-disabled-sync", consume=True)
assert caught.value.package == "pm-runtime"
assert result is not None
@@ -247,7 +248,7 @@ def test_invalid_selection_waits_for_failed_receipt_and_lock_release(client, tmp
home = tmp_path / "home"
(home / "config.yaml").write_text("plugins: []\n")
with pytest.raises(ValueError, match="plugins must be a mapping"):
- client.sync_venv([], explicit=True, selection={"home": str(home), "enabled": [], "disabled": []})
+ client.sync_venv([], explicit=True, plugins=Selection({"home": str(home), "enabled": [], "disabled": []}))
receipts = list((home / "logs" / "update_receipts").glob("pm_*.json"))
assert len(receipts) == 1
assert json.loads(receipts[0].read_text())["outcome"] == "failed"
@@ -420,7 +421,7 @@ def test_worker_receipt_is_exact_even_if_latest_is_replaced(client, tmp_path, mo
monkeypatch.setattr(receipt, "accept_worker_receipt", accept)
with receipt.worker_context("my-update"):
- client.sync_venv([], explicit=True, plugin_dirs=[])
+ client.sync_venv([], explicit=True, plugins=Members([]))
result = receipt.last_for_update("my-update", consume=True)
assert received and result == received[0]
assert result["update_id"] == "my-update" and result["outcome"] == "ok"
@@ -456,7 +457,7 @@ def test_resolution_conflict_survives_worker_and_receipt(client, tmp_path, monke
"raise ResolutionConflict('venv', 'impossible union', 'change member')")
with receipt.worker_context("conflict-update"):
with pytest.raises(ResolutionConflict) as caught:
- client.sync_venv([], explicit=True, plugin_dirs=[])
+ client.sync_venv([], explicit=True, plugins=Members([]))
result = receipt.last_for_update("conflict-update", consume=True)
assert (caught.value.package, caught.value.cause, caught.value.remedy) == (
"venv", "impossible union", "change member")
@@ -482,7 +483,7 @@ def test_failed_facts_write_restores_exact_config_before_reporting(client, tmp_p
f" assert b'new' in Path({str(config)!r}).read_bytes()\n"
" raise OSError('facts disk full')\nFacts.record_state = fail\n")
with pytest.raises(OSError, match="facts disk full"):
- client.sync_venv(explicit=True, selection={"home": str(home), "enabled": ["new"], "disabled": []})
+ client.sync_venv(explicit=True, plugins=Selection({"home": str(home), "enabled": ["new"], "disabled": []}))
assert config.read_bytes() == previous
assert (install_state_dir(repo) / "facts.json").read_bytes() == facts
assert not (install_state_dir(repo) / "publication.json").exists()
@@ -517,7 +518,7 @@ def test_foreign_checkout_sync_uses_its_own_pm_generation(client, tmp_path, monk
client.lock_project(foreign, offline=True, explicit=True)
assert not venv_is_current(project_root=foreign)
original_root = paths.repo_root()
- client.sync_venv([], project_root=foreign, plugin_dirs=[], explicit=True)
+ client.sync_venv([], project_root=foreign, plugins=Members([]), explicit=True)
selected = selected_venv(foreign)
assert selected != foreign / "venv"
assert selected.is_relative_to(runtime_facts_path(foreign).parent)
diff --git a/tests/pm/test_worker_publication.py b/tests/pm/test_worker_publication.py
index 8255a0135f2..58127b38680 100644
--- a/tests/pm/test_worker_publication.py
+++ b/tests/pm/test_worker_publication.py
@@ -10,6 +10,8 @@ from pathlib import Path
import pytest
+from pm.plugin_inputs import Candidates, Selection, StagedUpdate
+
from tests.pm.test_worker import client, isolated_python, _current_environment # noqa: F401
from tests.pm._fixtures import worker_toolchain
@@ -25,9 +27,9 @@ def test_worker_publishes_selection_even_when_dependencies_are_current(client, t
repo = _current_environment(tmp_path, monkeypatch, [])
facts = (install_state_dir(repo) / "facts.json").read_bytes()
with receipt.worker_context("selection-publication"):
- client.sync_venv(explicit=True, selection={
+ client.sync_venv(explicit=True, plugins=Selection({
"home": str(home), "enabled": ["plain"], "disabled": ["old"], "extra_dirs": [],
- })
+ }))
result = receipt.last_for_update("selection-publication", consume=True)
from utils import fast_safe_load
assert fast_safe_load(config.read_text())["plugins"] == {"enabled": ["plain"], "disabled": ["old"]}
@@ -80,11 +82,11 @@ def test_staged_plugin_publication_uses_installed_identity_and_local_dependencie
with metadata_path.open("a", encoding="utf-8") as stream:
stream.write(f'no-index=true\nfind-links=[{json.dumps(wheel.parent.as_posix())}]\n')
(staged / "code.py").write_text('new code')
- client.sync_venv(explicit=True, staged_plugin={
+ client.sync_venv(explicit=True, plugins=StagedUpdate({
"staged": str(staged), "target": str(target), "target_digest": tree_digest(target) if target.exists() else None,
"old_metadata": {"example": {"revision": "old"}},
"new_metadata": {"example": {"revision": "new"}},
- })
+ }))
assert (target / "code.py").read_text() == "new code"
assert not staged.exists()
assert json.loads(metadata.read_text())["example"]["revision"] == "new"
@@ -124,7 +126,7 @@ def test_selection_refuses_config_edits_during_preparation(client, tmp_path, mon
)
worker_toolchain(client, monkeypatch, isolated_python, injection)
with pytest.raises(ValueError, match="changed"):
- client.sync_venv(explicit=True, selection={"home": str(home), "enabled": ["new"], "disabled": []})
+ client.sync_venv(explicit=True, plugins=Selection({"home": str(home), "enabled": ["new"], "disabled": []}))
assert edited.read_text() == expected
assert (install_state_dir(repo) / "facts.json").read_bytes() == facts
assert not (install_state_dir(repo) / "publication.json").exists()
@@ -148,10 +150,10 @@ def test_worker_rejects_unloadable_staged_plugin_without_app_dependencies(client
(staged / "plugin.yaml").write_text(invalid)
previous = tree_digest(target)
with pytest.raises(ValueError):
- client.sync_venv(explicit=True, staged_plugin={
+ client.sync_venv(explicit=True, plugins=StagedUpdate({
"target": str(target), "staged": str(staged), "target_digest": previous,
"old_metadata": {}, "new_metadata": {"example": {"revision": "new"}},
- })
+ }))
assert tree_digest(target) == previous
assert staged.exists()
@@ -161,10 +163,10 @@ def test_additional_candidates_are_discovered_by_sync_and_passive_probe(client,
candidate.mkdir()
(candidate / "plugin.yaml").write_text("name: candidate\npython_dependencies: [fixture-dep==1]\n")
_current_environment(tmp_path, monkeypatch, [candidate])
- assert client.venv_is_current(extra_plugin_dirs=[candidate])
+ assert client.venv_is_current(plugins=Candidates([candidate]))
assert not client.venv_is_current()
- client.sync_venv(explicit=True, extra_plugin_dirs=[candidate])
- assert client.venv_is_current(extra_plugin_dirs=[candidate])
+ client.sync_venv(explicit=True, plugins=Candidates([candidate]))
+ assert client.venv_is_current(plugins=Candidates([candidate]))
def test_memory_setup_sends_candidate_paths_instead_of_discovery_callbacks(tmp_path, monkeypatch):
@@ -174,7 +176,7 @@ def test_memory_setup_sends_candidate_paths_instead_of_discovery_callbacks(tmp_p
(candidate / "plugin.yaml").write_text("name: provider\npython_dependencies: [fixture-dep==1]\n")
monkeypatch.setattr("plugins.memory.find_provider_dir", lambda name: candidate)
_, inputs = memory_provider_dependency_inputs("provider")
- assert inputs == {"extras": [], "extra_plugin_dirs": [candidate]}
+ assert inputs == {"extras": [], "plugins": Candidates([candidate])}
@pytest.mark.parametrize(("kind", "rebuild", "phase"), [
@@ -214,7 +216,7 @@ def test_worker_death_recovers_at_each_durable_publication_boundary(
if kind == "selection":
if rebuild:
(target / "pyproject.toml").write_text(core.replace("death-proof", "example"))
- arguments = {"selection": {"home": str(home), "enabled": ["example"], "disabled": []}}
+ arguments = {"plugins": Selection({"home": str(home), "enabled": ["example"], "disabled": []})}
payload = config
else:
staged = tmp_path / "staged"
@@ -222,8 +224,9 @@ def test_worker_death_recovers_at_each_durable_publication_boundary(
(staged / "code.py").write_text("new")
if rebuild:
(staged / "pyproject.toml").write_text(core.replace("death-proof", "example"))
- arguments = {"staged_plugin": {"target": str(target), "staged": str(staged), "target_digest": before_tree,
- "old_metadata": {"example": {"revision": "old"}}, "new_metadata": {"example": {"revision": "new"}}}}
+ arguments = {"plugins": StagedUpdate({
+ "target": str(target), "staged": str(staged), "target_digest": before_tree,
+ "old_metadata": {"example": {"revision": "old"}}, "new_metadata": {"example": {"revision": "new"}}})}
payload = metadata
# Exit immediately after the real durable write, not a simulated publication.
injection = (
@@ -300,10 +303,10 @@ def test_staged_publication_refuses_concurrent_input_edits(client, tmp_path, mon
"Venv.apply = apply\n")
facts = (install_state_dir(repo) / "facts.json").read_bytes()
with pytest.raises(ValueError, match="changed"):
- client.sync_venv(explicit=True, staged_plugin={
+ client.sync_venv(explicit=True, plugins=StagedUpdate({
"target": str(target), "staged": str(staged), "target_digest": tree_digest(target),
"old_metadata": {}, "new_metadata": {"example": {"revision": "new"}},
- })
+ }))
assert edited.read_text() == proposed
assert (target / "code.py").read_text() == (proposed if mutation == "target" else "old code")
assert (install_state_dir(repo) / "facts.json").read_bytes() == facts
@@ -340,11 +343,11 @@ def test_staged_publication_preserves_a_concurrent_sibling_install_record(
"Venv.apply = apply\n",
)
- client.sync_venv(explicit=True, staged_plugin={
+ client.sync_venv(explicit=True, plugins=StagedUpdate({
"target": str(target), "staged": str(staged), "target_digest": tree_digest(target),
"old_metadata": {"example": {"revision": "old"}},
"new_metadata": {"example": {"revision": "new"}},
- })
+ }))
assert json.loads(metadata.read_text()) == {
"example": {"revision": "new"},
@@ -367,10 +370,10 @@ def test_inactive_portable_publication_does_not_inspect_unrelated_dependency_man
staged.mkdir()
from hermes_cli.agent_plugins import PLUGIN_SCHEMA_V1
(staged / "plugin.json").write_text(json.dumps({"$schema": PLUGIN_SCHEMA_V1, "name": "inactive", "version": "1.0.0"}))
- client.sync_venv(explicit=True, staged_plugin={
+ client.sync_venv(explicit=True, plugins=StagedUpdate({
"target": str(target), "staged": str(staged), "target_digest": tree_digest(target),
"old_metadata": {}, "new_metadata": {"inactive": {"revision": "new"}},
- })
+ }))
assert json.loads((target / "plugin.json").read_text())["name"] == "inactive"
assert (sibling / "plugin.yaml").read_bytes() == b"\xff"
@@ -382,7 +385,7 @@ def test_selection_preserves_yaml11_values_and_quotes_plugin_names(client, tmp_p
config = home / "config.yaml"
config.write_text('feature: yes\nother: no\nlabel: "on"\nplugins: {enabled: []}\n')
before = hermes_yaml.safe_load(config.read_bytes())
- client.sync_venv(explicit=True, selection={"home": str(home), "enabled": ["on", "yes", "no"], "disabled": []})
+ client.sync_venv(explicit=True, plugins=Selection({"home": str(home), "enabled": ["on", "yes", "no"], "disabled": []}))
after = hermes_yaml.safe_load(config.read_bytes())
assert {key: after[key] for key in ("feature", "other", "label")} == {key: before[key] for key in ("feature", "other", "label")}
assert set(after["plugins"]["enabled"]) == {"on", "yes", "no"}
@@ -404,7 +407,7 @@ def test_explicit_publication_keeps_its_intent_through_tool_acquisition(client,
"def acquire(*, explicit=False, **kwargs):\n"
" if not explicit: raise InstallError('tools', 'explicit intent was lost')\n"
" return tools(explicit=explicit, **kwargs)\npm._uv._toolchain = acquire\n")
- client.sync_venv(explicit=True, selection={"home": str(tmp_path / "home"), "enabled": [], "disabled": []})
+ client.sync_venv(explicit=True, plugins=Selection({"home": str(tmp_path / "home"), "enabled": [], "disabled": []}))
assert (selected_venv(project) / "pyvenv.cfg").is_file()