The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Make PM workers own plugin publication and recovery
ethernetd190198c770a
diff --git a/hermes_cli/memory_setup.py b/hermes_cli/memory_setup.pyindex c5daee0ffb4..bac6a6cd31c 100644--- a/hermes_cli/memory_setup.py+++ b/hermes_cli/memory_setup.py@@ -53,7 +53,6 @@ def _prompt(label: str, default: str | None = None, secret: bool = False) -> strdef memory_provider_dependency_inputs(provider_name: str) -> tuple[dict, dict]:"""Read one candidate declaration for preparation and passive readiness."""- from hermes_cli.plugins_admission import candidate_member_dirsfrom hermes_cli.plugins_cmd import PluginOperationError, _read_manifest_for_installfrom pm.package import InstallErrorfrom pm.workspace import _is_member_candidate@@ -74,7 +73,7 @@ def memory_provider_dependency_inputs(provider_name: str) -> tuple[dict, dict]:return meta, {}# Without a proposed home, selection retains every configured member.- inputs = {"plugin_dirs": lambda: candidate_member_dirs((), extra_dirs=[plugin_dir])} if member else {}+ inputs = {"extra_plugin_dirs": [plugin_dir]} if member else {}return meta, {"extras": extras, **inputs}diff --git a/hermes_cli/plugins_admission.py b/hermes_cli/plugins_admission.pyindex 7cdd20484b6..38f296ef13b 100644--- a/hermes_cli/plugins_admission.py+++ b/hermes_cli/plugins_admission.py@@ -1,5 +1,4 @@-"""Validate a proposed plugin set, then publish config and runtime selection."""-+"""Submit proposed plugin selections to the independent PM publisher."""from __future__ import annotationsfrom pathlib import Path@@ -10,96 +9,27 @@ class AdmissionRefused(RuntimeError):"""The candidate set was refused; config and environment untouched."""-def candidate_member_dirs(- candidate_enabled: Iterable[str],- candidate_disabled: Iterable[str] = (),- *,- active_plugins_dir: Optional[Path] = None,- extra_dirs: Iterable[Path] = (),-) -> list[Path]:- """Member dirs implied by the PROPOSED enabled sets: per plugins dir,- its enabled names — the active dir's replaced by the candidate set- (removals excluded), other homes unchanged — filtered to dirs that- actually declare python deps. ``extra_dirs`` (the install target)- join when they declare deps."""- from pm.workspace import enabled_member_dirs, _is_member_candidate-- active = Path(active_plugins_dir) if active_plugins_dir else None- members = enabled_member_dirs(- proposed_home=active.parent if active else None,- enabled=candidate_enabled, disabled=candidate_disabled,- )- for directory in extra_dirs:- directory = Path(directory)- if directory not in members and _is_member_candidate(directory):- members.append(directory)- return members---def _config_path() -> Path:- from hermes_cli.config import get_hermes_home-- return get_hermes_home() / "config.yaml"---def _config_commit(candidate_enabled: set, candidate_disabled: set):- """Journal both config versions before publishing either config or facts."""- import shutil- import tempfile-- from pm.paths import repo_root- from hermes_cli.runtime_state import begin_publication, _atomic_bytes- from hermes_cli.config import read_raw_config- from utils import atomic_roundtrip_yaml_save-- path = _config_path()- config = read_raw_config()- plugins_cfg = config.setdefault("plugins", {})- if not isinstance(plugins_cfg, dict):- raise ValueError(f"plugins must be a mapping in {path}")- plugins_cfg["enabled"] = sorted(candidate_enabled)- plugins_cfg["disabled"] = sorted(candidate_disabled)- with tempfile.TemporaryDirectory(prefix="hermes-admission-") as temporary:- staged = Path(temporary) / "config.yaml"- if path.is_file():- shutil.copyfile(path, staged)- atomic_roundtrip_yaml_save(staged, config)- proposed = staged.read_bytes()- publication = begin_publication(repo_root(), path, proposed)- try:- _atomic_bytes(path, proposed)- except BaseException:- publication()- raise- return publication--def admit_plugin_set_change(candidate_enabled: set,candidate_disabled: set,*,active_plugins_dir: Optional[Path] = None,extra_dirs: Iterable[Path] = (),+ expected_config: str | None = None,) -> None:- """Validate the proposed sets against the active environment and- commit — env selection and config move together, inside pm's single- locked transaction.+ """PM discovers and validates the proposed union under its install lock.- Raises :class:`AdmissionRefused` BEFORE anything is published when- the candidate union fails to resolve (conflict, frozen feature set,- …) or when the config write itself fails. The active environment and- the previous config bytes are kept EXACTLY — no rollback re-resolve.+ No config or dependency selection is written by this application process."""+ from hermes_constants import get_hermes_homefrom pm.client import sync_venv- extra_dirs = tuple(extra_dirs)+ home = Path(active_plugins_dir).parent if active_plugins_dir is not None else get_hermes_home()try:- sync_venv(- explicit=True,- plugin_dirs=lambda: candidate_member_dirs(- candidate_enabled, candidate_disabled, active_plugins_dir=active_plugins_dir, extra_dirs=extra_dirs- ),- before_publish=lambda: _config_commit(candidate_enabled, candidate_disabled),- )+ sync_venv(explicit=True, 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:raise AdmissionRefused(str(exc)) from excdiff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex 2acd905aa57..2aaa9031be0 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -852,6 +852,7 @@ def cmd_install(if should_enable:from hermes_cli.plugins_admission import AdmissionRefused+ expected_config = _plugin_selection_version()enabled = _get_enabled_set()disabled = _get_disabled_set()enabled.add(installed_name)@@ -862,7 +863,7 @@ def cmd_install(disabled,extra_dirs=[target],console=console,- action=f"Enable '{installed_name}'",+ action=f"Enable '{installed_name}'", expected_config=expected_config,)except AdmissionRefused:console.print(@@ -1012,19 +1013,23 @@ def _save_enabled_set(enabled: set) -> None:_write_config_value("plugins", "enabled", sorted(enabled))-def _save_plugin_sets(enabled: set, disabled: set) -> None:+def _plugin_selection_version() -> str:+ from hermes_cli.runtime_state import _digest+ return _digest(get_hermes_home() / "config.yaml") or "missing"+++def _save_plugin_sets(enabled: set, disabled: set, *, expected_config: str | None = None) -> None:from hermes_cli.plugins_admission import admit_plugin_set_change- admit_plugin_set_change(enabled, disabled, active_plugins_dir=_plugins_dir())+ admit_plugin_set_change(enabled, disabled, active_plugins_dir=_plugins_dir(), expected_config=expected_config)def _admit_and_save_plugin_sets(- enabled: set, disabled: set, *, extra_dirs=(), console=None, action: str = "enable"+ enabled: set, disabled: set, *, extra_dirs=(), console=None, action: str = "enable", expected_config=None) -> None:"""ONE admission authority for proposed enabled/disabled sets (C13):the candidate union is resolved against the ACTIVE environment and- the config commits inside the same locked pm transaction (sync's- ``before_publish`` hook) — a refusal or a config-write failure+ the config commits inside the same worker-owned PM transaction — a refusal or a config-write failurepublishes nothing: previous config bytes AND previous environmentstay exactly in place. Raises :class:`AdmissionRefused` (UI callerscatch and surface it — admission never auto-disables to fit)."""@@ -1032,7 +1037,7 @@ def _admit_and_save_plugin_sets(try:admit_plugin_set_change(- enabled, disabled, active_plugins_dir=_plugins_dir(), extra_dirs=extra_dirs+ enabled, disabled, active_plugins_dir=_plugins_dir(), extra_dirs=extra_dirs, expected_config=expected_config)except AdmissionRefused as exc:if console is not None:@@ -1071,11 +1076,12 @@ def _discard_key_and_leaf(names: set, key: str) -> None:def _set_plugin_enabled(name: str, *, enable: bool) -> None:"""Persist the proposed selection through the same dependency transaction."""+ expected_config = _plugin_selection_version()enabled = _get_enabled_set()disabled = _get_disabled_set()(enabled.add if enable else enabled.discard)(name)(disabled.discard if enable else disabled.add)(name)- _save_plugin_sets(enabled, disabled)+ _save_plugin_sets(enabled, disabled, expected_config=expected_config)def _resolve_plugin_key(name: str) -> Optional[str]:@@ -1134,6 +1140,7 @@ def cmd_enable(name: str, allow_tool_override: Optional[bool] = None) -> None:key, source = resolved_refuse_legacy_relay(key)+ expected_config = _plugin_selection_version()enabled = _get_enabled_set()disabled = _get_disabled_set()if key in enabled and key not in disabled:@@ -1147,7 +1154,7 @@ def cmd_enable(name: str, allow_tool_override: Optional[bool] = None) -> None:manifest_name = next((e[0] for e in _discover_all_plugins() if e[5] == key), None)if manifest_name is not None:disabled.discard(manifest_name)- _admit_and_save_plugin_sets(enabled, disabled, console=console, action=f"Enable '{key}'")+ _admit_and_save_plugin_sets(enabled, disabled, console=console, action=f"Enable '{key}'", expected_config=expected_config)console.print(f"[green]✓[/green] Plugin [bold]{key}[/bold] enabled. Takes effect on next session.")# Built-in tool override is a privileged grant; bundled plugins are trusted.@@ -1313,6 +1320,7 @@ def cmd_disable(name: str) -> None:key = _resolve_plugin_key(name)if key is None:_fail(console, f"[red]Plugin '{name}' is not installed or bundled.[/red]")+ expected_config = _plugin_selection_version()enabled = _get_enabled_set()disabled = _get_disabled_set()if key not in enabled and key in disabled:@@ -1321,7 +1329,7 @@ def cmd_disable(name: str) -> None:# Also drop a stale legacy bare-name entry so it can't keep a nested plugin loading._discard_key_and_leaf(enabled, key)disabled.add(key)- _save_plugin_sets(enabled, disabled)+ _save_plugin_sets(enabled, disabled, expected_config=expected_config)console.print(f"[yellow]\u2298[/yellow] Plugin [bold]{key}[/bold] disabled. Takes effect on next session.")@@ -1759,6 +1767,7 @@ def cmd_toggle() -> None:"""Interactive composite UI — general plugins + provider plugin categories."""console = _console()entries = _discover_all_plugins()+ expected_config = _plugin_selection_version()enabled_set = _get_enabled_set()disabled_set = _get_disabled_set()@@ -1783,12 +1792,12 @@ def cmd_toggle() -> None:returntry:import curses- _run_composite_ui(curses, plugin_keys, plugin_labels, plugin_selected, disabled_set, categories, console)+ _run_composite_ui(curses, plugin_keys, plugin_labels, plugin_selected, disabled_set, categories, console, expected_config=expected_config)except ImportError:- _run_composite_fallback(plugin_keys, plugin_labels, plugin_selected, disabled_set, categories, console)+ _run_composite_fallback(plugin_keys, plugin_labels, plugin_selected, disabled_set, categories, console, expected_config=expected_config)-def _persist_plugin_selection(plugin_keys, chosen, disabled) -> tuple[bool, set]:+def _persist_plugin_selection(plugin_keys, chosen, disabled, *, expected_config=None) -> tuple[bool, set]:"""Save the composite UI's checkbox state; returns ``(changed, new_enabled)``.Unchecked plugins go to the disabled-list (so they stay off even if something auto-enables@@ -1798,6 +1807,8 @@ def _persist_plugin_selection(plugin_keys, chosen, disabled) -> tuple[bool, set]# See #40190.# Persist by canonical key only — never the bare manifest name — so the disabled-list stays aligned with# cmd_enable / PluginManager (#40190).+ if expected_config is None:+ expected_config = _plugin_selection_version()new_enabled: set = set()new_disabled: set = set(disabled) # preserve existing disabled state for unseen pluginsfor i, key in enumerate(plugin_keys):@@ -1812,11 +1823,11 @@ def _persist_plugin_selection(plugin_keys, chosen, disabled) -> tuple[bool, set]# C13: the composite UI's candidate goes through the ONE admission# authority — refusal raises AdmissionRefused BEFORE any config# write; the caller surfaces it and the selection stays unsaved.- _admit_and_save_plugin_sets(new_enabled, new_disabled, action="Save plugin selection")+ _admit_and_save_plugin_sets(new_enabled, new_disabled, action="Save plugin selection", expected_config=expected_config)return changed, new_enabled-def _run_composite_ui(curses, plugin_keys, plugin_labels, plugin_selected, disabled, categories, console):+def _run_composite_ui(curses, plugin_keys, plugin_labels, plugin_selected, disabled, categories, console, *, expected_config=None):"""Custom curses screen with checkboxes + category action rows."""from hermes_cli.curses_ui import _addnstr, flush_stdinchosen = set(plugin_selected)@@ -1929,7 +1940,7 @@ def _run_composite_ui(curses, plugin_keys, plugin_labels, plugin_selected, disabfrom hermes_cli.plugins_admission import AdmissionRefusedtry:- changed, new_enabled = _persist_plugin_selection(plugin_keys, chosen, disabled)+ changed, new_enabled = _persist_plugin_selection(plugin_keys, chosen, disabled, expected_config=expected_config)except AdmissionRefused as exc:console.print(f"[red]✗[/red] Plugin selection refused, not saved: {exc}")console.print(@@ -1952,7 +1963,7 @@ def _run_composite_ui(curses, plugin_keys, plugin_labels, plugin_selected, disabconsole.print()-def _run_composite_fallback(plugin_keys, plugin_labels, plugin_selected, disabled, categories, console):+def _run_composite_fallback(plugin_keys, plugin_labels, plugin_selected, disabled, categories, console, *, expected_config=None):"""Text-based fallback for the composite plugins UI."""from hermes_cli.colors import Colors, colorprint(color("\n Plugins", Colors.YELLOW))@@ -1998,7 +2009,7 @@ def _save_plugin_selection_fallback(plugin_keys, chosen, disabled) -> None:from hermes_cli.plugins_admission import AdmissionRefusedtry:- _persist_plugin_selection(plugin_keys, chosen, disabled)+ _persist_plugin_selection(plugin_keys, chosen, disabled, expected_config=expected_config)except AdmissionRefused as exc:print(f" Plugin selection refused, not saved: {exc}")print(" config.yaml and the active environment are unchanged.")diff --git a/hermes_cli/plugins_transaction.py b/hermes_cli/plugins_transaction.pyindex 7a70ddac162..a45aea3ddb0 100644--- a/hermes_cli/plugins_transaction.py+++ b/hermes_cli/plugins_transaction.py@@ -1,121 +1,20 @@"""Publish plugin code and its dependency selection through one recoverable handoff."""from __future__ import annotations-import base64-import json-import osfrom pathlib import Pathimport shutil-import uuid-def recover_plugin_publication(project: Path, row: dict, journal: Path) -> None:- from hermes_cli.fs_utils import rmtree_force- from hermes_cli.runtime_paths import dependency_home_root, runtime_facts_path- from hermes_cli.runtime_state import _atomic_bytes, _bytes, _digest-- target, backup, metadata = (Path(row[key]) for key in ("target", "backup", "metadata"))- home = dependency_home_root().resolve()- if (not target.resolve().is_relative_to(home) or target.parent.name != "plugins"- or backup.parent != target.parent or not backup.name.startswith(".previous-")- or metadata != target.parent / ".install-metadata.json"):- raise ValueError("plugin publication paths escape their home")- committed = row.get("committed") or _digest(runtime_facts_path(project)) != row["facts_before"]- if committed:- if backup.exists():- rmtree_force(backup)- else:- old = base64.b64decode(row["metadata_before"], validate=True) if row["metadata_before"] is not None else None- current = _bytes(metadata)- new = base64.b64decode(row["metadata_after"], validate=True)- if current not in (old, new):- raise ValueError("plugin metadata changed after publication; preserve it for manual recovery")- if backup.exists():- if target.exists():- rmtree_force(target)- os.replace(backup, target)- elif not row["target_existed"] and target.exists():- rmtree_force(target)- if old is None:- metadata.unlink(missing_ok=True)- else:- _atomic_bytes(metadata, old)- journal.unlink()---class PluginPublication:- def __init__(self, project: Path, staged: Path, target: Path, metadata: dict):- from hermes_cli.runtime_paths import install_state_dir, runtime_facts_path- from hermes_cli.runtime_state import _atomic_bytes, _bytes, _digest-- self.project = project- self.journal = install_state_dir(project) / "publication.json"- backup = target.parent / f".previous-{uuid.uuid4().hex}"- metadata_path = target.parent / ".install-metadata.json"- previous = _bytes(metadata_path)- proposed = (json.dumps(metadata, indent=2, sort_keys=True) + "\n").encode("utf-8")- self.row = {- "kind": "plugin", "target": str(target), "backup": str(backup), "metadata": str(metadata_path),- "target_existed": target.exists(), "facts_before": _digest(runtime_facts_path(project)),- "metadata_before": base64.b64encode(previous).decode() if previous is not None else None,- "metadata_after": base64.b64encode(proposed).decode(),- }- _atomic_bytes(self.journal, json.dumps(self.row).encode())- try:- if target.exists():- os.replace(target, backup)- os.replace(staged, target)- _atomic_bytes(metadata_path, proposed)- except BaseException:- self()- raise-- def __call__(self) -> None:- recover_plugin_publication(self.project, self.row, self.journal)-- def finish(self) -> None:- from hermes_cli.runtime_state import _atomic_bytes-- # A code-only update has no new environment fact to mark its commit.- self.row["committed"] = True- _atomic_bytes(self.journal, json.dumps(self.row).encode())- recover_plugin_publication(self.project, self.row, self.journal)---def publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata: dict) -> None:- from hermes_cli import plugins_cmd- from hermes_cli.runtime_state import recover_publication, runtime_lock- from pm import paths+def publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata: dict,+ *, target_digest: str | None = None) -> None:from pm.client import sync_venv- from pm.workspace import _is_member_candidate, enabled_plugin_dirs, member_sources-- project = paths.repo_root()-- def candidate_members():- if plugins_cmd._read_install_metadata() != old_metadata:- raise plugins_cmd.PluginOperationError("Plugin install metadata changed while preparing the update; retry.")- sources = member_sources(enabled_plugin_dirs())- active = target.resolve() in sources- if active:- sources[target.resolve()] = staged- for source in sources.values():- plugins_cmd._check_manifest_version(plugins_cmd._read_manifest_for_install(source), source.name)- return {identity: source for identity, source in sources.items() if _is_member_candidate(source)}+ from pm.store import tree_digest- # Validate all active dependencies. The installed identity remains stable while- # PM snapshots the staged inputs into the candidate generation's workspace.- active = target.resolve() in member_sources(enabled_plugin_dirs())- if active:- sync_venv(explicit=True, plugin_dirs=candidate_members,- before_publish=lambda: PluginPublication(project, staged, target, new_metadata))- else:- with runtime_lock(project):- recover_publication(project)- if target.resolve() in member_sources(enabled_plugin_dirs()):- raise plugins_cmd.PluginOperationError("Plugin enablement changed while preparing the install; retry.")- if plugins_cmd._read_install_metadata() != old_metadata:- raise plugins_cmd.PluginOperationError("Plugin install metadata changed while preparing the install; retry.")- PluginPublication(project, staged, target, new_metadata).finish()+ sync_venv(explicit=True, staged_plugin={+ "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 update_plugin(target: Path, *, catalog_entry=None) -> str:@@ -196,7 +95,7 @@ def update_plugin(target: Path, *, catalog_entry=None) -> str:record["revision"] = revisionif tree_digest(staged) == before:return output- publish_plugin(staged, target, metadata, {**metadata, target.name: record})+ publish_plugin(staged, target, metadata, {**metadata, target.name: record}, target_digest=before)return outputexcept pc.PluginOperationError:raisediff --git a/hermes_cli/runtime_state.py b/hermes_cli/runtime_state.pyindex 42a17a0c9fe..faf5fd2ca75 100644--- a/hermes_cli/runtime_state.py+++ b/hermes_cli/runtime_state.py@@ -83,6 +83,38 @@ def _atomic_bytes(path: Path, data: bytes):Path(temporary).unlink(missing_ok=True)+def _recover_plugin_publication(project: Path, row: dict, journal: Path) -> None:+ from hermes_cli.fs_utils import rmtree_force++ target, backup, metadata = (Path(row[key]) for key in ("target", "backup", "metadata"))+ home = dependency_home_root().resolve()+ if (not target.resolve().is_relative_to(home) or target.parent.name != "plugins"+ or backup.parent != target.parent or not backup.name.startswith(".previous-")+ or metadata != target.parent / ".install-metadata.json"):+ raise ValueError("plugin publication paths escape their home")+ committed = row.get("committed") or _digest(runtime_facts_path(project)) != row["facts_before"]+ if committed:+ if backup.exists():+ rmtree_force(backup)+ else:+ old = base64.b64decode(row["metadata_before"], validate=True) if row["metadata_before"] is not None else None+ current = _bytes(metadata)+ new = base64.b64decode(row["metadata_after"], validate=True)+ if current not in (old, new):+ raise ValueError("plugin metadata changed after publication; preserve it for manual recovery")+ if backup.exists():+ if target.exists():+ rmtree_force(target)+ os.replace(backup, target)+ elif not row["target_existed"] and target.exists():+ rmtree_force(target)+ if old is None:+ metadata.unlink(missing_ok=True)+ else:+ _atomic_bytes(metadata, old)+ journal.unlink()++def recover_publication(project: Path) -> None:"""Recover while holding runtime_lock, before activation or another write."""journal = install_state_dir(project) / "publication.json"@@ -92,15 +124,13 @@ def recover_publication(project: Path) -> None:try:row = json.loads(data)if row.get("kind") == "plugin":- from hermes_cli.plugins_transaction import recover_plugin_publication-- recover_plugin_publication(project, row, journal)+ _recover_plugin_publication(project, row, journal)returnconfig = 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- if _digest(runtime_facts_path(project)) == row["facts_before"]:+ 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 Noneif current not in (prior, row.get("config_after")):@@ -115,26 +145,13 @@ def recover_publication(project: Path) -> None:raise RuntimeError(f"cannot recover dependency publication: {journal}: {exc}") from exc-class Publication:- def __init__(self, project: Path, config: Path, proposed: bytes | None = None):- self.project = project- self.journal = install_state_dir(project) / "publication.json"- previous = _bytes(config)- row = {"config": str(config.resolve()), "previous": base64.b64encode(previous).decode() if previous is not None else None,- "facts_before": _digest(runtime_facts_path(project)),- "config_after": hashlib.sha256(proposed).hexdigest() if proposed is not None else None}- _atomic_bytes(self.journal, json.dumps(row).encode())-- def __call__(self) -> None:- recover_publication(self.project)-- def finish(self) -> None:- self.journal.unlink(missing_ok=True)---def begin_publication(project: Path, config: Path, proposed: bytes | None = None) -> Publication:+def finish_publication(project: Path) -> None:+ """Persist a commit even when code/config changed without a new generation."""+ journal = install_state_dir(project) / "publication.json"+ row = json.loads(journal.read_bytes())+ row["committed"] = True+ _atomic_bytes(journal, json.dumps(row).encode())recover_publication(project)- return Publication(project, config, proposed)def lease_generation(environment: Path) -> None:diff --git a/pm/client.py b/pm/client.pyindex 95b6da96e41..9359de642a2 100644--- a/pm/client.py+++ b/pm/client.py@@ -122,10 +122,8 @@ def _request(operation, arguments, *, callbacks=None, pause_event=None, project_breakname = response["callback"]try:- value = callbacks[name](*response.get("args", []))- if name not in ("plugin_dirs", "before_publish"):- value = None- send({"type": "callback_result", "call": response["call"], "result": value})+ callbacks[name](*response.get("args", []))+ send({"type": "callback_result", "call": response["call"], "result": None})except BaseException as exc:if callback_error is None:callback_error = exc@@ -187,30 +185,19 @@ def ensure(name, *, base_env=None, explicit=False, progress=None, pause_event=Noreturn Runner(name, env_for(name, base_env=base_env))-def sync_venv(extras=None, *, explicit=False, plugin_dirs=None, before_publish=None, repair=False,+def sync_venv(extras=None, *, explicit=False, plugin_dirs=None, extra_plugin_dirs=(), selection=None, staged_plugin=None, repair=False,project_root: Path | None = None) -> None:+ if selection is not None and "expected_config" not in selection:+ from hermes_cli.runtime_state import _digest+ selection = {**selection, "expected_config": _digest(Path(selection["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.ensure import sync_venv as directreturn direct(extras, explicit=explicit, plugin_dirs=plugin_dirs,- before_publish=before_publish, repair=repair)- callbacks = {}- if callable(plugin_dirs):- callbacks["plugin_dirs"] = lambda: _members(plugin_dirs())- members = None- else:- members = _members(plugin_dirs)- if before_publish is not None:- def publish():- publication = before_publish()- if publication is not None:- callbacks["undo"] = publication- if hasattr(publication, "finish"):- callbacks["finish"] = publication.finish- return {"undo": publication is not None, "finish": hasattr(publication, "finish")}- callbacks["before_publish"] = publish+ selection=selection, staged_plugin=staged_plugin, extra_plugin_dirs=extra_plugin_dirs, repair=repair)_request("sync_venv", {"extras": extras, "explicit": explicit, "repair": repair,- "plugin_dirs": members}, callbacks=callbacks, project_root=project_root)+ "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)def stage_only(name, target, *, progress=None) -> Path:@@ -302,15 +289,16 @@ def ensure_python_tool(}))-def venv_is_current(*, extras: list[str] | None = None, plugin_dirs=None,+def venv_is_current(*, extras: list[str] | None = None, plugin_dirs=None, extra_plugin_dirs=(),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.ensure import venv_is_current as direct- return direct(extras=extras, plugin_dirs=plugin_dirs, project_root=project_root)- members = plugin_dirs() if callable(plugin_dirs) else plugin_dirs+ return direct(extras=extras, plugin_dirs=plugin_dirs, extra_plugin_dirs=extra_plugin_dirs, project_root=project_root)+ members = plugin_dirstry:- return bool(_request("venv_is_current", {"extras": extras, "plugin_dirs": _members(members)},+ 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]},project_root=project_root))except InstallError as exc:if exc.package == "pm-runtime":diff --git a/pm/ensure.py b/pm/ensure.pyindex c84b9daf136..0166122fd94 100644--- a/pm/ensure.py+++ b/pm/ensure.py@@ -444,7 +444,7 @@ def _runtime_state_matches(fact: dict, stamp: str, *, project_root: Path | Nonereturn (environment / "pyvenv.cfg").is_file()-def venv_is_current(*, extras: list[str] | None = None, plugin_dirs=None,+def venv_is_current(*, extras: list[str] | None = None, plugin_dirs=None, extra_plugin_dirs=(),project_root: Path | None = None) -> bool:"""Probe the requested union without changing recorded dependency state."""from hermes_cli.runtime_paths import runtime_facts_path@@ -462,13 +462,16 @@ def venv_is_current(*, extras: list[str] | None = None, plugin_dirs=None,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 []))- members = plugin_dirs() if callable(plugin_dirs) else plugin_dirs+ 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_dirsinputs = {} if members is None else {"plugin_dirs": members}stamp = package.expected_stamp(enabled, **inputs)return _runtime_state_matches(fact, stamp, project_root=root)-def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plugin_dirs=None, before_publish=None, repair: bool = False) -> None:+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:"""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,@@ -487,19 +490,15 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, pluBEFORE the frozen/lazy refusals (a refusal is a recorded ``failed``outcome, not a silent raise); finalize runs in FINALLY — no-op syncs("ok" with ``venv_rebuild`` false) and refusals ("failed") both get- a receipt. ``before_publish`` is the concrete selection hook: called- while the install lock is held, AFTER the environment staged and- BEFORE the facts write — it returns an undo callable that runs if- the facts write then fails, so a selection committed here is rolled- back atomically instead of drifting from the surviving environment.- No module globals, no callback framework — one hook, one consumer."""+ 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 receiptfrom pm.features import read_featurestoken = receipt.begin("sync")outcome = "failed"try:- if repair and (extras is not None or plugin_dirs is not None or before_publish is not None):+ 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):raise ValueError("repair restores the recorded environment; it cannot change features or plugins")if extras:from pm.extras import extra_supported@@ -519,10 +518,26 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plu)package = get_package("venv")- from hermes_cli.runtime_state import runtime_lock, recover_publication+ from hermes_cli.runtime_state import runtime_lock, recover_publication, finish_publication+ from pm.publication import PluginSelection, StagedPlugin, candidate_memberswith runtime_lock(paths.repo_root()):recover_publication(paths.repo_root())- members = plugin_dirs() if callable(plugin_dirs) else plugin_dirs+ 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)+ 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 {}@@ -539,30 +554,21 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plustamp = 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")- if not repair and _runtime_state_matches(fact, stamp):- if before_publish is not None:- publication = before_publish()- if hasattr(publication, "finish"):- publication.finish()- receipt.record_venv_rebuild(False, "already in sync")- outcome = "ok"- return+ current = not repair and _runtime_state_matches(fact, stamp)receipt.record_feature_list(enabled)- undo = Nonetry:- result = package.apply(enabled, **inputs) or {}- if before_publish is not None:- undo = before_publish()- facts.record_state("venv", stamp, enabled, **result)- if hasattr(undo, "finish"):- undo.finish()- receipt.record_venv_rebuild(True)+ 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:+ 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:- if undo is not None:- try:- undo()- except Exception:- LOG.exception("pm sync: publish undo failed; config may drift")+ recover_publication(paths.repo_root())raiseoutcome = "ok"except BaseException as exc:diff --git a/pm/package.py b/pm/package.pyindex 69cea6b3fb0..b9c2c3c90d3 100644--- a/pm/package.py+++ b/pm/package.py@@ -351,7 +351,7 @@ class StatePackage(Package):def expected_stamp(self, extras: list[str]) -> str:raise NotImplementedError- def apply(self, extras: list[str]) -> None:+ def apply(self, extras: list[str], *, explicit: bool = False) -> None:raise NotImplementedErrordiff --git a/pm/packages.py b/pm/packages.pyindex 04c444c745c..acde350caad 100644--- a/pm/packages.py+++ b/pm/packages.py@@ -397,7 +397,7 @@ class Venv(StatePackage):h.update(members_stamp(enabled_member_dirs() if plugin_dirs is None else plugin_dirs).encode())return h.hexdigest()- def apply(self, extras: list[str], *, plugin_dirs=None, repair: bool = False) -> dict:+ def apply(self, extras: list[str], *, plugin_dirs=None, repair: bool = False, explicit: bool = False) -> dict:"""Prepare one complete environment; the caller commits its selection."""import uuidfrom hermes_cli.runtime_paths import install_state_dir, runtime_facts_path@@ -408,7 +408,7 @@ class Venv(StatePackage):project = self.project_root()generation = install_state_dir(project) / "environments" / uuid.uuid4().hexcandidate = generation / "venv"- environment = managed_environment(candidate, explicit=repair)+ environment = managed_environment(candidate, explicit=explicit or repair)members = [] if repair else (enabled_member_dirs() if plugin_dirs is None else plugin_dirs)try:generation.mkdir(parents=True)diff --git a/pm/plugins_state.py b/pm/plugins_state.pyindex 25fc6cb0863..14d50af5107 100644--- a/pm/plugins_state.py+++ b/pm/plugins_state.py@@ -102,7 +102,7 @@ def _all_homes() -> list[Path]:return homes-def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None) -> dict[Path, list[str]]:+def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None, installing: Path | None = None) -> dict[Path, list[str]]:"""plugins_dir → ordered enabled list, per home. Keyed by thePLUGINS DIR (where the member dirs live), not the home itself.@@ -119,7 +119,7 @@ def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None)if proposed_home is not None and home.resolve() == Path(proposed_home).resolve():config = {**config, "plugins": {"enabled": list(enabled or ()), "disabled": list(disabled or ())}}names = _enabled_from_config(config)- provider = _provider_from_config(home, config)+ provider = _provider_from_config(home, config, installing=installing)if provider and provider not in names:names.append(provider)if names:@@ -127,11 +127,12 @@ def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None)return out-def _provider_from_config(home: Path, config: dict[str, Any]) -> Optional[str]:+def _provider_from_config(home: Path, config: dict[str, Any], *, installing: Path | None = None) -> Optional[str]:"""The ``memory.provider`` key of an already-parsed config, when itsplugin dir exists (no dir = not a member)."""provider = (config.get("memory") or {}).get("provider")if not provider or not provider.strip():return Nonename = provider.strip()- return name if _is_directory(home / "plugins" / name) else None+ return name if (_is_directory(home / "plugins" / name) or+ (installing is not None and (home / "plugins" / name).resolve() == installing.resolve())) else Nonediff --git a/pm/publication.py b/pm/publication.pynew file mode 100644index 00000000000..9548ba90dd9--- /dev/null+++ b/pm/publication.py@@ -0,0 +1,170 @@+"""Worker-local plugin selection and code publication. No application dependency imports.++Requests carry proposed data; discovery, snapshots and publication happen only+while the install lock is held. The stdlib boot journal owns crash recovery.+"""+from __future__ import annotations++import base64+import hashlib+import io+import json+from pathlib import Path++from hermes_cli.runtime_paths import dependency_home_root, install_state_dir, runtime_facts_path+from hermes_cli.runtime_state import _atomic_bytes, _bytes, _digest+from pm.workspace import enabled_plugin_dirs, _is_member_candidate+++def candidate_members(extra_dirs=(), **selection):+ selected = enabled_plugin_dirs(**selection)+ for source in selected:+ validate_manifest(source)+ members = [source for source in selected if _is_member_candidate(source)]+ for directory in extra_dirs:+ directory = Path(directory)+ if directory not in members and _is_member_candidate(directory):+ members.append(directory)+ return members+++def selection_snapshot() -> dict[Path, bytes | None]:+ from pm.plugins_state import _all_homes+ return {home / "config.yaml": _bytes(home / "config.yaml") for home in _all_homes()}+++def validate_manifest(source: Path) -> dict:+ # These parsers depend only on stdlib + PM's YAML runtime, never plugins_cmd+ # or the application's config/UI dependency tree.+ from hermes_yaml import safe_load, YAMLError+ from hermes_cli.plugins_manifest import SUPPORTED_MANIFEST_VERSION, requires_hermes_error++ native = next((source / name for name in ("plugin.yaml", "plugin.yml") if (source / name).exists()), None)+ try:+ if native is not None:+ manifest = safe_load(native.read_text(encoding="utf-8-sig"))+ elif (source / "plugin.json").exists() or (source / "plugin.json").is_symlink():+ from hermes_cli.agent_plugins import read_agent_plugin_manifest+ manifest, _ = read_agent_plugin_manifest(source)+ else:+ return {}+ except (OSError, UnicodeError, YAMLError) as exc:+ raise ValueError(f"Could not read plugin manifest {source}: {exc}") from exc+ if not isinstance(manifest, dict):+ raise ValueError(f"Plugin manifest must be a mapping: {source}")+ reason = requires_hermes_error(manifest)+ if reason:+ raise ValueError(f"Plugin '{source.name}' {reason}")+ if manifest.get("manifest_version") is not None:+ try:+ version = int(manifest["manifest_version"])+ except (ValueError, TypeError) as exc:+ raise ValueError(f"Plugin '{source.name}' has invalid manifest_version") from exc+ if version > SUPPORTED_MANIFEST_VERSION:+ raise ValueError(f"Plugin '{source.name}' requires manifest_version {version}; update Hermes first")+ return manifest+++class PluginSelection:+ def __init__(self, selection: dict):+ from hermes_yaml import roundtrip_yaml++ self.configs = selection_snapshot()+ self.home = Path(selection["home"]).resolve()+ if not self.home.is_relative_to(dependency_home_root().resolve()):+ raise ValueError("config path is outside Hermes state")+ self.path = self.home / "config.yaml"+ self.previous = _bytes(self.path)+ expected = selection.get("expected_config")+ actual = hashlib.sha256(self.previous).hexdigest() if self.previous is not None else "missing"+ if expected is not None and expected != actual:+ raise ValueError("Plugin configuration changed since this selection was read; retry.")+ yaml = roundtrip_yaml()+ config = yaml.load(self.previous.decode("utf-8-sig")) if self.previous else {}+ if config is None:+ config = {}+ if not isinstance(config, dict):+ raise ValueError(f"configuration must be a mapping: {self.path}")+ plugins = config.setdefault("plugins", {})+ if not isinstance(plugins, dict):+ raise ValueError(f"plugins must be a mapping in {self.path}")+ plugins["enabled"] = sorted(selection["enabled"])+ plugins["disabled"] = sorted(selection["disabled"])+ output = io.StringIO()+ yaml.dump(config, output)+ self.proposed = output.getvalue().encode("utf-8")+ self.members = candidate_members(selection.get("extra_dirs", ()), proposed_home=self.home,+ enabled=selection["enabled"], disabled=selection["disabled"])++ def publish(self, project: Path) -> None:+ if selection_snapshot() != self.configs or _bytes(self.path) != self.previous:+ raise ValueError("plugin configuration changed while preparing publication; retry")+ row = {"config": str(self.path),+ "previous": base64.b64encode(self.previous).decode() if self.previous is not None else None,+ "facts_before": _digest(runtime_facts_path(project)),+ "config_after": hashlib.sha256(self.proposed).hexdigest()}+ _atomic_bytes(install_state_dir(project) / "publication.json", json.dumps(row).encode())+ _atomic_bytes(self.path, self.proposed)+++class StagedPlugin:+ def __init__(self, plugin: dict):+ from pm.store import tree_digest+ from pm.workspace import enabled_plugin_dirs, member_sources++ self.configs = selection_snapshot()+ self.target = Path(plugin["target"]).absolute()+ self.staged = Path(plugin["staged"]).resolve()+ if (not self.target.resolve().is_relative_to(dependency_home_root().resolve())+ or self.target.parent.name != "plugins" or self.target.is_symlink()+ or self.staged == self.target.resolve() or self.staged.is_relative_to(self.target.resolve())+ or self.target.resolve().is_relative_to(self.staged)):+ raise ValueError("plugin publication paths escape or overlap their home")+ manifest = validate_manifest(self.staged)+ if manifest.get("name", self.target.name) != self.target.name:+ raise ValueError("The updated plugin changed its installed name; reinstall it explicitly.")+ self.staged_digest = tree_digest(self.staged)+ self.metadata = self.target.parent / ".install-metadata.json"+ self.previous = _bytes(self.metadata)+ current = json.loads(self.previous) if self.previous is not None else {}+ if current != plugin["old_metadata"]:+ raise ValueError("Plugin install metadata changed while preparing the update; retry.")+ self.target_digest = tree_digest(self.target) if self.target.exists() else None+ if self.target_digest != plugin["target_digest"]:+ raise ValueError("Plugin files changed while preparing the update; retry.")+ self.proposed = (json.dumps(plugin["new_metadata"], indent=2, sort_keys=True) + "\n").encode()+ sources = member_sources(enabled_plugin_dirs(installing=self.target))+ self.active = self.target.resolve() in sources+ self.members = {}+ if self.active:+ sources[self.target.resolve()] = self.staged+ for source in sources.values():+ validate_manifest(source)+ self.members = {identity: source for identity, source in sources.items() if _is_member_candidate(source)}++ def publish(self, project: Path) -> None:+ import os+ import uuid+ from pm.store import tree_digest++ if selection_snapshot() != self.configs:+ raise ValueError("Plugin enablement changed while preparing the update; retry.")+ if tree_digest(self.staged) != self.staged_digest:+ raise ValueError("Staged plugin files changed while preparing the update; retry.")+ if _bytes(self.metadata) != self.previous:+ raise ValueError("Plugin install metadata changed while preparing the update; retry.")+ current = tree_digest(self.target) if self.target.exists() else None+ if current != self.target_digest:+ raise ValueError("Plugin files changed while preparing the update; retry.")+ backup = self.target.parent / f".previous-{uuid.uuid4().hex}"+ row = {+ "kind": "plugin", "target": str(self.target), "backup": str(backup), "metadata": str(self.metadata),+ "target_existed": self.target.exists(), "facts_before": _digest(runtime_facts_path(project)),+ "metadata_before": base64.b64encode(self.previous).decode() if self.previous is not None else None,+ "metadata_after": base64.b64encode(self.proposed).decode(),+ }+ _atomic_bytes(install_state_dir(project) / "publication.json", json.dumps(row).encode())+ if self.target.exists():+ os.replace(self.target, backup)+ os.replace(self.staged, self.target)+ _atomic_bytes(self.metadata, self.proposed)diff --git a/pm/worker.py b/pm/worker.pyindex 45d7ca38606..1854140b07e 100644--- a/pm/worker.py+++ b/pm/worker.py@@ -92,37 +92,18 @@ def main():raise RuntimeError(reply["error"])return reply["result"]- def sync_venv(**arguments):- if "plugin_dirs" in request["callbacks"]:- arguments["plugin_dirs"] = lambda: _members(callback("plugin_dirs"))- else:- arguments["plugin_dirs"] = _members(arguments["plugin_dirs"])- if "before_publish" in request["callbacks"]:- def publish():- hooks = callback("before_publish")- if not any(hooks.values()):- return None- def undo():- if hooks["undo"]:- callback("undo")- if hooks["finish"]:- undo.finish = lambda: callback("finish")- return undo- arguments["before_publish"] = publish- return engine.sync_venv(**arguments)-with receipt.worker_context(request.get("update_id")):try:load_package_definitions(request.get("packages", []))from pm import operations as python- operations = {"ensure": engine.ensure, "sync_venv": sync_venv,+ operations = {"ensure": engine.ensure, "sync_venv": engine.sync_venv,"stage_only": engine.stage_only, "venv_is_current": engine.venv_is_current,"build_environment": python.build_environment, "lock_project": python.lock_project,"stage_manager_runtime": python.stage_manager_runtime,"ensure_environment": python.ensure_environment,"ensure_python_tool": python.ensure_python_tool}arguments = request["arguments"]- if request["operation"] == "venv_is_current":+ if request["operation"] in ("sync_venv", "venv_is_current"):arguments["plugin_dirs"] = _members(arguments.get("plugin_dirs"))if request["operation"] == "ensure":arguments["pause_event"] = pausediff --git a/pm/workspace.py b/pm/workspace.pyindex 5a29aed04e5..2f6206d1ffe 100644--- a/pm/workspace.py+++ b/pm/workspace.py@@ -179,12 +179,12 @@ def _is_member_candidate(plugin_dir: Path) -> bool:return False-def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:+def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None, installing: Path | None = None) -> list[Path]:"""Resolve the effective plugin selection without filtering dependency declarations."""from pm.plugins_state import _is_directory, enabled_plugins_ordered- selection = enabled_plugins_ordered() if proposed_home is None else enabled_plugins_ordered(- proposed_home=proposed_home, enabled=enabled, disabled=disabled,+ selection = enabled_plugins_ordered(+ proposed_home=proposed_home, enabled=enabled, disabled=disabled, installing=installing,)members = []for plugins_dir, names in selection.items():@@ -193,9 +193,10 @@ def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None) -> lif relative.is_absolute() or ".." in relative.parts:raise InstallError("venv", f"invalid plugin key: {name}")plugin_dir = plugins_dir / relative- if not _is_directory(plugin_dir):+ proposed = installing is not None and plugin_dir.resolve() == installing.resolve()+ if not proposed and not _is_directory(plugin_dir):plugin_dir = paths.repo_root() / "plugins" / relative- if _is_directory(plugin_dir):+ if proposed or _is_directory(plugin_dir):members.append(plugin_dir)return list(dict.fromkeys(members))diff --git a/tests/hermes_cli/test_plugin_update_recovery.py b/tests/hermes_cli/test_plugin_update_recovery.pyindex eb89e35d45a..c5e447f74fd 100644--- a/tests/hermes_cli/test_plugin_update_recovery.py+++ b/tests/hermes_cli/test_plugin_update_recovery.py@@ -28,11 +28,14 @@ def test_boot_recovers_plugin_publication_after_process_death(tmp_path, committeprogram = '''from pathlib import Pathimport os,sys-from hermes_cli.plugins_transaction import PluginPublication+from pm.publication import StagedPlugin+from pm.store import tree_digestfrom hermes_cli.runtime_paths import runtime_facts_pathfrom pm.lock import Factsproject,staged,target = map(Path,sys.argv[1:4])-pub = PluginPublication(project,staged,target,{"example":{"revision":"new"}})+StagedPlugin({"staged": str(staged), "target": str(target), "target_digest": tree_digest(target),+ "old_metadata": {"example":{"revision":"old"}},+ "new_metadata": {"example":{"revision":"new"}}}).publish(project)if sys.argv[4] == "True":Facts(runtime_facts_path(project)).record_state("venv","new",[])os._exit(17)diff --git a/tests/hermes_cli/test_plugins_admission_setter.py b/tests/hermes_cli/test_plugins_admission_setter.pyindex 21b1ad1e83d..e409829ac5f 100644--- a/tests/hermes_cli/test_plugins_admission_setter.py+++ b/tests/hermes_cli/test_plugins_admission_setter.py@@ -1,7 +1,7 @@"""C13 enable admission: every UI path's proposed enabled/disabled sets gothrough ONE authority — the candidate union resolves against the activeenvironment and the config commits inside pm's single locked transaction-(sync's before_publish hook). Refusal (dep conflict OR config-write+(worker-owned publication). Refusal (dep conflict OR config-writefailure) publishes nothing: previous config bytes and previous environmentstay exactly in place. Real temp HERMES_HOME — no live user writes."""@@ -54,11 +54,15 @@ def sync_calls(monkeypatch):from pm import clientcalls = []- def _sync(extras=None, *, explicit=False, plugin_dirs=None, before_publish=None):- members = plugin_dirs() if callable(plugin_dirs) else plugin_dirs- calls.append(list(members or []))- if before_publish is not None:- before_publish() # same contract: config commits under the sync+ def _sync(extras=None, *, explicit=False, selection=None):+ from pm.publication import PluginSelection+ from pm.paths import repo_root+ from hermes_cli.runtime_state import runtime_lock, finish_publication+ with runtime_lock(repo_root()):+ change = PluginSelection(selection)+ calls.append(list(change.members))+ change.publish(repo_root())+ finish_publication(repo_root())monkeypatch.setattr(client, "sync_venv", _sync)return calls@@ -157,7 +161,7 @@ def test_dashboard_enable_refusal_reports_not_ok(plugin_home, monkeypatch, sync_assert _enabled_set(plugin_home) == set()-# ── the before_publish hook: config commits under the lock, undo on facts failure ─+# ── worker-owned publication: exact rollback on facts failure ─def test_config_commit_undo_restores_previous_bytes(plugin_home):@@ -165,14 +169,17 @@ def test_config_commit_undo_restores_previous_bytes(plugin_home):config_path = plugin_home / "config.yaml"previous = config_path.read_bytes()- undo = adm._config_commit({"dep-plug"}, set())+ from pm.publication import PluginSelection+ from pm.paths import repo_root+ from hermes_cli.runtime_state import recover_publication+ PluginSelection({"home": str(plugin_home), "enabled": ["dep-plug"], "disabled": []}).publish(repo_root())assert _enabled_set(plugin_home) == {"dep-plug"} # committed exactly once- undo() # facts write failed afterwards → restore+ recover_publication(repo_root()) # facts write failed afterwards → restoreassert config_path.read_bytes() == previousdef test_facts_failure_triggers_undo_inside_one_transaction(plugin_home, monkeypatch):- """Real sync_venv: apply stages → before_publish commits config → facts+ """Real sync_venv: apply stages → worker commits config → factswrite fails → undo restores the previous config bytes atomically; thereceipt records the failure."""import importlib@@ -199,10 +206,6 @@ def test_facts_failure_triggers_undo_inside_one_transaction(plugin_home, monkeyporder = []- def before_publish():- order.append("before_publish")- return adm._config_commit({"dep-plug"}, set())-facts_path = plugin_home / "runtime" / "facts.json"ensure.Facts(facts_path).record_state("venv", "previous-stamp", [])previous_facts = facts_path.read_bytes()@@ -210,13 +213,14 @@ def test_facts_failure_triggers_undo_inside_one_transaction(plugin_home, monkeypmonkeypatch.setattr(ensure.paths, "repo_root", lambda: plugin_home / "runtime")def fail_publication(self, *args, **kwargs):+ assert _enabled_set(plugin_home) == {"dep-plug"}order.append("record_state")raise OSError("facts disk full")monkeypatch.setattr(ensure.Facts, "record_state", fail_publication)with pytest.raises(OSError, match="facts disk full"):- ensure.sync_venv(explicit=True, plugin_dirs=[plug], before_publish=before_publish)- assert order == ["before_publish", "record_state"] # config committed under the lock first+ ensure.sync_venv(explicit=True, selection={"home": str(plugin_home), "enabled": ["dep-plug"], "disabled": []})+ assert order == ["record_state"] # config committed under the lock firstassert (plugin_home / "config.yaml").read_bytes() == previous # undone atomicallyassert facts_path.read_bytes() == previous_factslatest = json.loads((rdir / "latest.json").read_text(encoding="utf-8-sig"))@@ -254,9 +258,8 @@ def test_noop_sync_writes_ok_receipt_rebuild_false(plugin_home, monkeypatch):rdir = plugin_home / "receipts"monkeypatch.setattr("pm.receipt._receipt_dir", lambda: rdir)monkeypatch.setattr(ensure, "_runtime_state_matches", lambda fact, stamp: True)- committed = []- ensure.sync_venv(extras=[], before_publish=lambda: committed.append(True))- assert committed == [True], "unchanged dependencies must still commit a plugin selection"+ ensure.sync_venv(extras=[], selection={"home": str(plugin_home), "enabled": ["plain"], "disabled": []})+ assert _enabled_set(plugin_home) == {"plain"}, "unchanged dependencies must still commit a plugin selection"latest = json.loads((rdir / "latest.json").read_text(encoding="utf-8-sig"))assert latest["outcome"] == "ok"assert latest["venv_rebuild"]["ok"] is Falsediff --git a/tests/hermes_cli/test_plugins_update_sync.py b/tests/hermes_cli/test_plugins_update_sync.pyindex e085f73dad0..a1a650fcb6d 100644--- a/tests/hermes_cli/test_plugins_update_sync.py+++ b/tests/hermes_cli/test_plugins_update_sync.py@@ -43,8 +43,8 @@ def test_disabled_update_does_not_change_dependencies_or_enablement(installed, mconfig = (home / "config.yaml").read_bytes()facts = paths.runtime_facts_path().read_bytes()state["sha"] = _version(repo, "2.0.0")- monkeypatch.setattr("pm.client.sync_venv",- lambda **kwargs: pytest.fail("disabled plugin changed the dependency selection"))+ monkeypatch.setattr("pm.packages.Venv.apply",+ lambda *args, **kwargs: pytest.fail("disabled plugin changed the dependency selection"))result = pc.dashboard_update_user_plugin("transactional")assert result["ok"], resultassert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip() == state["sha"]diff --git a/tests/hermes_cli/test_tools_config_post_setup.py b/tests/hermes_cli/test_tools_config_post_setup.pyindex ef19c8105e2..7ab2bd51c6e 100644--- a/tests/hermes_cli/test_tools_config_post_setup.py+++ b/tests/hermes_cli/test_tools_config_post_setup.py@@ -138,12 +138,16 @@ def test_langfuse_setup_uses_plugin_admission_and_preserves_config_on_refusal(def resolve_candidate(**kwargs):assert kwargs["explicit"] is True- kwargs["plugin_dirs"]()+ assert kwargs["selection"]["enabled"]if failure == "admission":raise pm.InstallError("venv", "candidate refused")# The real admission publisher must commit both lists, not a second UI writer.- publication = kwargs["before_publish"]()- publication.finish()+ from pm.publication import PluginSelection+ 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())+ finish_publication(repo_root())with (patch("pm.sync_venv", side_effect=pm.InstallError("venv", "SDK refused") if failure == "sdk" else None) as sdk,diff --git a/tests/pm/test_admission_members_locked.py b/tests/pm/test_admission_members_locked.pyindex d739d17d4d1..51ca7296da4 100644--- a/tests/pm/test_admission_members_locked.py+++ b/tests/pm/test_admission_members_locked.py@@ -35,13 +35,13 @@ def test_admission_reads_other_profiles_after_taking_lock(tmp_path, monkeypatch)def members(*args, **kwargs):return list(state["members"])- def apply(extras, *, plugin_dirs):+ def apply(extras, *, plugin_dirs, explicit=False):assert state["inside"]assert plugin_dirs == [sibling]return {}monkeypatch.setattr(runtime_state, "runtime_lock", after_competing_publication)- monkeypatch.setattr(admission, "candidate_member_dirs", members)+ monkeypatch.setattr("pm.publication.candidate_members", members)monkeypatch.setattr(ensure, "get_package", lambda _: SimpleNamespace(expected_stamp=lambda *args, **kwargs: "new", apply=apply,))diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.pyindex c4e7e8c0c3f..97f5b7caa74 100644--- a/tests/pm/test_pm_core.py+++ b/tests/pm/test_pm_core.py@@ -608,7 +608,7 @@ class FakeVenv(StatePackage):h.update(",".join(sorted(extras)).encode())return h.hexdigest()- def apply(self, extras):+ def apply(self, extras, *, explicit=False):self.applied.append(list(extras))from hermes_cli.runtime_paths import install_state_dirdiff --git a/tests/pm/test_runtime_context_home.py b/tests/pm/test_runtime_context_home.pyindex a79791ed103..54421a29856 100644--- a/tests/pm/test_runtime_context_home.py+++ b/tests/pm/test_runtime_context_home.py@@ -1,7 +1,7 @@"""Context-only homes use the same dependency state as their own process."""from hermes_cli import runtime_paths-from hermes_cli.plugins_admission import _config_commit+from pm.publication import PluginSelectionfrom hermes_cli.runtime_state import recover_publication, runtime_lockfrom hermes_constants import reset_hermes_home_override, set_hermes_home_overridefrom pm import paths, plugins_state@@ -27,7 +27,7 @@ def test_context_home_publication_recovers_from_its_own_process(tmp_path, monkeycontext_home / "plugins": ["old"],}with runtime_lock(project):- _config_commit({"new"}, set())+ PluginSelection({"home": str(config.parent), "enabled": ["new"], "disabled": []}).publish(project)assert config.read_bytes() != originalfinally:reset_hermes_home_override(token)diff --git a/tests/pm/test_runtime_journal_concurrent_edit.py b/tests/pm/test_runtime_journal_concurrent_edit.pyindex 1b92f2f841c..ca8c68ed1e9 100644--- a/tests/pm/test_runtime_journal_concurrent_edit.py+++ b/tests/pm/test_runtime_journal_concurrent_edit.py@@ -4,7 +4,7 @@ import pytestdef test_recovery_refuses_to_replace_newer_config(tmp_path, monkeypatch):from hermes_cli.runtime_state import recover_publication, runtime_lock- from hermes_cli.plugins_admission import _config_commit+ from pm.publication import PluginSelectionimport pm.paths as pathsfrom hermes_cli.runtime_paths import install_state_dir@@ -15,7 +15,7 @@ def test_recovery_refuses_to_replace_newer_config(tmp_path, monkeypatch):config = tmp_path / "config.yaml"config.write_bytes(b"plugins:\n enabled: [old]\n")with runtime_lock(repo):- _config_commit({"new"}, set())+ PluginSelection({"home": str(config.parent), "enabled": ["new"], "disabled": []}).publish(repo)config.write_bytes(config.read_bytes() + b"model: user-choice\n")changed = config.read_bytes()with pytest.raises(RuntimeError, match="config changed"):diff --git a/tests/pm/test_runtime_public.py b/tests/pm/test_runtime_public.pyindex 2cfa4b623af..d1883c308ef 100644--- a/tests/pm/test_runtime_public.py+++ b/tests/pm/test_runtime_public.py@@ -13,7 +13,7 @@ def test_public_mutations_delegate_but_environment_reads_stay_local(tmp_path, momonkeypatch.setattr(engine, "ensure", lambda *a, **kw: (_ for _ in ()).throw(AssertionError("inline install")))monkeypatch.setattr(engine, "sync_venv", lambda *a, **kw: (_ for _ in ()).throw(AssertionError("inline sync")))monkeypatch.setattr(client, "is_runtime", lambda: False, raising=False)- pm.sync_venv(["all"], explicit=True, plugin_dirs=lambda: (_ for _ in ()).throw(AssertionError("inline sync")))+ pm.sync_venv(["all"], explicit=True, plugin_dirs=[])pm.ensure("node", explicit=True)assert calls == ["sync_venv", "ensure"]assert pm.env_for is engine.env_fordiff --git a/tests/pm/test_runtime_recovery.py b/tests/pm/test_runtime_recovery.pyindex 7f534943b1d..6e396f9ff52 100644--- a/tests/pm/test_runtime_recovery.py+++ b/tests/pm/test_runtime_recovery.py@@ -22,13 +22,13 @@ def test_killed_publication_recovers_before_boot(tmp_path, commit_facts):code = '''import os, sysfrom pathlib import Path-from hermes_cli.plugins_admission import _config_commit+from pm.publication import PluginSelectionfrom hermes_cli.runtime_paths import runtime_facts_pathimport pm.paths as pathsfrom pm.lock import Factsrepo, config = map(Path, sys.argv[1:3])paths.repo_root = lambda: repo-change = _config_commit({"new"}, set())+PluginSelection({"home": str(config.parent), "enabled": ["new"], "disabled": []}).publish(repo)if sys.argv[3] == "True":Facts(runtime_facts_path(repo)).record_state("venv", "new", [])os._exit(17)diff --git a/tests/pm/test_runtime_transaction.py b/tests/pm/test_runtime_transaction.pyindex b9b36db3363..0585d785589 100644--- a/tests/pm/test_runtime_transaction.py+++ b/tests/pm/test_runtime_transaction.py@@ -49,7 +49,7 @@ def test_sync_commits_only_a_successful_candidate(tmp_path, monkeypatch, failuredef expected_stamp(self, extras):return "new"- def apply(self, extras):+ def apply(self, extras, *, explicit=False):if failure != "missing":assert selected_venv(root) == previousassert extras == ["base", "new-extra"]diff --git a/tests/pm/test_worker.py b/tests/pm/test_worker.pyindex fc674cd9bda..8e8b046ea35 100644--- a/tests/pm/test_worker.py+++ b/tests/pm/test_worker.py@@ -164,19 +164,12 @@ def test_currency_probe_preserves_union_and_candidate_inputs(client, tmp_path, mif route != "direct":engine = importlib.import_module("pm.ensure")monkeypatch.setattr(engine, "venv_is_current", lambda **kw: pytest.fail("probe ran in caller"))- callbacks = []-- def select():- callbacks.append("selected")- return members-def snapshot():return {path.relative_to(tmp_path): (path.read_bytes() if path.is_file() else None)for path in tmp_path.rglob("*")}before = snapshot()- assert client.venv_is_current(extras=["provider-extra"], plugin_dirs=select, **root_args)- assert callbacks == ["selected"]+ 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)@@ -185,7 +178,7 @@ def test_currency_probe_preserves_union_and_candidate_inputs(client, tmp_path, mmanifest.write_text('name: candidate\npython_dependencies: ["candidate-dep==2"]\n')changed = snapshot()- assert not client.venv_is_current(extras=["provider-extra"], plugin_dirs=select, **root_args)+ assert not client.venv_is_current(extras=["provider-extra"], plugin_dirs=members, **root_args)assert snapshot() == changedassert selected_venv(repo) == environment# Corruption must not be mistaken for a missing or current environment.@@ -207,34 +200,35 @@ def _assert_worker_holds_lock(repo):@pytest.mark.parametrize("explicit", [True, False])-def test_sync_callbacks_preserve_member_mapping_and_lock(client, tmp_path, monkeypatch, explicit):- identity, staged = tmp_path / "installed", tmp_path / "staged"- staged.mkdir()- (staged / "plugin.yaml").write_text("name: test\n")- members = {identity: staged}- repo = _current_environment(tmp_path, monkeypatch, members)- events = []-- def select():- _assert_worker_holds_lock(repo)- events.append("members")- return members-- class Publication:- def __call__(self):- pytest.fail("successful no-op publication was undone")-- def finish(self):- _assert_worker_holds_lock(repo)- events.append("finish")-- def before_publish():- _assert_worker_holds_lock(repo)- events.append("publish")- return Publication()-- client.sync_venv([], explicit=explicit, plugin_dirs=select, before_publish=before_publish)- assert events == ["members", "publish", "finish"]+def test_sync_discovers_profile_members_after_worker_acquires_lock(client, tmp_path, monkeypatch, isolated_python, explicit):+ from concurrent.futures import ThreadPoolExecutor+ import time+ from hermes_cli.runtime_state import runtime_lock+ from tests.pm.test_worker_publication import worker_toolchain++ sibling = tmp_path / "home/profiles/sibling/plugins/dependency"+ sibling.mkdir(parents=True)+ (sibling / "plugin.yaml").write_text("name: dependency\npython_dependencies: []\n")+ repo = _current_environment(tmp_path, monkeypatch, [sibling])+ ready = tmp_path / "waiting-for-lock"+ worker_toolchain(client, monkeypatch, isolated_python,+ "from contextlib import contextmanager\nimport hermes_cli.runtime_state as state\n"+ "original = state.runtime_lock\n@contextmanager\ndef lock(project):\n"+ f" Path({str(ready)!r}).touch()\n"+ " with original(project):\n yield\nstate.runtime_lock = lock\n")+ with ThreadPoolExecutor() as executor:+ with runtime_lock(repo):+ future = executor.submit(client.sync_venv, explicit=explicit, 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)+ assert ready.exists(), "worker never reached the install lock"+ assert not future.done(), "worker ignored the install lock"+ (sibling.parent.parent / "config.yaml").write_text("plugins:\n enabled: [dependency]\n")+ future.result(timeout=30)+ assert client.venv_is_current()@pytest.mark.parametrize("current", [True, False])@@ -262,19 +256,11 @@ def test_lazy_disabled_sync_does_not_bootstrap_tools(client, tmp_path, monkeypatmonkeypatch.setattr(_uv, "_toolchain", toolchain)monkeypatch.setattr("pm.runtime_stage.stage_runtime",lambda *a, **kw: pytest.fail("lazy-disabled sync prepared PM runtime"))- selections = []-- def select():- _assert_worker_holds_lock(repo)- selections.append("selected")- return []-with receipt.worker_context("lazy-disabled-sync"):with pytest.raises(InstallError, match="lazy installs are disabled") as caught:- client.sync_venv([], plugin_dirs=select)+ client.sync_venv([], plugin_dirs=[])result = receipt.last_for_update("lazy-disabled-sync", consume=True)assert caught.value.package == "pm-runtime"- assert selections == []assert result is not Noneassert result["outcome"] == "failed"receipts = list((tmp_path / "home" / "logs" / "update_receipts").glob("pm_*.json"))@@ -283,22 +269,17 @@ def test_lazy_disabled_sync_does_not_bootstrap_tools(client, tmp_path, monkeypatassert not paths.facts_path().exists()-def test_callback_exception_waits_for_failed_receipt_and_lock_release(client, tmp_path, monkeypatch):+def test_invalid_selection_waits_for_failed_receipt_and_lock_release(client, tmp_path, monkeypatch):import jsonfrom hermes_cli.runtime_paths import install_state_dirfrom hermes_cli.runtime_state import _lockrepo = _current_environment(tmp_path, monkeypatch, [])- error = LookupError("selection disappeared")-- def fail():- _assert_worker_holds_lock(repo)- raise error-- with pytest.raises(LookupError) as caught:- client.sync_venv([], explicit=True, plugin_dirs=fail)- assert caught.value is error- receipts = list((tmp_path / "home" / "logs" / "update_receipts").glob("pm_*.json"))+ 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": []})+ receipts = list((home / "logs" / "update_receipts").glob("pm_*.json"))assert len(receipts) == 1assert json.loads(receipts[0].read_text())["outcome"] == "failed"with (install_state_dir(repo) / ".install.lock").open("a+b") as lock:@@ -483,33 +464,28 @@ def test_resolution_conflict_survives_worker_and_receipt(client, tmp_path, monkeassert "engine stdout" in capfd.readouterr().err-def test_failed_finish_runs_undo_before_propagating_callback_exception(client, tmp_path, monkeypatch, isolated_python):+def test_failed_facts_write_restores_exact_config_before_reporting(client, tmp_path, monkeypatch, isolated_python):+ from tests.pm.test_worker_publication import worker_toolchain+ from hermes_cli.runtime_paths import install_state_dir+repo = _current_environment(tmp_path, monkeypatch, [])+ home = tmp_path / "home"+ config = home / "config.yaml"+ config.write_text("# preserve me\nplugins: {enabled: [old]}\n")+ previous = config.read_bytes()+ facts = (install_state_dir(repo) / "facts.json").read_bytes()(repo / "uv.lock").write_text("version = 2\n")- _patch_worker_apply(client, monkeypatch, isolated_python, "return {}")- events = []- error = LookupError("finish failed")-- class Publication:- def __call__(self):- _assert_worker_holds_lock(repo)- events.append("undo")- return object() # Return values of effect-only callbacks are ignored.-- def finish(self):- _assert_worker_holds_lock(repo)- events.append("finish")- raise error-- def publish():- _assert_worker_holds_lock(repo)- events.append("publish")- return Publication()-- with pytest.raises(LookupError) as caught:- client.sync_venv([], explicit=True, plugin_dirs=[], before_publish=publish)- assert caught.value is error- assert events == ["publish", "finish", "undo"]+ worker_toolchain(client, monkeypatch, isolated_python,+ "from pm.packages import Venv\nfrom pm.lock import Facts\n"+ "Venv.apply = lambda *args, **kwargs: {}\n"+ "def fail(*args, **kwargs):\n"+ 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": []})+ assert config.read_bytes() == previous+ assert (install_state_dir(repo) / "facts.json").read_bytes() == facts+ assert not (install_state_dir(repo) / "publication.json").exists()def test_invalid_arguments_keep_the_engine_exception_type(client):diff --git a/tests/pm/test_worker_publication.py b/tests/pm/test_worker_publication.pynew file mode 100644index 00000000000..fb05cda6551--- /dev/null+++ b/tests/pm/test_worker_publication.py@@ -0,0 +1,386 @@+"""Plugin publication runs in PM's independent worker, not application callbacks."""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++import pytest++from tests.pm.test_worker import client, isolated_python, _current_environment # noqa: F401+++def test_worker_publishes_selection_even_when_dependencies_are_current(client, tmp_path, monkeypatch):+ from hermes_cli.runtime_paths import install_state_dir+ from pm import receipt++ home = tmp_path / "home"+ home.mkdir()+ config = home / "config.yaml"+ config.write_text('# keep my comment\nmodel: "untouched"\nplugins:\n enabled: [old]\n')+ 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={+ "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"]}+ assert '# keep my comment' in config.read_text()+ assert 'model: "untouched"' in config.read_text()+ assert (install_state_dir(repo) / "facts.json").read_bytes() == facts+ assert not (install_state_dir(repo) / "publication.json").exists()+ assert result is not None+ assert result["outcome"] == "ok"+ assert result["venv_rebuild"]["ok"] is False+ assert json.loads((home / "logs/update_receipts/latest.json").read_text())["outcome"] == "ok"+++def worker_toolchain(client, monkeypatch, isolated_python, injection=""):+ uv = shutil.which("uv")+ assert uv+ worker = Path(client.__file__).with_name("worker.py")+ script = (+ "import runpy, sys, os; from pathlib import Path; "+ f"sys.path.insert(0, {str(worker.parent.parent)!r}); "+ "import pm._uv; "+ f"pm._uv._toolchain = lambda **kwargs: (Path({uv!r}), Path({sys.executable!r}));\n"+ + injection + f"\nrunpy.run_path({str(worker)!r}, run_name='__main__')"+ )+ monkeypatch.setattr(client, "runtime_command", lambda path, **kwargs: [str(isolated_python), "-I", "-B", "-c", script])++[email protected]("active", [False, True])[email protected]("missing", [False, True], ids=["existing", "missing"])+def test_staged_plugin_publication_uses_installed_identity_and_local_dependencies(+ client, tmp_path, monkeypatch, isolated_python, active, missing,+):+ from hermes_cli.runtime_paths import install_state_dir, selected_venv+ from pm.store import tree_digest+ from tests.pm.test_environment_build import _wheel+ from pm import paths++ worker_toolchain(client, monkeypatch, isolated_python)+ project = tmp_path / "project"+ project.mkdir()+ monkeypatch.setattr(paths, "repo_root", lambda: project)+ (project / "pyproject.toml").write_text(+ '[project]\nname="publication-core"\nversion="1"\nrequires-python=">=3.11"\n'+ '[tool.uv]\npackage=false\n')+ client.lock_project(project, offline=True, explicit=True)+ home = tmp_path / "home"+ target = home / "plugins" / "example"+ target.mkdir(parents=True)+ (home / "config.yaml").write_text('plugins:\n enabled: ' + ('[example]' if active else '[]') + '\n')+ (target / "plugin.yaml").write_text("name: example\n")+ (target / "code.py").write_text('old code')+ metadata = target.parent / ".install-metadata.json"+ metadata.write_text('{"example":{"revision":"old"}}\n')+ client.sync_venv(explicit=True)+ previous = selected_venv(project)+ if missing:+ shutil.rmtree(target)+ staged = tmp_path / "staged"+ staged.mkdir()+ wheel = _wheel(tmp_path, "publication_dep")+ (staged / "plugin.yaml").write_text('name: example\npython_dependencies: [' + json.dumps(f"publication-dep @ {wheel.as_uri()}") + ']\n')+ (staged / "code.py").write_text('new code')+ client.sync_venv(explicit=True, staged_plugin={+ "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"+ selected = selected_venv(project)+ assert (selected != previous) is active+ if active:+ python = selected / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ probe = subprocess.run([str(python), "-I", "-c", "import publication_dep; print(publication_dep.__version__)"],+ text=True, capture_output=True, timeout=30)+ assert probe.returncode == 0, probe.stderr+ assert probe.stdout.strip() == "1.0"+ facts = (install_state_dir(project) / "facts.json").read_bytes()+ client.sync_venv(explicit=True)+ assert (install_state_dir(project) / "facts.json").read_bytes() == facts+ assert not (install_state_dir(project) / "publication.json").exists()+ assert not list(target.parent.glob(".previous-*"))++[email protected]("mutation", ["sibling", "active"])+def test_selection_refuses_config_edits_during_preparation(client, tmp_path, monkeypatch, isolated_python, mutation):+ from hermes_cli.runtime_paths import install_state_dir+ home = tmp_path / "home"+ home.mkdir()+ config = home / "config.yaml"+ config.write_text("plugins:\n enabled: [old]\n")+ repo = _current_environment(tmp_path, monkeypatch, [])+ (repo / "uv.lock").write_text("version = 2\n")+ edited = config if mutation == "active" else home / "profiles/sibling/config.yaml"+ expected = "plugins:\n enabled: [concurrent]\n"+ facts = (install_state_dir(repo) / "facts.json").read_bytes()+ injection = (+ "from pm.packages import Venv\n"+ "def apply(self, *args, **kwargs):\n"+ f" p=Path({str(edited)!r}); p.parent.mkdir(parents=True, exist_ok=True); p.write_text({expected!r})\n"+ " return {}\n"+ "Venv.apply=apply\n"+ )+ 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": []})+ assert edited.read_text() == expected+ assert (install_state_dir(repo) / "facts.json").read_bytes() == facts+ assert not (install_state_dir(repo) / "publication.json").exists()++[email protected]("invalid", ["name: [", "manifest_version: 999", "requires_hermes: '>=999'", "name: other"])+def test_worker_rejects_unloadable_staged_plugin_without_app_dependencies(client, tmp_path, monkeypatch, invalid):+ from pm.store import tree_digest+ repo = _current_environment(tmp_path, monkeypatch, [])+ target = tmp_path / "home/plugins/example"+ target.mkdir(parents=True)+ (target / "plugin.yaml").write_text("name: example\n")+ staged = tmp_path / "staged"+ staged.mkdir()+ (staged / "plugin.yaml").write_text(invalid)+ previous = tree_digest(target)+ with pytest.raises(ValueError):+ client.sync_venv(explicit=True, staged_plugin={+ "target": str(target), "staged": str(staged), "target_digest": previous,+ "old_metadata": {}, "new_metadata": {"example": {"revision": "new"}},+ })+ assert tree_digest(target) == previous+ assert staged.exists()+++def test_additional_candidates_are_discovered_by_sync_and_passive_probe(client, tmp_path, monkeypatch):+ candidate = tmp_path / "candidate"+ candidate.mkdir()+ (candidate / "plugin.yaml").write_text("name: candidate\npython_dependencies: []\n")+ _current_environment(tmp_path, monkeypatch, [candidate])+ assert client.venv_is_current(extra_plugin_dirs=[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])+++def test_memory_setup_sends_candidate_paths_instead_of_discovery_callbacks(tmp_path, monkeypatch):+ from hermes_cli.memory_setup import memory_provider_dependency_inputs+ candidate = tmp_path / "provider"+ candidate.mkdir()+ (candidate / "plugin.yaml").write_text("name: provider\npython_dependencies: []\n")+ monkeypatch.setattr("plugins.memory.find_provider_dir", lambda name: candidate)+ _, inputs = memory_provider_dependency_inputs("provider")+ assert inputs == {"extras": [], "extra_plugin_dirs": [candidate]}++[email protected](("kind", "rebuild", "phase"), [+ (kind, rebuild, phase)+ for kind in ("selection", "tree") for rebuild in (False, True) for phase in ("journal", "payload", "commit")+] + [("tree", rebuild, phase) for rebuild in (False, True) for phase in ("backup", "tree")])+def test_worker_death_recovers_at_each_durable_publication_boundary(+ client, tmp_path, monkeypatch, isolated_python, kind, rebuild, phase,+):+ from hermes_cli.runtime_paths import install_state_dir, selected_venv+ from pm import paths+ from pm.package import InstallError+ from pm.store import tree_digest++ worker_toolchain(client, monkeypatch, isolated_python)+ project = tmp_path / "project"+ project.mkdir()+ monkeypatch.setattr(paths, "repo_root", lambda: project)+ core = '[project]\nname="death-proof"\nversion="1"\nrequires-python=">=3.11"\n[tool.uv]\npackage=false\n'+ (project / "pyproject.toml").write_text(core)+ client.lock_project(project, offline=True, explicit=True)+ home = tmp_path / "home"+ target = home / "plugins/example"+ target.mkdir(parents=True)+ (target / "plugin.yaml").write_text("name: example\n")+ (target / "code.py").write_text("old")+ config = home / "config.yaml"+ config.write_text("# exact bytes\nplugins:\n enabled: " + ("[example]" if kind == "tree" else "[]") + "\n")+ metadata = target.parent / ".install-metadata.json"+ metadata.write_text('{"example":{"revision":"old"}}\n')+ client.sync_venv(explicit=True)+ before_env = selected_venv(project)+ state = install_state_dir(project)+ facts = state / "facts.json"+ before = {p: p.read_bytes() for p in (config, metadata, facts)}+ before_tree = tree_digest(target)+ if kind == "selection":+ if rebuild:+ (target / "pyproject.toml").write_text(core.replace("death-proof", "example"))+ arguments = {"selection": {"home": str(home), "enabled": ["example"], "disabled": []}}+ payload = config+ else:+ staged = tmp_path / "staged"+ shutil.copytree(target, staged)+ (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"}}}}+ payload = metadata+ # Exit immediately after the real durable write, not a simulated publication.+ injection = (+ "import json\nimport pm.publication as publication\nimport hermes_cli.runtime_state as state\n"+ "original = state._atomic_bytes\n"+ "def write(path, data):\n original(path, data)\n"+ f" if {phase!r} == 'journal' and path.name == 'publication.json': os._exit(17)\n"+ f" if {phase!r} == 'payload' and path == Path({str(payload)!r}): os._exit(17)\n"+ f" if {phase!r} == 'commit' and path.name == 'publication.json' and json.loads(data).get('committed'): os._exit(17)\n"+ "publication._atomic_bytes = state._atomic_bytes = write\n"+ "original_replace = os.replace\ndef replace(source, target):\n original_replace(source, target)\n"+ f" if {phase!r} == 'backup' and Path(target).name.startswith('.previous-'): os._exit(17)\n"+ f" if {phase!r} == 'tree' and Path(target) == Path({str(target)!r}): os._exit(17)\n"+ "os.replace = replace\n"+ )+ if phase == "commit" and rebuild:+ injection += ("from pm.lock import Facts\nrecord = Facts.record_state\n"+ "def commit(self, *args, **kwargs):\n record(self, *args, **kwargs)\n os._exit(17)\n"+ "Facts.record_state = commit\n")+ worker_toolchain(client, monkeypatch, isolated_python, injection)+ with pytest.raises(InstallError, match="worker exited without a result"):+ client.sync_venv(explicit=True, **arguments)+ assert (state / "publication.json").exists()+ source = Path(client.__file__).resolve().parent.parent+ program = (f"import sys; sys.path.insert(0, {str(source)!r}); from pathlib import Path; "+ "from hermes_cli.runtime_state import runtime_lock, recover_publication; "+ f"project = Path({str(project)!r})\n"+ "with runtime_lock(project):\n recover_publication(project)\n recover_publication(project)\n")+ recovery = subprocess.run([sys.executable, "-I", "-S", "-c", program], capture_output=True, text=True,+ env=dict(os.environ), timeout=30)+ assert recovery.returncode == 0, recovery.stderr+ committed = phase == "commit"+ assert (selected_venv(project) != before_env) is (committed and rebuild)+ if not committed:+ assert {p: p.read_bytes() for p in before} == before+ if kind == "tree":+ assert (target / "code.py").read_text() == ("new" if committed else "old")+ if not committed:+ assert tree_digest(target) == before_tree+ else:+ from utils import fast_safe_load+ assert fast_safe_load(config.read_text())["plugins"]["enabled"] == (["example"] if committed else [])+ assert not (state / "publication.json").exists()+ assert not list(target.parent.glob(".previous-*"))++[email protected]("mutation", ["metadata", "target", "staged", "sibling-manifest"])+def test_staged_publication_refuses_concurrent_input_edits(client, tmp_path, monkeypatch, isolated_python, mutation):+ from hermes_cli.runtime_paths import install_state_dir+ from pm.store import tree_digest+ repo = _current_environment(tmp_path, monkeypatch, [])+ home = tmp_path / "home"+ target = home / "plugins/example"+ target.mkdir(parents=True)+ (target / "plugin.yaml").write_text("name: example\n")+ (target / "code.py").write_text("old code")+ sibling = target.parent / "sibling"+ sibling.mkdir()+ (sibling / "plugin.yaml").write_text("name: sibling\npython_dependencies: []\n")+ (home / "config.yaml").write_text("plugins:\n enabled: [example, sibling]\n")+ metadata = target.parent / ".install-metadata.json"+ metadata.write_text("{}\n")+ staged = tmp_path / "staged"+ staged.mkdir()+ (staged / "plugin.yaml").write_text("name: example\npython_dependencies: []\n")+ (staged / "code.py").write_text("new code")+ edited = {"metadata": metadata, "target": target / "code.py", "staged": staged / "code.py",+ "sibling-manifest": sibling / "plugin.yaml"}[mutation]+ proposed = "name: sibling\nversion: changed\npython_dependencies: []\n" if mutation == "sibling-manifest" else "concurrent edit"+ worker_toolchain(client, monkeypatch, isolated_python,+ "from pm.packages import Venv\n"+ "def apply(*args, **kwargs):\n"+ f" Path({str(edited)!r}).write_text({proposed!r})\n return {{}}\n"+ "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={+ "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+ assert not (install_state_dir(repo) / "publication.json").exists()+++def test_inactive_portable_publication_does_not_inspect_unrelated_dependency_manifests(client, tmp_path, monkeypatch):+ from pm.store import tree_digest+ _current_environment(tmp_path, monkeypatch, [])+ home = tmp_path / "home"+ target = home / "plugins/inactive"+ target.mkdir(parents=True)+ sibling = home / "plugins/sibling"+ sibling.mkdir()+ (sibling / "plugin.yaml").write_bytes(b"\xff")+ (home / "config.yaml").write_text("plugins:\n enabled: [sibling]\n")+ staged = tmp_path / "staged"+ 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={+ "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"+++def test_selection_preserves_yaml11_values_and_quotes_plugin_names(client, tmp_path, monkeypatch):+ import hermes_yaml+ _current_environment(tmp_path, monkeypatch, [])+ home = tmp_path / "home"+ 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": []})+ 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"}+ assert 'label: "on"' in config.read_text()+++def test_explicit_publication_keeps_its_intent_through_tool_acquisition(client, tmp_path, monkeypatch, isolated_python):+ from pm import paths+ from hermes_cli.runtime_paths import selected_venv+ project = tmp_path / "project"+ project.mkdir()+ monkeypatch.setattr(paths, "repo_root", lambda: project)+ (project / "pyproject.toml").write_text('[project]\nname="explicit-proof"\nversion="1"\nrequires-python=">=3.11"\n[tool.uv]\npackage=false\n')+ worker_toolchain(client, monkeypatch, isolated_python)+ client.lock_project(project, offline=True, explicit=True)+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")+ worker_toolchain(client, monkeypatch, isolated_python,+ "from pm.package import InstallError\ntools = pm._uv._toolchain\n"+ "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": []})+ assert (selected_venv(project) / "pyvenv.cfg").is_file()+++def test_stale_enablement_cannot_replace_a_newer_selection(client, tmp_path, monkeypatch):+ from hermes_cli import plugins_cmd as pc+ from hermes_cli.plugins_admission import AdmissionRefused+ from utils import fast_safe_load+ _current_environment(tmp_path, monkeypatch, [])+ config = tmp_path / "home/config.yaml"+ config.write_text("plugins: {enabled: [], disabled: []}\n")+ read = pc._get_enabled_set+ def concurrent_commit():+ stale = read()+ config.write_text("plugins: {enabled: [first], disabled: []}\n")+ return stale+ monkeypatch.setattr(pc, "_get_enabled_set", concurrent_commit)+ with pytest.raises(AdmissionRefused, match="changed"):+ pc._set_plugin_enabled("second", enable=True)+ assert fast_safe_load(config.read_bytes())["plugins"]["enabled"] == ["first"]diff --git a/tests/pm/test_workspace.py b/tests/pm/test_workspace.pyindex 527ef87b1a1..0806c031fa9 100644--- a/tests/pm/test_workspace.py+++ b/tests/pm/test_workspace.py@@ -207,7 +207,7 @@ def test_enabled_member_dirs_finds_enabled_dep_plugins(tmp_path, monkeypatch):# newest LAST) — discovery preserves the configured order.monkeypatch.setattr("pm.plugins_state.enabled_plugins_ordered",- lambda: {plugins: ["legacy-plug", "modern-plug", "plain-plug"]},+ lambda **kwargs: {plugins: ["legacy-plug", "modern-plug", "plain-plug"]},)found = ws.enabled_member_dirs()names = [p.name for p in found]@@ -223,7 +223,7 @@ def test_enabled_member_dirs_empty_when_nothing_enabled(tmp_path, monkeypatch):(member / "pyproject.toml").write_text("[project]\n", encoding="utf-8")monkeypatch.setattr(- "pm.plugins_state.enabled_plugins_ordered", lambda: {}+ "pm.plugins_state.enabled_plugins_ordered", lambda **kwargs: {})assert ws.enabled_member_dirs() == []diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.mdindex 5746706d007..0304d3efe60 100644--- a/website/docs/reference/package-management.md+++ b/website/docs/reference/package-management.md@@ -114,6 +114,13 @@ prepared environment inputs. The generated workspace and extended lock remainoutside shipped source. Repair copies the recorded workspace and lock, includingplugin build inputs, rather than resolving against edited live manifests.+Plugin enablement and staged code updates are submitted as data to the isolated+PM worker. Under the installation lock, it discovers the proposed dependency+union, validates the candidate, and publishes configuration or plugin files and+metadata with the environment selection. It rejects inputs changed during+preparation. A durable journal permits recovery before application imports,+including code-only updates that do not require a new environment.+A failed candidate does not replace the selected environment or silentlydisable other plugins. If preparation succeeds, a restart can still be requiredto activate the new environment in a running Hermes process.