The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge branch 'ethie/uv-build-logs' into ethie/pm-clean
ethernet7d73a180ae6e
diff --cc docs/source-update-completion.mdindex 00000000000,8aa34a437b8..87221130b79mode 000000,100644..100644--- a/docs/source-update-completion.md+++ b/docs/source-update-completion.md@@@ -1,0 -1,80 +1,84 @@@+ # Source update completion ownership++ ## Phase seam++ The command process owns admission, the update lock and output lifetime, pre-update+ inventory, all-profile snapshots, gateway pause, Git selection/stash/restore and+ syntax/HEAD guards, and the ZIP download/stage/dirty recheck/release graft/swap.+ It imports the completion transport before swapping code. Once the final tree is+ selected (including upstream merge), Git, already-current retry and ZIP all send+ one versioned JSON request to `update_completion.py` **from that tree**. No cached+ application module is evicted or reloaded in the command process.++ The request carries canonical source/home, desktop product selection, interactive+ and gateway mode, pre-update version, active and sibling snapshot identifiers,+ serialized runtime plan, open receipt identity/data and paused-Windows token. It+ contains data, never callables or pickles. stdin stays inherited for interactive+ configuration prompts; gateway mode retains its non-interactive behavior. Child+ output stays visible and is mirrored by the parent's update output stream.++ ## New-code owner++ A stdlib-only entrypoint starts using the available Python with `-I -S`, so no+ old site-packages or executable `.pth` files initialize. A private bytecode-cache+ prefix fences stale cache files before any new-checkout imports. Its explicit+ import path points at the new checkout. It calls the new PM interface to prepare the+ recorded dependency union, then starts the selected Python with the new activation+ environment. That interpreter also starts with site initialization disabled,+ then the runtime owner leases and activates its selected generation before any+ application imports. Only that interpreter imports application completion code. The same+ receipt/correlation identity crosses this preparation boundary (including PM+ results). Selected-Python completion owns launcher publication, builders, cache+ invalidation, all-profile configuration/state/skills maintenance, process scans,+ fleet restart, Windows resume, dashboard deduplication and verification.++ The existing per-kind restart and abort-recovery algorithms remain; transient+ supervisor/process failures are real even without mixed-generation imports. Only+ the purge/reload workaround and independent retry/ZIP tail compositions disappear.+ Gateway exit status is written before a restart can terminate the updater's cgroup,+ and is demoted on later failure. Verification publishes the final receipt.++ ## Parent lifecycle and failures++ The parent waits and propagates the child's exact nonzero result (a signal is+ mapped to shell-style 128+signal). A child cannot succeed by merely exiting zero:+ a terminal response with the matching receipt identity is required. The response+ returns the mutated Windows token so the parent's registered emergency resume does+ not repeat completed work. Normal parent completion performs no maintenance.++ The parent retains its original receipt until acknowledged child finalization;+ missing/failed child output leaves it available to the existing command-boundary+ failure finalizer. The stdlib bootstrap returns correlated PM failure data even+ when application imports are unavailable, and normalizes negative signal exits+ at each process boundary. POSIX completion owns a new session/process group;+ cancellation kills that group before releasing the lock (Windows uses the retained+ child's `taskkill /T` tree). The parent records the pending fleet obligation before+ starting the completion process, including when preparation cannot begin. The parent's emergency Windows resume remains a last-resort+ lifecycle obligation when the child cannot execute or is killed. A failed child+ never clears the pending fleet obligation. No automatic code rollback after+ maintenance has begun (SQLite snapshots remain file-loss recovery, not rollback).++ ## Historical surface++ All names frozen from the complete reachable shipped updater history stay-resolvable. Retired preparation and module-reload hooks become narrow nonzero-relaunch stops, not alternate completion paths or false successful receipts.++resolvable. Historical dependency hooks retain the stdlib-only takeover bridge:++the old parent waits, carries receipt/recovery state and never resumes a retired++installer. Newly retired preparation and module-reload hooks explicitly marked++incomplete stop nonzero and request `hermes update` again; they cannot manufacture++a missing completion request. Current Git/current/ZIP callers use only the++canonical completion transport, not the historical takeover entrypoint.+ Unfrozen branch-only retry compositions are deleted, not shimmed. ACP convenience+ publication uses the launcher owner's `expose_cli`; the historical ACP entry is+ only an adapter, never a second writer. The frozen set is never trimmed or replaced+ with tag-only coverage. New current-path imports are unioned with that history.++ ## Verification++ Use isolated homes, disposable Git repositories and fake dependency/build/service+ adapters only. Exercise an old process with cached incompatible modules across a+ real Git transition to new code, selected-Python execution, receipt identity and+ snapshot transfer, nonzero/abrupt child exit, lock release and Windows-token+ return. Focused existing tests cover dirty ZIP checks/grafts, snapshots, fleet+ reconciliation, supervisor timing and historical imports. Native service restart+ and Windows/macOS acceptance remain separate required lanes; no live user service+ or user state is touched by this implementation's test runs.diff --cc hermes_cli/_old_updater.pyindex ada8714c76b,d72c33965b7..2dbaa640b33--- a/hermes_cli/_old_updater.py+++ b/hermes_cli/_old_updater.py@@@ -1,145 -1,15 +1,154 @@@-"""Shims to stop the old updater doing work until relaunch."""+"""The newly imported escape hatch from an already-running historical updater.+This module must remain stdlib-only: the parent still has the old interpreter,+modules and native extensions. Only the child imports the updated application.+"""+from __future__ import annotations++import dataclasses+import json+import os+from pathlib import Path+import subprocessimport sys-from typing import NoReturn+import tempfile+from typing import Any, NoReturn+++_result: int | None = None+++def _historical_context() -> tuple[dict, list[dict], Any]:+ """Carry data already held by old frames, without importing their modules.++ Older callers did not pass a continuation object. Read only the historical+ updater's known local names; do not serialize frames or arbitrary globals.+ """+ names = ("had_desktop_app_before_update", "pre_update_snapshot_id",+ "pre_update_version", "gateway_mode", "assume_yes", "_pre_update_plan")+ found = {}+ resumes = []+ restart_update = None+ frame = sys._getframe(1)+ try:+ while frame is not None:+ # Capture hooks can be imported BEFORE the old updater has pulled.+ # A declared-but-unassigned version in its innermost known frame+ # proves early entry; a None value is still a post-capture value.+ if (restart_update is None+ and frame.f_globals.get("__name__") in ("hermes_cli.update_cmd", "hermes_cli.main")+ and frame.f_code.co_name in ("_cmd_update_impl", "cmd_update")+ and "pre_update_version" in frame.f_code.co_varnames):+ restart_update = "pre_update_version" not in frame.f_locals+ for name in names:+ if name not in found and name in frame.f_locals:+ found[name] = frame.f_locals[name]+ token = frame.f_locals.get("_windows_gateway_resume")+ if isinstance(token, dict) and not any(token is item for item in resumes):+ resumes.append(token)+ frame = frame.f_back+ finally:+ del frame+ receipt_module = sys.modules.get("hermes_cli.update_receipt")+ receipt_slot = vars(receipt_module).get("_current") if receipt_module else None+ get_current = getattr(receipt_slot, "get", None)+ current = get_current() if get_current is not None else receipt_slot+ receipt = getattr(current, "data", None)+ plan = found.get("_pre_update_plan")+ if dataclasses.is_dataclass(plan) and not isinstance(plan, type):+ plan = dataclasses.asdict(plan)+ elif not isinstance(plan, dict):+ plan = receipt.get("plan") if isinstance(receipt, dict) else None+ return {+ "restart_update": restart_update is True,+ "desktop": bool(found.get("had_desktop_app_before_update", False)),+ "pre_update_snapshot_id": found.get("pre_update_snapshot_id"),+ "pre_update_version": found.get("pre_update_version"),+ "gateway_mode": bool(found.get("gateway_mode", "--gateway" in sys.argv)),+ "assume_yes": bool(found.get("assume_yes", "--yes" in sys.argv)),+ "windows_resume": resumes[0] if resumes else None,+ "plan": plan,+ "receipt": receipt if isinstance(receipt, dict) else None,+ }, resumes, receipt_slot+++def _run_child(request: dict) -> tuple[int, dict]:+ """One JSON exchange; the old process never imports the updated graph."""+ root = Path(__file__).resolve().parents[1]+ home = os.environ.get("HERMES_HOME")+ constants = sys.modules.get("hermes_constants")+ override = vars(constants).get("_HERMES_HOME_OVERRIDE") if constants else None+ if override is not None:+ value = override.get()+ if isinstance(value, (str, Path)) and value:+ home = str(value)+ request.update(root=str(root), home=home, argv=list(sys.argv))+ env = {key: value for key, value in os.environ.items()+ if not key.startswith(("PYTHON", "UV_")) and key != "VIRTUAL_ENV"}+ if home:+ env["HERMES_HOME"] = home+ env.setdefault("HERMES_UPDATE_HANDOFF_PID", str(os.getpid()))+ with tempfile.TemporaryDirectory(prefix="hermes-update-takeover-") as directory:+ context = Path(directory) / "request.json"+ result = Path(directory) / "result.json"+ context.write_text(json.dumps(request), encoding="utf-8")+ child = subprocess.run(+ [sys.executable, "-I", "-S", "-B", "-X", "utf8", str(root / "hermes_cli/_update_takeover.py"),+ str(context), str(result)], cwd=root, env=env,+ )+ completed = json.loads(result.read_text(encoding="utf-8")) if result.is_file() else {}+ if not isinstance(completed, dict):+ raise ValueError("invalid update takeover acknowledgement")+ return child.returncode if child.returncode >= 0 else 1, completed- def stop_for_relaunch() -> NoReturn:+ def stop_for_relaunch(*, incomplete: bool = False) -> NoReturn:- """Do not return: old callers would fall back to pip or claim completion."""- command = "hermes update" if incomplete else "hermes"- print(- "You're updating from an older version of Hermes Agent. "- f"To complete this update, run `{command}` again.",- file=sys.stderr,- )- raise SystemExit(1 if incomplete else 0)+ """Finish in a fresh child, then exit rather than resume an old fallback.++ The historical name is retained. A finally/atexit path can call another+ shim while unwinding; it must receive the same result, not start again.+ """++ if incomplete:++ # A newly retired completion hook has no complete captured worklist.++ # It must not start another update or invent a successful receipt.++ print(++ "You're updating from an older version of Hermes Agent. "++ "To complete this update, run `hermes update` again.",++ file=sys.stderr,++ )++ raise SystemExit(1)+ global _result+ if _result is not None:+ raise SystemExit(_result)+ _result = 1+ try:+ request, resumes, receipt_slot = _historical_context()+ _result, completed = _run_child(request)+ if completed.get("resume_handled"):+ for token in resumes:+ token["resume_needed"] = False+ if completed.get("receipt_handled"):+ if hasattr(receipt_slot, "set"):+ receipt_slot.set(None)+ elif receipt_slot is not None:+ vars(sys.modules["hermes_cli.update_receipt"])["_current"] = None+ except (OSError, ValueError, TypeError) as exc:+ _result = 1+ print(f"Update takeover failed: {exc}", file=sys.stderr, flush=True)+ raise SystemExit(_result)+++def relaunch_stopped_serves(token: dict) -> None:+ """A historical atexit token is separate work, not another whole update."""+ if not token.get("pending"):+ return+ code = 1+ try:+ code, completed = _run_child({"stopped_serves": token})+ if completed.get("serves_handled") is True:+ token["pending"] = False+ except (OSError, ValueError, TypeError) as exc:+ print(f"Stopped serve recovery failed: {exc}", file=sys.stderr, flush=True)+ if code or token.get("pending"):+ print("Stopped serve recovery did not complete; restart the affected "+ "serve/dashboard backends manually.", file=sys.stderr, flush=True)diff --cc hermes_cli/main.pyindex 735e8725886,560c4714987..99610d0b511--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@@ -2052,6 -2052,6 +2052,8 @@@ def _detect_venv_python_processes(*, exreturn []++# Retired hooks must bypass update_cmd: its current dispatcher captures PM helpers++# before swapping code, but a historical caller may first resolve these afterward.# Frozen updater surface (PEP 562 ``__getattr__`` below): the frozen# ``hermes_cli/update_cmd*.py`` files resolve these names via ``_m().<name>``# on hermes_cli.main; importing update_cmd eagerly would cost every ``hermes``@@@ -2060,23 -2060,23 +2062,28 @@@_FROZEN_UPDATER_SURFACE: dict[str, tuple[str, ...]] = {"hermes_cli.update_cmd": ("_assess_parked_branch_switch",-- "_capture_active_lazy_features","_cold_start_windows_gateway_after_update", "_discard_stashed_changes","_filter_non_gateway_concurrent_instances", "_fleet_probe_expected_runtimes",-- "_get_origin_url", "_handoff_reapable_backend_pids", "_ledger_manual_serve_holders",-- "_ledger_reapable_backend_pids", "_leftover_pausable_gateway_pids", "_npm_lockfile_changed",-- "_orphaned_desktop_backend_pids", "_park_stashed_changes",++ "_get_origin_url", "_park_stashed_changes","_pause_windows_gateways_for_update", "_print_parked_branch_kept_notice",-- "_print_parked_branch_skip_warning", "_purge_stale_hermes_modules",-- "_refresh_active_lazy_features", "_refresh_active_memory_provider_dependencies",++ "_print_parked_branch_skip_warning","_refresh_bootstrap_cache_scripts", "_refresh_windows_gateway_launchers",-- "_relaunch_stopped_serves", "_reload_updated_runtime_modules","_restore_stashed_changes","_resume_windows_gateways_after_update", "_run_logged_subprocess", "_run_pre_update_backup",-- "_stash_local_changes_if_needed", "_stop_process_trees", "_sync_with_upstream_if_needed",++ "_stash_local_changes_if_needed", "_sync_with_upstream_if_needed","_venv_launcher_ancestors","_wait_for_windows_update_gateway_exit", "_warn_orphaned_update_autostashes",-- "_write_update_incomplete_marker",++ ),++ "hermes_cli.old_updater_deps": (++ "_capture_active_lazy_features", "_handoff_reapable_backend_pids",++ "_ledger_manual_serve_holders", "_ledger_reapable_backend_pids",++ "_leftover_pausable_gateway_pids", "_npm_lockfile_changed",++ "_orphaned_desktop_backend_pids", "_refresh_active_lazy_features",++ "_refresh_active_memory_provider_dependencies", "_relaunch_stopped_serves",++ "_stop_process_trees",++ ),++ "hermes_cli.update_cmd_maint": (++ "_purge_stale_hermes_modules", "_reload_updated_runtime_modules",),"hermes_cli.dashboard_procs": ("_detect_concurrent_hermes_instances", "_kill_stale_dashboard_processes",@@@ -2089,12 -2089,12 +2096,15 @@@ _FROZEN_ATTR_SOURCES: dict[str, str] =def __getattr__(name):"""Resolve the frozen updater surface on first read (see _FROZEN_UPDATER_SURFACE)."""-- module = _FROZEN_ATTR_SOURCES.get(name)-- if module is None:-- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")-- import importlib++ if name == "_write_update_incomplete_marker":++ from hermes_cli._old_updater import stop_for_relaunch as value++ else:++ module = _FROZEN_ATTR_SOURCES.get(name)++ if module is None:++ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")++ import importlib-- value = getattr(importlib.import_module(module), name)++ value = getattr(importlib.import_module(module), name)globals()[name] = value # cache: later accesses skip __getattr__return valuediff --cc hermes_cli/plugins_cmd.pyindex 4a3bb624439,3c057fbc732..841f36f4216--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@@ -991,16 -1005,27 +991,20 @@@ _get_disabled_set = functools.partial(__get_enabled_set = functools.partial(_config_name_set, "plugins", "enabled")-def _save_disabled_set(disabled: set) -> None:- _write_config_value("plugins", "disabled", sorted(disabled))--def _save_enabled_set(enabled: set) -> None:- _write_config_value("plugins", "enabled", sorted(enabled))+ """Frozen old-updater import: never resurrect a raw plugin-selection write."""+ from hermes_cli._old_updater import stop_for_relaunch++ stop_for_relaunch()+ 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(), expected_config=expected_config)--def _admit_and_save_plugin_sets(- enabled: set | Callable[[], tuple[set, set]], disabled: set | None,- *, 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@@@ -1050,23 -1074,14 +1053,22 @@@ def _discard_key_and_leaf(names: set, knames.discard(key.split("/")[-1])-def _set_plugin_enabled(name: str, *, enable: bool) -> None:- """Persist the proposed selection through the same dependency transaction."""+def _set_plugin_enabled(name: str, *, enable: bool, aliases=(), console=None) -> None:- """Apply the command's delta to the latest selection under PM's lock."""- def selection():- from pm.plugins_state import _read_home_config-- config = _read_home_config(get_hermes_home()) or {}- plugins = config.get("plugins") or {}- enabled = set(plugins.get("enabled") or ())- disabled = set(plugins.get("disabled") or ())- removed = disabled if enable else enabled- _discard_key_and_leaf(removed, name)- removed.difference_update(aliases)- (enabled if enable else disabled).add(name)- return enabled, disabled-- _admit_and_save_plugin_sets(selection, None, console=console,- action=f"{'Enable' if enable else 'Disable'} '{name}'")++ """Submit the command's delta with the version of the selection it read."""++ from pm.plugins_state import _read_home_config+++ 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, expected_config=expected_config)++ config = _read_home_config(get_hermes_home()) or {}++ plugins = config.get("plugins") or {}++ enabled = set(plugins.get("enabled") or ())++ disabled = set(plugins.get("disabled") or ())++ removed = disabled if enable else enabled++ _discard_key_and_leaf(removed, name)++ removed.difference_update(aliases)++ (enabled if enable else disabled).add(name)++ _admit_and_save_plugin_sets(enabled, disabled, console=console,++ action=f"{'Enable' if enable else 'Disable'} '{name}'",++ expected_config=expected_config)def _resolve_plugin_key(name: str) -> Optional[str]:diff --cc hermes_cli/plugins_transaction.pyindex b3b190e8ef7,c7dc6644f17..f26352581f2--- a/hermes_cli/plugins_transaction.py+++ b/hermes_cli/plugins_transaction.py@@@ -83,46 -13,15 +13,26 @@@ def recover_plugin_publication(projectdef publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata: dict,- *, require_consent: bool = False) -> None:- from hermes_cli import plugins_cmd- from hermes_cli.runtime_state import recover_publication, runtime_lock- from pm import paths- *, target_digest: str | None = None) -> None:++ *, target_digest: str | None = None, require_consent: bool = False) -> None:from pm.client import sync_venv- from pm.workspace import _is_member_candidate, enabled_plugin_dirs, member_sources-- project = paths.repo_root()+ from pm.store import tree_digest- 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)}++ if require_consent:++ from hermes_cli import plugins_cmd++ from pm.workspace import enabled_plugin_dirs+- # 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:- if require_consent:++ if target.resolve() in enabled_plugin_dirs(installing=target):+ consented, reason = plugins_cmd._install_plugin_python_deps(+ plugins_cmd._read_manifest_for_install(staged), staged, plugins_cmd._console())+ if not consented:+ raise plugins_cmd.PluginOperationError(+ f"Reinstall declined: {reason}. The installed plugin and active environment are unchanged.")- 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:diff --cc hermes_cli/update_cmd.pyindex 9b4910d69ea,b655d9ef631..0d1800ed961--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@@ -1268,15 -1267,11 +1267,11 @@@ def _handle_update_called_process_errorprint(f"⚠ {stage}: {e}")print("→ Falling back to ZIP download...")print()-- update_complete = _update_via_zip(++ _update_via_zip(args, had_desktop_app_before_update=had_desktop_app_before_update,- gateway_mode=gateway_mode, pre_update_snapshot_id=pre_update_snapshot_id,- pre_update_version=pre_update_version,- _pre_update_plan=_pre_update_plan, _windows_gateway_resume=_windows_gateway_resume,- target_sha=target_sha,+ target_sha=target_sha, completion_request=completion_request,**({"target_repository": target_repository} if target_repository else {}))- if not update_complete:- sys.exit(1)+else:print(f"✗ {stage}: {e}")_print_called_process_error_tail(e)@@@ -1442,18 -1404,13 +1404,14 @@@ def _cmd_update_impl(args, gateway_modeif use_zip_update:try:-- update_complete = _update_via_zip(++ _update_via_zip(args, had_desktop_app_before_update=had_desktop_app_before_update,- gateway_mode=gateway_mode, pre_update_snapshot_id=pre_update_snapshot_id,- pre_update_version=opts.pre_update_version,- _pre_update_plan=_pre_update_plan, _windows_gateway_resume=_windows_gateway_resume,- target_sha=release_sha,+ target_sha=release_sha, completion_request=completion_request,**({"target_repository": target_repository} if target_repository else {}))finally:- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ if _windows_gateway_resume and _windows_gateway_resume.get("resume_needed"):+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- if not update_complete:- sys.exit(1)+returntry:@@@ -1539,12 -1490,9 +1491,10 @@@try:_handle_update_called_process_error(e, args, gateway_mode, had_desktop_app_before_update, target_sha=release_sha,- target_repository=target_repository,- pre_update_snapshot_id=pre_update_snapshot_id, pre_update_version=opts.pre_update_version,- _pre_update_plan=_pre_update_plan, _windows_gateway_resume=_windows_gateway_resume)+ target_repository=target_repository, completion_request=completion_request)finally:- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ if _windows_gateway_resume and _windows_gateway_resume.get("resume_needed"):+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----diff --cc hermes_cli/venv_sync.pyindex cd312df88a0,d9ddb400f69..e36435321ad--- a/hermes_cli/venv_sync.py+++ b/hermes_cli/venv_sync.py@@@ -49,9 -49,25 +49,24 @@@ def _is_sealed(project_root: Path) -> breturn True+ def check_runtime(project_root: Path) -> str | None:+ """One passive startup verdict; callers only choose stderr or logging."""+ import pm+ from hermes_cli.steward import sealed_steward++ pm.adopt()- problems = pm.check()++ problems = pm.activate()+ if not problems:- pm.activate()+ return None+ steward = sealed_steward(Path(project_root))+ remedy = (f"this {steward}-managed install must rebuild the artifact to fix"+ if steward else "run `hermes pm install`")+ return f"install out of sync ({'; '.join(problems)}) — {remedy}"++def publish_launchers(project_root: Path) -> None:"""Refresh the durable source command before an old Python can be collected."""- from hermes_cli._launchers import ENTRY_POINTS, ensure_install_launchers, resolve_store_python+ from hermes_cli._launchers import ENTRY_POINTS, ensure_install_launchers, expose_cli, resolve_store_pythonfrom hermes_cli.steward import read_install_stamproot = Path(project_root)diff --cc pm/ensure.pyindex e57d55997d8,0166122fd94..303f55a3b8a--- a/pm/ensure.py+++ b/pm/ensure.py@@@ -21,40 -20,10 +21,38 @@@ from pm.store import Store, current_tarLOG = logging.getLogger(__name__)- # ``progress(stage, done, total, label)`` — stage is "download" | "unpack",- # label is the archive counter ("1/2") when a package has several. Slow- # lines sit in one stage for minutes, so the byte counters are what prove- # liveness to a UI.+ # ``progress(stage, done, total, label)`` reports download/unpack/verify;+ # multi-archive labels follow lockfile order.+def _prepare_artifacts(package, store, scratch, artifacts, version, target, *,+ progress=None, pause_event=None, download_progress=None):+ def tick(done, total, ranges):+ if progress is not None:+ active = next(reversed(ranges))+ index = next(i for i, artifact in enumerate(artifacts) if artifact["url"] == active)+ label = f"{index + 1}/{len(artifacts)}" if len(artifacts) > 1 else ""+ progress("download", done, total, label)+ if download_progress is not None:+ download_progress(done, total, ranges)++ staged = scratch / "tree"+ archives = store.fetch_many(artifacts, scratch, progress=tick, pause_event=pause_event)+ for index, archive in enumerate(archives):+ if pause_event is not None and pause_event.is_set():+ raise DownloadPaused("install paused")+ if progress is not None:+ label = f"{index + 1}/{len(artifacts)}" if len(artifacts) > 1 else ""+ progress("unpack", 0, 0, label)+ # unpack empties its destination; extract additional archives separately.+ destination = staged if index == 0 else scratch / f"extra-{index}"+ package.unpack(archive, destination, target)+ if index:+ merge_tree(destination, staged)+ package.stage(store, staged, version, target)+ return staged++def _lockfile() -> Lockfile:return Lockfile(paths.lockfile_path())@@@ -314,8 -278,16 +326,7 @@@ def _install)with store.scratch() as scratch:staged = scratch / "tree"- previous = facts.get(package.name)try:- def tick(done, total, ranges):- if progress is not None:- active = next(reversed(ranges))- index = next(i for i, artifact in enumerate(artifacts) if artifact["url"] == active)- label = f"{index + 1}/{len(artifacts)}" if len(artifacts) > 1 else ""- progress("download", done, total, label)- if download_progress is not None:- download_progress(done, total, ranges)-if copy_from is not None:source_facts, source_store = copy_fromsource = source_facts.get(package.name)@@@ -337,12 -322,27 +348,15 @@@reason = package.verify(staged, target)if reason:raise InstallError(package.name, f"staged entry failed verification: {reason}")+ if facts is None:+ (staged / ".pm-stage-pin.json").write_text(pin, encoding="utf-8")- if entry.exists() or entry.is_symlink():- entry.rename(previous_entry)- try:- store.publish(staged, entry_name)- reason = package.verify(entry, target)- if reason:- raise InstallError(package.name, f"published entry failed verification: {reason}")+ with _publish_entry(package, store, staged, entry, previous_entry, target):- facts.record(- package.name, version, entry_name, package.env(entry, target), store.root,- target=target, artifacts=[a["sha256"] for a in artifacts],- digest=tree_digest(entry),- )+ if facts is not None:+ facts.record(+ package.name, version, entry_name, package.env(entry, target), store.root,+ target=target, artifacts=[a["sha256"] for a in artifacts],+ digest=tree_digest(entry),+ )- except BaseException:- if previous_entry.exists():- _restore_previous_entry(store, entry, previous_entry)- raise- if previous_entry.exists():- _remove_entry(store, previous_entry.name)_remove_downloads(store, artifacts)except (InstallError, DownloadPaused):raisediff --cc pm/publication.pyindex 00000000000,9548ba90dd9..7fc46a19ef2mode 000000,100644..100644--- a/pm/publication.py+++ b/pm/publication.py@@@ -1,0 -1,170 +1,148 @@@+ """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++ from pm.plugin_declarations import read_python_declaration, manifest_version_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)++ manifest = read_python_declaration(source).manifest++ reason = manifest_version_error(manifest, source.name)+ 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")++ raise ValueError(reason)+ 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 --cc pm/workspace.pyindex 64ef95b7073,2f6206d1ffe..6b2fad5e97e--- a/pm/workspace.py+++ b/pm/workspace.py@@@ -18,9 -18,7 +18,8 @@@ if TYPE_CHECKINGfrom pm import pathsfrom pm.package import InstallError+from pm.plugin_declarations import read_python_declaration, manifest_version_error- WORKSPACE_DIRNAME = ".pm-workspace"_MEMBER_EXCLUDE = frozenset({".git", ".venv", "venv", "node_modules", "__pycache__"})@@@ -182,38 -154,32 +155,10 @@@ def _generate_pyproject(plugin_dirs: lidef _is_member_candidate(plugin_dir: Path) -> bool:- """A plugin dir is a workspace-member candidate when it declares python- deps: a pyproject.toml (modern), or legacy pip_dependencies/- python_dependencies in plugin.yaml (the bridge materializes those)."""- import stat-- for name in ("pyproject.toml", "plugin.yaml"):- path = plugin_dir / name- try:- mode = path.stat().st_mode- except FileNotFoundError:- continue- except OSError as exc:- raise ValueError(f"could not inspect plugin metadata: {path}") from exc- if not stat.S_ISREG(mode):- continue- if name == "pyproject.toml":- return True- try:- text = path.read_text(encoding="utf-8-sig")- except (OSError, UnicodeError) as exc:- raise ValueError(f"could not read plugin metadata: {path}") from exc- return "pip_dependencies" in text or "python_dependencies" in text- return False+ return read_python_declaration(plugin_dir).is_member- 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@@@ -236,31 -203,41 +182,28 @@@def enabled_member_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:"""Keep every selected member or refuse an incompatible selection."""- from hermes_cli.plugins_cmd import _check_manifest_version, _read_manifest_for_install-selected = enabled_plugin_dirs(proposed_home=proposed_home, enabled=enabled, disabled=disabled)+ members = []for path in selected:- _check_manifest_version(_read_manifest_for_install(path), path.name)- return [path for path in selected if _is_member_candidate(path)]---def _legacy_requirements(plugin_dir: Path) -> list[str]:- from utils import fast_safe_load-- manifest = plugin_dir / "plugin.yaml"- if not manifest.is_file():- return []- data = fast_safe_load(manifest.read_text(encoding="utf-8-sig"))- if not isinstance(data, dict):- raise InstallError("venv", f"invalid plugin manifest: {manifest}")- specs = []- for key in ("pip_dependencies", "python_dependencies"):- values = data.get(key, [])- if not isinstance(values, list) or any(not isinstance(v, str) for v in values):- raise InstallError("venv", f"invalid {key}: {manifest}")- specs.extend(values)- return list(dict.fromkeys(specs))+ declaration = read_python_declaration(path)+ reason = manifest_version_error(declaration.manifest, path.name)+ if reason:+ raise InstallError("venv", reason)+ if declaration.is_member:+ members.append(path)+ return members- def _workspace_member(plugin_dir: Path, root: Path, *, identity: Path | None = None) -> Path:+ def _workspace_member(plugin_dir: Path, root: Path, *, identity: Path) -> Path:"""Keep workspace members with their generation, not a temporary install clone."""import json- import shutilimport tomllib- key = hashlib.sha256(str((identity or plugin_dir).resolve()).encode()).hexdigest()[:16]+ key = hashlib.sha256(str(identity.resolve()).encode()).hexdigest()[:16]- pyproject = plugin_dir / "pyproject.toml"- if pyproject.is_file() and "GENERATED by pm" not in pyproject.read_text(encoding="utf-8-sig"):+ declaration = read_python_declaration(plugin_dir)+ pyproject = declaration.pyproject+ if pyproject is not None:member = root / "plugin-sources" / key- if member.exists():- shutil.rmtree(member)shutil.copytree(plugin_dir, member, symlinks=True,ignore=_member_ignored)document = tomllib.loads(pyproject.read_text(encoding="utf-8-sig"))@@@ -282,9 -259,9 +225,9 @@@(member / "pyproject.toml").write_text(tomli_w.dumps(document), encoding="utf-8")return member- specs = _legacy_requirements(plugin_dir)+ specs = declaration.requirementsmember = root / "plugin-deps" / key- member.mkdir(parents=True, exist_ok=True)+ member.mkdir(parents=True)(member / "pyproject.toml").write_text(f'[project]\nname = "hermes-plugin-{key}"\nversion = "0.0.0"\n''requires-python = ">=3.11"\n'diff --cc tests/hermes_cli/test_boot_convergence.pyindex 00000000000,c1c85f17afe..1dcb16069abmode 000000,100644..100644--- a/tests/hermes_cli/test_boot_convergence.py+++ b/tests/hermes_cli/test_boot_convergence.py@@@ -1,0 -1,191 +1,192 @@@+ """Real startup paths share one passive PM verdict, including fast dispatch."""++import importlib+ import json+ import sys+ from pathlib import Path++ import pytest+++ @pytest.mark.parametrize("surface", ["serve", "version", "gateway"])+ def test_each_start_checks_pm_once_before_dispatch(surface, tmp_path, monkeypatch, capsys, caplog):+ import pm+ from hermes_cli import boot_bootstrap++ home = tmp_path / "home"+ home.mkdir()+ runtime = tmp_path / "tools"+ runtime.mkdir()+ # A recorded but empty store is genuinely drifted against the shipped lock.+ (runtime / "facts.json").write_text(json.dumps({"schema": 1, "packages": {}}))+ root = tmp_path / "payload"+ root.mkdir()+ (root / "install-stamp.json").write_text(json.dumps({+ "commit": "abcdef012345", "payload": "bundled", "updateMechanism": "electron-updater",+ }))+ monkeypatch.setattr(Path, "home", lambda: home)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(runtime))+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(root))+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")+ monkeypatch.delenv("HERMES_DISABLE_FAST_SERVE_LAUNCH", raising=False)+ checked = []+ real_check = pm.check++ def check():+ problems = real_check()+ assert problems+ checked.append(problems)+ return problems++ def no_install(*args, **kwargs):+ pytest.fail("startup must not install or sync")+- monkeypatch.setattr(pm, "check", check)++ monkeypatch.setattr(importlib.import_module("pm.ensure"), "check", check)+ monkeypatch.setattr(pm, "ensure", no_install)+ monkeypatch.setattr(pm, "sync_venv", no_install)+ dispatched = []+ if surface == "gateway":+ import gateway.run as gr++ async def start(*args, **kwargs):+ dispatched.append(len(checked))+ return True++ monkeypatch.setattr(gr, "start_gateway", start)+ monkeypatch.setattr(gr, "_exit_after_graceful_shutdown", lambda code: None)+ monkeypatch.setattr(sys, "argv", ["gateway"])+ run = gr.main+ else:+ from hermes_cli import main++ monkeypatch.setattr(main, "cmd_dashboard", lambda args: dispatched.append(len(checked)))+ monkeypatch.setattr(main, "cmd_version", lambda args: dispatched.append(len(checked)))+ monkeypatch.setattr(sys, "argv", ["hermes", "serve" if surface == "serve" else "--version"])+ run = main.main+ for _ in range(2):+ checked.clear()+ capsys.readouterr()+ caplog.clear()+ run()+ assert len(checked) == 1+ assert dispatched[-1] == 1+ output = capsys.readouterr().err+ warnings = [r for r in caplog.records if "install out of sync" in r.message]+ if surface == "gateway":+ assert len(warnings) == 1+ else:+ assert output.count("install out of sync") == 1+ assert "rebuild the artifact" in (warnings[0].message if surface == "gateway" else output)+ assert not list(home.rglob("machine.json"))+ assert boot_bootstrap.current_install_identity(root) == "abcdef012345"+++ @pytest.mark.parametrize("sibling_profile", [False, True])+ def test_concurrent_boots_bound_real_home_migration(tmp_path, monkeypatch, sibling_profile):+ import os+ import subprocess+ import sqlite3+ import time+ from hermes_cli.config import DEFAULT_CONFIG++ root = tmp_path / "payload"+ root.mkdir()+ (root / "install-stamp.json").write_text(json.dumps({+ "commit": "abcdef012345", "updateMechanism": "external", "distribution": "nix",+ }))+ home = tmp_path / "home"+ other = home / "profiles/coder" if sibling_profile else home+ for directory in {home, other}:+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "config.yaml").write_text(f"_config_version: {DEFAULT_CONFIG['_config_version'] - 1}\n")+ (directory / ".env").write_text("EXAMPLE_KEY=test\n")+ with sqlite3.connect(directory / "state.db") as db:+ db.execute("CREATE TABLE retained (value)")+ db.execute("INSERT INTO retained VALUES ('before')")+ entered = tmp_path / "entered"+ release = tmp_path / "release"+ script = tmp_path / "boot.py"+ script.write_text('''import json, sys, time+ from pathlib import Path+ from hermes_cli import boot_bootstrap, post_update+ root, entered, release = map(Path, sys.argv[1:4])+ def migrate():+ if sys.argv[4] == 'hold':+ entered.touch()+ deadline = time.monotonic() + 30+ while not release.exists():+ if time.monotonic() > deadline: raise RuntimeError('release timeout')+ time.sleep(0.02)+ return post_update.step_migrate_config()+ post_update.BOOT_HOME_STEPS = (('migrate', migrate), ('db', post_update.step_state_db_guard))+ print(json.dumps(boot_bootstrap.run_boot_bootstrap(root)))+ ''')+ env = dict(os.environ, HOME=str(tmp_path), HERMES_HOME=str(home),+ HERMES_RUNTIME_DIR=str(tmp_path / "tools"),+ PYTHONPATH=str(Path(__file__).resolve().parents[2]))+ command = [sys.executable, str(script), str(root), str(entered), str(release)]+ first = subprocess.Popen([*command, "hold"], env=env, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, text=True)+ try:+ deadline = time.monotonic() + 30+ while not entered.exists():+ assert first.poll() is None+ assert time.monotonic() < deadline+ time.sleep(0.02)+ second = subprocess.run([*command, "go"], env=dict(env, HERMES_HOME=str(other)),+ capture_output=True, text=True, timeout=30)+ assert second.returncode == 0, second.stderr+ result = json.loads(second.stdout.splitlines()[-1])+ if sibling_profile:+ assert result["home"]["migrate"]["ok"]+ assert result["home"]["db"]["ok"]+ else:+ assert result == {"home": "lost-race"}+ release.touch()+ stdout, stderr = first.communicate(timeout=30)+ assert first.returncode == 0, stderr+ assert json.loads(stdout.splitlines()[-1])["home"]["db"]["ok"]+ again = subprocess.run([*command, "go"], env=env, capture_output=True, text=True, timeout=30)+ assert json.loads(again.stdout.splitlines()[-1]) == {"home": "skipped"}+ for directory in {home, other}:+ assert len(list(directory.glob("config.yaml.bak-*"))) == 1+ with sqlite3.connect(directory / "state.db") as db:+ assert db.execute("SELECT value FROM retained").fetchall() == [("before",)]+ finally:+ release.touch()+ if first.poll() is None:+ first.kill()+ first.communicate(timeout=30)+++ def test_failed_migration_is_restored_and_not_retried(tmp_path, monkeypatch):+ from hermes_cli import boot_bootstrap, config, post_update++ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ root = tmp_path / "payload"+ root.mkdir()+ (root / "install-stamp.json").write_text(json.dumps({+ "commit": "abcdef012345", "updateMechanism": "external", "distribution": "nix",+ }))+ config_file = home / "config.yaml"+ config_file.write_text(f"_config_version: {config.DEFAULT_CONFIG['_config_version'] - 1}\n")+ env_file = home / ".env"+ env_file.write_text("EXAMPLE_KEY=keep\n")+ original = {p: p.read_bytes() for p in (config_file, env_file)}+ calls = []++ def interrupted(**kwargs):+ calls.append(True)+ config_file.write_text("half written")+ env_file.write_text("half written")+ raise RuntimeError("interrupted migration")++ monkeypatch.setattr(config, "migrate_config", interrupted)+ monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", (("migrate", post_update.step_migrate_config),))+ assert not boot_bootstrap.run_boot_bootstrap(root)["home"]["migrate"]["ok"]+ assert {p: p.read_bytes() for p in original} == original+ assert boot_bootstrap.run_boot_bootstrap(root) == {"home": "skipped"}+ assert calls == [True]diff --cc tests/hermes_cli/test_plugin_worker_lifecycle.pyindex 5324dec75a6,00000000000..e25a6f77dadmode 100644,000000..100644--- a/tests/hermes_cli/test_plugin_worker_lifecycle.py+++ b/tests/hermes_cli/test_plugin_worker_lifecycle.py@@@ -1,268 -1,0 +1,279 @@@+"""Command → real PM worker → offline wheels → persisted state → fresh imports."""+from __future__ import annotations++import pytest++from tests.hermes_cli.plugin_worker_support import (+ plugin_world as plugin_world,+ isolated_python as isolated_python,+)++[email protected]("surface,suffix", [+ ("pyproject", "yaml"), ("python_dependencies", "yaml"), ("pip_dependencies", "yaml"),+ ("python_dependencies", "yml"), ("pip_dependencies", "yml"),+])+def test_declaration_consent_admission_and_resync(plugin_world, monkeypatch, capsys, surface, suffix):+ from hermes_cli import plugins_cmd+ from pm import client, receipt++ world = plugin_world+ origin, revision = world.origin(surface=surface, suffix=suffix)+ before = (world.home / "config.yaml").read_bytes()+ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: False)+ world.command("install", identifier=origin.as_uri(), ref=revision, enable=True, allow_removed=True)+ assert world.enabled() == [], "non-interactive Python admission bypassed consent"+ assert (world.home / "config.yaml").read_bytes() == before+ assert "skipped (non-interactive)" in " ".join(capsys.readouterr().out.split())++ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True)+ monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True)+ monkeypatch.setattr("builtins.input", lambda prompt: "no")+ world.command("install", identifier=origin.as_uri(), force=True, enable=True, allow_removed=True)+ assert world.enabled() == []+ assert (world.home / "config.yaml").read_bytes() == before+ assert "declined" in capsys.readouterr().out++ monkeypatch.setattr("builtins.input", lambda prompt: "yes")+ world.command("install", identifier=origin.as_uri(), force=True, enable=True, allow_removed=True)+ assert world.enabled() == ["plugin-worker-proof"]+ assert receipt.latest()["outcome"] == "ok"+ world.imports()+ selected = world.selected()+ client.sync_venv(explicit=True)+ assert world.selected() == selected+ world.imports()++ declaration = world.home / "plugins/plugin-worker-proof" / ("pyproject.toml" if surface == "pyproject" else f"plugin.{suffix}")+ declaration.write_text(declaration.read_text(encoding="utf-8").replace("==1.0", "==2.0"), encoding="utf-8")+ client.sync_venv(explicit=True)+ assert world.selected() != selected, "changed declaration was not stamped"+ # Code has not changed: inspect the new dependency independently.+ import os+ import subprocess+ python = world.selected() / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ result = subprocess.run([str(python), "-I", "-c", "import plugin_proof_dep; assert plugin_proof_dep.__version__ == '2.0'"],+ capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+++def test_active_force_reinstall_decline_preserves_entire_selection(plugin_world, monkeypatch):+ from hermes_cli import plugins_cmd+ from pm import paths+ from tests.hermes_cli.plugin_worker_support import git, version++ world = plugin_world+ origin, first = world.origin()+ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True)+ monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True)+ answers = []+ monkeypatch.setattr("builtins.input", lambda prompt: answers.append(prompt) or "yes")+ world.command("install", identifier=origin.as_uri(), ref=first, enable=True, allow_removed=True)+ world.imports()+ target = world.home / "plugins/plugin-worker-proof"+ watched = [world.home / "config.yaml", target / "__init__.py", target / "plugin.yaml",+ target.parent / ".install-metadata.json", paths.runtime_facts_path()]+ before = {path: path.read_bytes() for path in watched}+ selected = world.selected()+ second = version(origin, pin="2.0")+ monkeypatch.setattr("builtins.input", lambda prompt: answers.append(prompt) or "no")+ try:+ world.command("install", identifier=origin.as_uri(), ref=second, force=True, enable=True, allow_removed=True)+ except SystemExit as exc:+ assert exc.code == 1+ assert {path: path.read_bytes() for path in watched} == before+ assert git(target, "rev-parse", "HEAD") == first+ assert world.selected() == selected+ world.imports()++ answers.clear()+ monkeypatch.setattr("builtins.input", lambda prompt: answers.append(prompt) or "yes")+ world.command("install", identifier=origin.as_uri(), ref=second, force=True, enable=True, allow_removed=True)+ assert len(answers) == 1, "active replacement asked for the same consent twice"+ assert git(target, "rev-parse", "HEAD") == second+ assert world.selected() != selected+ world.imports(pin="2.0")++[email protected]("flag", ["no_enable", "enable"])+def test_active_reinstall_does_not_overwrite_a_later_disable(plugin_world, monkeypatch, flag):+ from hermes_cli import plugins_cmd+ from pm import paths+ from tests.hermes_cli.plugin_worker_support import version++ world = plugin_world+ origin, first = world.origin()+ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True)+ monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True)+ monkeypatch.setattr("builtins.input", lambda prompt: "yes")+ world.command("install", identifier=origin.as_uri(), ref=first, enable=True, allow_removed=True)+ second = version(origin, pin="2.0")+ watched = [world.home / "config.yaml", paths.runtime_facts_path()]+ acknowledged = {}+ def disable_after_publication(*args):+ world.command("disable", name="plugin-worker-proof")+ acknowledged.update({path: path.read_bytes() for path in watched})+ monkeypatch.setattr(plugins_cmd, "_display_after_install", disable_after_publication)+ world.command("install", identifier=origin.as_uri(), ref=second, force=True, allow_removed=True, **{flag: True})+ assert acknowledged+ assert {path: path.read_bytes() for path in watched} == acknowledged+ assert world.enabled() == []+++def test_malformed_portable_member_cannot_join_a_new_generation(plugin_world, monkeypatch):+ import json+ from hermes_cli import plugins_cmd+ from hermes_cli.agent_plugins import PLUGIN_SCHEMA_V1+ from pm import client, paths+ from tests.hermes_cli.plugin_worker_support import git++ world = plugin_world+ origin, _ = world.origin(surface="pyproject")+ (origin / "plugin.yaml").unlink()+ (origin / "plugin.json").write_text(json.dumps({"$schema": PLUGIN_SCHEMA_V1, "name": "plugin-worker-proof"}), encoding="utf-8")+ git(origin, "add", "--all")+ git(origin, "commit", "-qm", "portable declaration")+ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True)+ monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True)+ monkeypatch.setattr("builtins.input", lambda prompt: "yes")+ world.command("install", identifier=origin.as_uri(), enable=True, allow_removed=True)+ world.imports()+ watched = [world.home / "config.yaml", paths.runtime_facts_path()]+ before = {path: path.read_bytes() for path in watched}+ (world.home / "plugins/plugin-worker-proof/plugin.json").write_text("{malformed", encoding="utf-8")+ with pytest.raises((ValueError, RuntimeError), match="plugin.json"):+ client.sync_venv(explicit=True)+ assert {path: path.read_bytes() for path in watched} == before+++def test_pack_admits_compatible_members_and_reports_conflict(plugin_world, monkeypatch, capsys):+ import json+ import hermes_yaml as yaml+ from hermes_cli import plugins_cmd+ from tests.hermes_cli.plugin_worker_support import git, version++ world = plugin_world+ incumbent, first = world.origin()+ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True)+ monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True)+ monkeypatch.setattr("builtins.input", lambda prompt: "yes")+ world.command("install", identifier=incumbent.as_uri(), ref=first, enable=True, allow_removed=True)+ world.imports()+ good, good_sha = world.origin(name="pack-good", capabilities=["tools.override"])+ bad, bad_sha = world.origin(name="pack-conflict", pin="2.0")+ last, last_sha = world.origin(name="pack-last", capabilities=["tools.override"])+ # Moving HEAD cannot move a pack's pinned selection.+ version(good, name="pack-good", pin="2.0")+ pack = world.root / "pack.yaml"+ pack.write_text(yaml.safe_dump({"name": "proof-pack", "plugins": [+ {"repo": repo.as_uri(), "ref": sha} for repo, sha in [(good, good_sha), (bad, bad_sha), (last, last_sha)]+ ], "config": {"pack-good": {"voice": "fixture"}}}), encoding="utf-8")+ answers = iter(["yes", "yes", "no"])+ monkeypatch.setattr("rich.console.Console.input", lambda self, prompt: next(answers))+ with pytest.raises(SystemExit) as exc:+ world.command("pack", pack_action="install", source=str(pack))+ assert exc.value.code == 1+ from rich.text import Text+ assert "2 installed, 1 failed" in " ".join(Text.from_ansi(capsys.readouterr().out).plain.split())+ assert set(world.enabled()) == {"plugin-worker-proof", "pack-good", "pack-last"}+ for name, sha in [("pack-good", good_sha), ("pack-conflict", bad_sha), ("pack-last", last_sha)]:+ assert git(world.home / "plugins" / name, "rev-parse", "HEAD") == sha+ for name in ("plugin-worker-proof", "pack-good", "pack-last"):+ world.imports(name)+ config = yaml.safe_load((world.home / "config.yaml").read_text(encoding="utf-8"))+ entries = config["plugins"]["entries"]+ assert entries["pack-good"]["voice"] == "fixture"+ assert "tools.override" in entries["pack-good"]["granted_capabilities"]+ assert "tools.override" not in entries.get("pack-last", {}).get("granted_capabilities", [])+ receipts = [json.loads(path.read_text()) for path in (world.home / "logs/update_receipts").glob("pm_*.json")]+ assert any(row["outcome"] == "failed" and "plugin-proof-dep" in json.dumps(row) for row in receipts)++[email protected]("sibling_profiles", [False, True], ids=["same-profile", "sibling-profiles"])+def test_concurrent_commands_keep_acknowledged_enables(plugin_world, sibling_profiles):+ import queue+ import threading+ import os+ from pathlib import Path+ import shutil+ import subprocess+ import sys+ import hermes_yaml as yaml+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override+ from tests.hermes_cli.plugin_worker_support import worker_command++ world = plugin_world+ homes = [world.home, world.home]+ if sibling_profiles:+ homes = [world.home / "profiles" / name for name in ("left", "right")]+ for home in homes:+ home.mkdir(parents=True)+ (home / "config.yaml").write_text("plugins:\n enabled: []\n disabled: []\n", encoding="utf-8")+ for name, home in zip(("race-left", "race-right"), homes):+ origin, revision = world.origin(name=name, dependency="plugin-proof-dep" if name == "race-left" else "plugin-proof-other")+ token = set_hermes_home_override(home)+ try:+ world.command("install", identifier=origin.as_uri(), ref=revision, no_enable=True, allow_removed=True)+ finally:+ reset_hermes_home_override(token)+ untouched = (world.home / "config.yaml").read_bytes()+ checkout = Path(__file__).resolve().parents[2]+ command = worker_command(checkout / "pm/worker.py", shutil.which("uv"), sys.executable,+ runtime_python=world.runtime_python)+ processes = []+ try:+ for name, home in zip(("race-left", "race-right"), homes):+ script = (+ "import sys; from pathlib import Path; "+ f"sys.path.insert(0, {str(checkout)!r}); from pm import client, paths; "+ f"paths.repo_root = lambda: Path({str(world.core)!r}); "+ f"paths.lockfile_path = lambda: Path({str(world.root / 'lock.json')!r})\n"+ "def ready(worker, **kwargs):\n"+ " print('READY', flush=True)\n"+ " assert sys.stdin.readline().strip() == 'go'\n"+ f" return {command!r}\n"+ "client.runtime_command = ready\n"+ "from hermes_cli.plugins_cmd import cmd_enable\n"- f"cmd_enable({name!r}, allow_tool_override=False)\n"++ "from hermes_cli.plugins_admission import AdmissionRefused\n"++ "try:\n"++ f" cmd_enable({name!r}, allow_tool_override=False)\n"++ "except AdmissionRefused as exc:\n"++ " assert 'configuration changed since this selection was read' in str(exc)\n"++ " raise SystemExit(75)\n"+ )+ processes.append(subprocess.Popen([sys.executable, "-I", "-B", "-c", script],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,+ env={**os.environ, "HERMES_HOME": str(home)}))+ # Both commands have reached the worker launch (after the old stale+ # read). Release one all the way through publication, then the other.+ ready = queue.Queue()+ for process in processes:+ threading.Thread(target=lambda proc=process: ready.put(proc.stdout.readline().strip()), daemon=True).start()+ assert [ready.get(timeout=30) for _ in processes] == ["READY", "READY"]- for process in processes:++ for index, process in enumerate(processes):+ out, err = process.communicate("go\n", timeout=60)- assert process.returncode == 0, out + err++ expected = 75 if index == 1 and not sibling_profiles else 0++ assert process.returncode == expected, out + err++ if not sibling_profiles:++ # The stale second request is refused, not acknowledged. An explicit++ # retry reads the first successful enable and extends it.++ assert world.enabled() == ["race-left"]++ world.command("enable", name="race-right", no_allow_tool_override=True)+ if sibling_profiles:+ assert (world.home / "config.yaml").read_bytes() == untouched+ for name, home in zip(("race-left", "race-right"), homes):+ assert yaml.safe_load((home / "config.yaml").read_text())["plugins"]["enabled"] == [name]+ else:+ assert set(world.enabled()) == {"race-left", "race-right"}, "acknowledged enable was lost"+ for name, home in zip(("race-left", "race-right"), homes):+ original = world.home+ world.home = home+ try:+ world.imports(name)+ finally:+ world.home = original+ finally:+ for process in processes:+ if process.poll() is None:+ process.kill()+ process.communicate(timeout=10)diff --cc tests/hermes_cli/test_plugins_admission_setter.pyindex 6a10dae660f,e409829ac5f..9a515fe2e40--- a/tests/hermes_cli/test_plugins_admission_setter.py+++ b/tests/hermes_cli/test_plugins_admission_setter.py@@@ -4,94 -13,254 +4,95 @@@ import syimport pytest-import hermes_cli.plugins_cmd as pc-from hermes_cli import plugins_admission as adm---class _Console:- def __init__(self):- self.lines: list[str] = []-- def print(self, *args, **kwargs):- for arg in args:- self.lines.append(str(arg))---def plugin_home(tmp_path, monkeypatch):- """Isolated HERMES_HOME: config.yaml, plugins/, facts all under tmp."""- home = tmp_path / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- (home / "plugins").mkdir()- return home---def _enabled_set(home) -> set:- from hermes_cli.config import load_config-- cfg = load_config()- return set(((cfg.get("plugins") or {}).get("enabled")) or [])---def _write_sets(home, enabled=(), disabled=()):- pc._write_config_value("plugins", "enabled", sorted(enabled))- pc._write_config_value("plugins", "disabled", sorted(disabled))---def sync_calls(monkeypatch):- """Stub the admission caller seam; real engine transactions are tested below."""- from pm import client- calls = []-- 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---def _dep_plugin(home) -> Path:- d = home / "plugins" / "dep-plug"- d.mkdir(exist_ok=True)- (d / "plugin.yaml").write_text(- 'name: dep-plug\npython_dependencies:\n - "somepkg>=1"\n', encoding="utf-8"- )- return d---def _entry(dir_path: Path):- return ("dep-plug", "1.0", "test plugin", "user", dir_path, "dep-plug")---def _discovery(monkeypatch, *entries):- monkeypatch.setattr(pc, "_discover_all_plugins", lambda: list(entries))- monkeypatch.setattr(pc, "_declared_capabilities_for_key", lambda key: [])---def _refusing_sync(monkeypatch, message="uv lock exited 1: unsatisfiable"):- from pm import client-- def _boom(*a, **k):- raise RuntimeError(message)-- monkeypatch.setattr(client, "sync_venv", _boom)---# ── cmd_enable (CLI path) ────────────────────────────────────────────────────---def test_enable_refusal_keeps_config(plugin_home, monkeypatch, sync_calls):- plug = _dep_plugin(plugin_home)- _discovery(monkeypatch, _entry(plug))- _refusing_sync(monkeypatch)- console = _Console()- monkeypatch.setattr(pc, "_console", lambda: console)- with pytest.raises(adm.AdmissionRefused):- pc.cmd_enable("dep-plug", allow_tool_override=False)- assert _enabled_set(plugin_home) == set() # config untouched- assert any("refused" in line for line in console.lines)---def test_enable_success_commits_candidate_union_once(plugin_home, monkeypatch, sync_calls):- plug = _dep_plugin(plugin_home)- _discovery(monkeypatch, _entry(plug))- pc.cmd_enable("dep-plug", allow_tool_override=False)- assert sync_calls == [[plug]] # exactly ONE sync: the candidate union- assert _enabled_set(plugin_home) == {"dep-plug"}---def test_enable_removal_filters_candidate(plugin_home, monkeypatch, sync_calls):- other = plugin_home / "plugins" / "other"- other.mkdir()- (other / "pyproject.toml").write_text("[project]\nname='o'\n", encoding="utf-8")- _write_sets(plugin_home, enabled=["other"])- plug = _dep_plugin(plugin_home)- _discovery(monkeypatch, _entry(plug))- pc.cmd_enable("dep-plug", allow_tool_override=False)- # proposed-sets driven: 'other' stays enabled (it IS in the candidate set)- assert sync_calls[-1] and set(sync_calls[-1]) == {other, plug}- assert _enabled_set(plugin_home) == {"other", "dep-plug"}---def test_deps_free_enable_does_not_churn_venv(plugin_home, monkeypatch, sync_calls):- plain = plugin_home / "plugins" / "plain"- plain.mkdir()- (plain / "plugin.yaml").write_text("name: plain\n", encoding="utf-8")- _discovery(monkeypatch, ("plain", "1.0", "p", "user", plain, "plain"))- pc.cmd_enable("plain", allow_tool_override=False)- assert sync_calls == [[]] # no members: cheap stamp check only---# ── composite UI + dashboard paths ──────────────────────────────────────────---def test_composite_selection_refusal_not_saved(plugin_home, monkeypatch, sync_calls):- plug = _dep_plugin(plugin_home)- _discovery(monkeypatch, _entry(plug))- _refusing_sync(monkeypatch, "conflict")- with pytest.raises(adm.AdmissionRefused):- pc._persist_plugin_selection(["dep-plug"], {0}, set())- assert _enabled_set(plugin_home) == set()---def test_dashboard_enable_refusal_reports_not_ok(plugin_home, monkeypatch, sync_calls):- plug = _dep_plugin(plugin_home)- monkeypatch.setattr(pc, "_resolve_plugin_key", lambda name: "dep-plug")- _refusing_sync(monkeypatch, "conflict")- result = pc.dashboard_set_agent_plugin_enabled("dep-plug", enabled=True)- assert result["ok"] is False- assert _enabled_set(plugin_home) == set()---# ── worker-owned publication: exact rollback on facts failure ─---def test_config_commit_undo_restores_previous_bytes(plugin_home):- _write_sets(plugin_home, enabled=["old"])- config_path = plugin_home / "config.yaml"- previous = config_path.read_bytes()-- 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- recover_publication(repo_root()) # facts write failed afterwards → restore- assert config_path.read_bytes() == previous---def test_facts_failure_triggers_undo_inside_one_transaction(plugin_home, monkeypatch):- """Real sync_venv: apply stages → worker commits config → facts- write fails → undo restores the previous config bytes atomically; the- receipt records the failure."""- import importlib- import sys-- if "pm.ensure" not in sys.modules:- importlib.import_module("pm.ensure")- ensure = sys.modules["pm.ensure"]-- rdir = plugin_home / "receipts"- monkeypatch.setattr("pm.receipt._receipt_dir", lambda: rdir)- plug = _dep_plugin(plugin_home)- _write_sets(plugin_home, enabled=["old"])- previous = (plugin_home / "config.yaml").read_bytes()-- monkeypatch.setattr(ensure, "_runtime_state_matches", lambda fact, stamp: False)- monkeypatch.setattr(ensure, "_facts", lambda: {})- monkeypatch.setattr(- ensure, "get_package",- lambda name: SimpleNamespace(- expected_stamp=lambda enabled, **kw: "stamp1", apply=lambda enabled, **kw: {}- ),- )-- order = []-- facts_path = plugin_home / "runtime" / "facts.json"- ensure.Facts(facts_path).record_state("venv", "previous-stamp", [])- previous_facts = facts_path.read_bytes()- monkeypatch.setattr(ensure.paths, "runtime_facts_path", lambda: facts_path)- monkeypatch.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, selection={"home": str(plugin_home), "enabled": ["dep-plug"], "disabled": []})- assert order == ["record_state"] # config committed under the lock first- assert (plugin_home / "config.yaml").read_bytes() == previous # undone atomically- assert facts_path.read_bytes() == previous_facts- latest = json.loads((rdir / "latest.json").read_text(encoding="utf-8-sig"))- assert latest["outcome"] == "failed"---# ── pm receipt invariant: every sync outcome writes a receipt ───────────────---def test_lazy_refusal_writes_failed_receipt(plugin_home, monkeypatch):- import importlib- import sys-- if "pm.ensure" not in sys.modules:- importlib.import_module("pm.ensure")- ensure = sys.modules["pm.ensure"]- rdir = plugin_home / "receipts"- monkeypatch.setattr("pm.receipt._receipt_dir", lambda: rdir)- monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: False)- monkeypatch.setattr(ensure, "_runtime_state_matches", lambda fact, stamp: False)- with pytest.raises(Exception):- ensure.sync_venv(extras=["somepkg"])- latest = json.loads((rdir / "latest.json").read_text(encoding="utf-8-sig"))- assert latest["kind"] == "sync"- assert latest["outcome"] == "failed"---def test_noop_sync_writes_ok_receipt_rebuild_false(plugin_home, monkeypatch):- import importlib- import sys-- if "pm.ensure" not in sys.modules:- importlib.import_module("pm.ensure")- ensure = sys.modules["pm.ensure"]- rdir = plugin_home / "receipts"- monkeypatch.setattr("pm.receipt._receipt_dir", lambda: rdir)- monkeypatch.setattr(ensure, "_runtime_state_matches", lambda fact, stamp: True)- 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 False- assert latest["venv_rebuild"]["reason"] == "already in sync"+from tests.hermes_cli.plugin_worker_support import (+ plugin_world as plugin_world,+ worker_command,+ isolated_python as isolated_python,+)++[email protected]("failure", ["config", "facts"])+def test_failed_publication_preserves_selection_and_imports(plugin_world, monkeypatch, failure):- from hermes_cli import runtime_state+ from hermes_cli.plugins_admission import AdmissionRefused+ from pm import client, paths, receipt++ world = plugin_world+ origin, sha = world.origin()+ world.command("install", identifier=origin.as_uri(), ref=sha, no_enable=True, allow_removed=True)+ world.command("enable", name="plugin-worker-proof", no_allow_tool_override=True)+ world.imports()+ selected = world.selected()+ origin, sha = world.origin(name="publication-candidate")+ world.command("install", identifier=origin.as_uri(), ref=sha, no_enable=True, allow_removed=True)+ config = world.home / "config.yaml"+ watched = [config, paths.runtime_facts_path()]+ before = {path: path.read_bytes() for path in watched}+ if failure == "config":- atomic_bytes = runtime_state._atomic_bytes- def fail(path, data):- if path == config and b"publication-candidate" in data:- raise OSError("fixture config disk full")- return atomic_bytes(path, data)- monkeypatch.setattr(runtime_state, "_atomic_bytes", fail)++ prelude = (++ "from pm import publication\n"++ "atomic_bytes = publication._atomic_bytes\n"++ "def fail(path, data):\n"++ f" if path == Path({str(config)!r}) and b'publication-candidate' in data:\n"++ " raise OSError('fixture config disk full')\n"++ " return atomic_bytes(path, data)\n"++ "publication._atomic_bytes = fail\n"++ )+ else:- # Fail on the worker's real disk-publication boundary, after proving- # the client callback has already changed config. Undo must cross the- # wire before the command can return failure.++ # Config and facts now publish in the worker; the failed command must++ # return only after that same worker has restored the previous bytes.+ prelude = (+ "from pm.lock import Facts\n"+ "def fail(self, *args, **kwargs):\n"+ f" assert 'publication-candidate' in Path({str(config)!r}).read_text()\n"+ " raise OSError('fixture facts disk full')\n"+ "Facts.record_state = fail\n"+ )- uv = shutil.which("uv")- assert uv- monkeypatch.setattr(client, "runtime_command", lambda path, **kw:- worker_command(path, uv, sys.executable, prelude=prelude,- runtime_python=world.runtime_python))++ uv = shutil.which("uv")++ assert uv++ monkeypatch.setattr(client, "runtime_command", lambda path, **kw:++ worker_command(path, uv, sys.executable, prelude=prelude,++ runtime_python=world.runtime_python))+ with pytest.raises(AdmissionRefused, match=f"fixture {failure} disk full"):+ world.command("enable", name="publication-candidate", no_allow_tool_override=True)+ assert {path: path.read_bytes() for path in watched} == before+ assert world.selected() == selected+ world.imports()+ assert receipt.latest()["outcome"] == "failed"+++def test_historical_writer_hands_off_without_mutating_config(plugin_world, monkeypatch):+ from hermes_cli.plugins_cmd import _save_enabled_set++ config = plugin_world.home / "config.yaml"+ before = config.read_bytes()+ def takeover():+ raise SystemExit(73)+ monkeypatch.setattr("hermes_cli._old_updater.stop_for_relaunch", takeover)+ with pytest.raises(SystemExit) as exc:+ _save_enabled_set({"must-not-be-saved"})+ assert exc.value.code == 73+ assert config.read_bytes() == before++[email protected]("surface", ["dashboard", "composite"])+def test_ui_conflict_is_reported_without_changing_selection(plugin_world, surface):+ from hermes_cli import plugins_cmd+ from hermes_cli.plugins_admission import AdmissionRefused+ from pm import paths++ world = plugin_world+ origin, sha = world.origin()+ world.command("install", identifier=origin.as_uri(), ref=sha, no_enable=True, allow_removed=True)+ world.command("enable", name="plugin-worker-proof", no_allow_tool_override=True)+ origin, sha = world.origin(name="conflicting-ui-plugin", pin="2.0")+ world.command("install", identifier=origin.as_uri(), ref=sha, no_enable=True, allow_removed=True)+ watched = [world.home / "config.yaml", paths.runtime_facts_path()]+ before = {path: path.read_bytes() for path in watched}+ if surface == "dashboard":+ result = plugins_cmd.dashboard_set_agent_plugin_enabled("conflicting-ui-plugin", enabled=True)+ assert not result["ok"] and "plugin-proof-dep" in result["error"]+ else:+ with pytest.raises(AdmissionRefused, match="plugin-proof-dep"):+ plugins_cmd._persist_plugin_selection(["plugin-worker-proof", "conflicting-ui-plugin"], {0, 1}, set())+ assert {path: path.read_bytes() for path in watched} == before+ world.imports()diff --cc tests/hermes_cli/test_plugins_cmd_enable_disable_nested.pyindex c6c72e470ea,62b4be831d1..ae27691c5e3--- a/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py+++ b/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py@@@ -1,90 -1,282 +1,131 @@@-"""Tests for nested/alias-normalized enable & disable flows.--Companion to test_plugins_cmd_category_discovery.py. That file covers the-*listing* side of nested category plugins (issue #41066). These tests cover-the *mutation* side: `hermes plugins enable/disable` must resolve a bare name-OR a full path-derived key (e.g. `observability/trace_sink`) to the canonical-registry key and write THAT — the same string PluginManager gates on — so a-nested bundled plugin can actually be toggled.-"""--import sys # noqa: F401-from pathlib import Path-from unittest.mock import patch+"""Canonical keys and privilege consent through real admission."""+import shutilimport pytest--[email protected](autouse=True)-def _capture_selection(monkeypatch):- import hermes_cli.plugins_cmd as pc- from hermes_cli import plugins_admission- def save(enabled, disabled, **kwargs):- pc._save_enabled_set(enabled)- pc._save_disabled_set(disabled)- monkeypatch.setattr(plugins_admission, "admit_plugin_set_change", save)---def _make_plugin_dir(parent: Path, name: str, manifest: dict) -> Path:- d = parent / name- d.mkdir(parents=True, exist_ok=True)- import hermes_yaml as yaml- (d / "plugin.yaml").write_text(yaml.safe_dump(manifest), encoding="utf-8")- (d / "__init__.py").write_text("def register(ctx): pass\n", encoding="utf-8")- return d---def _make_category_plugin(parent: Path, category: str, name: str, manifest: dict) -> Path:- return _make_plugin_dir(parent / category, name, manifest)---def nested_plugin_env(tmp_path):- """A user-plugins dir containing one nested and one flat plugin, with the- bundled dir pointed at an empty path. Returns the tmp_path."""- _make_category_plugin(tmp_path, "observability", "trace_sink", {- "name": "trace_sink", "version": "1.0.0", "description": "trace sink"- })- _make_plugin_dir(tmp_path, "disk-cleanup", {- "name": "disk-cleanup", "version": "1.0.0"- })- return tmp_path---# ----------------------------------------------------------------------------# _resolve_plugin_key-# ------------------------------------------------------------------------------class TestResolvePluginKey:- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- def test_full_key_resolves_to_itself(self, mock_user, mock_bundled, nested_plugin_env):- from hermes_cli.plugins_cmd import _resolve_plugin_key- mock_user.return_value = nested_plugin_env- mock_bundled.return_value = nested_plugin_env / "nonexistent"- assert _resolve_plugin_key("observability/trace_sink") == "observability/trace_sink"--- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- def test_unknown_returns_none(self, mock_user, mock_bundled, nested_plugin_env):- from hermes_cli.plugins_cmd import _resolve_plugin_key- mock_user.return_value = nested_plugin_env- mock_bundled.return_value = nested_plugin_env / "nonexistent"- assert _resolve_plugin_key("does-not-exist") is None-- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- def test_ambiguous_leaf_name_returns_none(self, mock_user, mock_bundled, tmp_path):- """Same leaf name under two categories must NOT silently pick one."""- from hermes_cli.plugins_cmd import _resolve_plugin_key- _make_category_plugin(tmp_path, "image_gen", "openai", {"name": "image-gen-openai"})- _make_category_plugin(tmp_path, "model-providers", "openai", {"name": "mp-openai"})- mock_user.return_value = tmp_path- mock_bundled.return_value = tmp_path / "nonexistent"- # Bare "openai" is ambiguous -> None; the full key still resolves.- assert _resolve_plugin_key("openai") is None- assert _resolve_plugin_key("image_gen/openai") == "image_gen/openai"---# ----------------------------------------------------------------------------# cmd_enable / cmd_disable — write the canonical key-# ------------------------------------------------------------------------------class TestEnableDisableNested:- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- @patch("hermes_cli.plugins_cmd._save_disabled_set")- @patch("hermes_cli.plugins_cmd._save_enabled_set")- @patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set())- @patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())- def test_enable_bare_name_writes_key(- self, mock_en, mock_dis, mock_save_en, mock_save_dis,- mock_user, mock_bundled, nested_plugin_env,- ):- from hermes_cli.plugins_cmd import cmd_enable- mock_user.return_value = nested_plugin_env- mock_bundled.return_value = nested_plugin_env / "nonexistent"-- cmd_enable("trace_sink", allow_tool_override=False) # bare name-- saved = mock_save_en.call_args[0][0]- # The canonical key — NOT the bare name — must be persisted, because- # that is what PluginManager matches when deciding to load.- assert "observability/trace_sink" in saved- assert "trace_sink" not in saved or "observability/trace_sink" in saved--- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- def test_enable_unknown_plugin_exits(self, mock_user, mock_bundled, nested_plugin_env):- from hermes_cli.plugins_cmd import cmd_enable- mock_user.return_value = nested_plugin_env- mock_bundled.return_value = nested_plugin_env / "nonexistent"- with pytest.raises(SystemExit):- cmd_enable("does-not-exist")-- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- @patch("hermes_cli.plugins_cmd._save_disabled_set")- @patch("hermes_cli.plugins_cmd._save_enabled_set")- @patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set())- @patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())- def test_enable_flat_plugin_unchanged(- self, mock_en, mock_dis, mock_save_en, mock_save_dis,- mock_user, mock_bundled, nested_plugin_env,- ):- """Flat plugins keep writing their bare name (key == name) — no regression."""- from hermes_cli.plugins_cmd import cmd_enable- mock_user.return_value = nested_plugin_env- mock_bundled.return_value = nested_plugin_env / "nonexistent"-- cmd_enable("disk-cleanup", allow_tool_override=False)- saved = mock_save_en.call_args[0][0]- assert "disk-cleanup" in saved---# ----------------------------------------------------------------------------# cmd_enable — built-in tool override consent (issue #29249)-# ------------------------------------------------------------------------------class TestEnableToolOverrideConsent:- """Enabling a non-bundled plugin must surface a consent decision about the- privileged ``allow_tool_override`` capability, and persist the operator's- choice under ``plugins.entries.<key>.allow_tool_override``."""--- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- @patch("hermes_cli.plugins_cmd._set_plugin_entry_flag")- @patch("hermes_cli.plugins_cmd._save_disabled_set")- @patch("hermes_cli.plugins_cmd._save_enabled_set")- @patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set())- @patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())- def test_interactive_eof_defaults_to_deny(- self, mock_en, mock_dis, mock_save_en, mock_save_dis, mock_set_flag,- mock_user, mock_bundled, nested_plugin_env,- ):- """Non-interactive stdin (EOFError) must fail closed to deny."""- from hermes_cli.plugins_cmd import cmd_enable- mock_user.return_value = nested_plugin_env- mock_bundled.return_value = nested_plugin_env / "nonexistent"-- with patch("rich.console.Console.input", side_effect=EOFError):- cmd_enable("disk-cleanup")-- mock_set_flag.assert_called_once_with(- "disk-cleanup", "allow_tool_override", False- )-- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- @patch("hermes_cli.plugins_cmd._set_plugin_entry_flag")- @patch("hermes_cli.plugins_cmd._save_disabled_set")- @patch("hermes_cli.plugins_cmd._save_enabled_set")- @patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set())- @patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())- def test_bundled_plugin_never_prompts_or_writes_entry(- self, mock_en, mock_dis, mock_save_en, mock_save_dis, mock_set_flag,- mock_user, mock_bundled, tmp_path,- ):- """Bundled plugins are trusted — no consent prompt, no entry write."""- from hermes_cli.plugins_cmd import cmd_enable- # Bundled dir holds the plugin; user dir is empty.- _make_plugin_dir(tmp_path / "bundled", "trusted_bundled", {- "name": "trusted_bundled", "version": "1.0.0",- })- mock_user.return_value = tmp_path / "empty"- mock_bundled.return_value = tmp_path / "bundled"-- # Console.input would raise if called — proving no prompt fired.- with patch("rich.console.Console.input", side_effect=AssertionError("prompted")):- cmd_enable("trusted_bundled")-- mock_set_flag.assert_not_called()---class TestCompositeMenuWritesCanonicalKey:- """#40190 follow-up: the interactive `hermes plugins` menu must persist- the CANONICAL KEY (``web/firecrawl``), never the bare manifest name- (``web-firecrawl``), so its disabled-list entries stay aligned with what- ``cmd_enable`` clears and what PluginManager gates on. Writing the bare- name is what silently vetoed a bundled backend forever (pi314).- """-- @patch("hermes_cli.plugins_cmd._save_disabled_set")- @patch("hermes_cli.plugins_cmd._save_enabled_set")- @patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())- def test_fallback_unchecked_plugin_disables_by_key_not_name(- self, mock_en, mock_save_en, mock_save_dis,- ):- from hermes_cli.plugins_cmd import _run_composite_fallback- from rich.console import Console-- # key differs from the manifest name, mirroring web/firecrawl.- plugin_keys = ["web/firecrawl"]- plugin_labels = ["web-firecrawl — firecrawl [bundled]"]- plugin_selected = set() # unchecked → should be disabled-- # First input() toggles nothing (blank Enter confirms immediately),- # second (category prompt) is skipped with blank Enter.- with patch("builtins.input", return_value=""):- _run_composite_fallback(- plugin_keys, plugin_labels, plugin_selected,- set(), [], Console(),- )-- saved_dis = mock_save_dis.call_args[0][0]- assert "web/firecrawl" in saved_dis # canonical key persisted- assert "web-firecrawl" not in saved_dis # never the bare name-- @pytest.mark.parametrize("config_changes", [False, True])- def test_fallback_forwards_preinteraction_digest(- self, tmp_path, monkeypatch, config_changes,- ):- from hermes_cli import plugins_cmd as pc-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- config_path = tmp_path / "config.yaml"- initial_config = "plugins:\n enabled: [web/firecrawl]\n disabled: []\n"- config_path.write_text(initial_config, encoding="utf-8")- original_digest = pc._plugin_selection_version()- monkeypatch.setattr(pc, "_discover_all_plugins", lambda: [- ("web-firecrawl", "1.0", "firecrawl", "bundled", None, "web/firecrawl"),- ])- monkeypatch.setattr(pc, "_provider_categories", lambda: [])- monkeypatch.setattr(sys.stdin, "isatty", lambda: True)- # Missing curses must use the real text-menu and persistence chain.- monkeypatch.setitem(sys.modules, "curses", None)- answers = iter(("1", "")) # uncheck the plugin, then confirm-- def respond(_prompt):- answer = next(answers)- if config_changes and answer == "1":- config_path.write_text(- initial_config + "model: edited-during-input\n", encoding="utf-8",- )- return answer-- with patch("builtins.input", side_effect=respond), patch(- "hermes_cli.plugins_admission.admit_plugin_set_change",- ) as admit:- pc.cmd_toggle()-- admit.assert_called_once_with(- set(), {"web/firecrawl"}, active_plugins_dir=tmp_path / "plugins",- extra_dirs=(), expected_config=original_digest,- )- if config_changes:- assert pc._plugin_selection_version() != original_digest+import hermes_yaml as yaml++from tests.hermes_cli.plugin_worker_support import (+ plugin_world as plugin_world,+ isolated_python as isolated_python,+)++[email protected]("query", ["trace-leaf", "trace-manifest", "observability/trace-leaf"])+def test_nested_enable_disable_and_composite_use_canonical_key(plugin_world, monkeypatch, query):+ from hermes_cli import plugins_cmd+ from rich.console import Console++ world = plugin_world+ origin, _ = world.origin(name="trace-manifest")+ key = "observability/trace-leaf"+ target = world.home / "plugins" / key+ shutil.copytree(origin, target)+ (world.home / "config.yaml").write_text(yaml.safe_dump({"plugins": {+ "enabled": [], "disabled": [key, "trace-leaf", "trace-manifest"]}}), encoding="utf-8")+ world.command("enable", name=query, no_allow_tool_override=True)+ assert world.enabled() == [key]+ config = yaml.safe_load((world.home / "config.yaml").read_text())+ assert config["plugins"]["disabled"] == []+ world.imports(key)+ world.command("disable", name=query)+ assert world.enabled() == []+ assert yaml.safe_load((world.home / "config.yaml").read_text())["plugins"]["disabled"] == [key]+ # The fallback menu must persist canonical keys too, not labels.+ monkeypatch.setattr("builtins.input", lambda prompt: "")+ plugins_cmd._run_composite_fallback([key], ["trace-manifest"], {0}, {key}, [], Console())+ assert world.enabled() == [key]+ world.imports(key)+++def test_ambiguous_and_unknown_names_cannot_change_config(plugin_world):+ from hermes_cli import plugins_cmd++ world = plugin_world+ for category in ("image_gen", "model-providers"):+ directory = world.home / "plugins" / category / "same-leaf"+ directory.mkdir(parents=True)+ (directory / "plugin.yaml").write_text(f"name: {category}-fixture\n", encoding="utf-8")+ before = (world.home / "config.yaml").read_bytes()+ for query in ("same-leaf", "not-installed"):+ with pytest.raises(SystemExit) as exc:+ world.command("enable", name=query)+ assert exc.value.code == 1+ assert plugins_cmd._resolve_plugin_key("image_gen/same-leaf") == "image_gen/same-leaf"+ assert (world.home / "config.yaml").read_bytes() == before+++def test_dependency_free_enable_no_churn_and_tool_override_fails_closed(plugin_world, monkeypatch):+ from hermes_cli import plugins_cmd+ from pm import client, receipt++ world = plugin_world+ client.sync_venv(explicit=True)+ selected = world.selected()+ origin, sha = world.origin(surface=None)+ facts = (world.home / "config.yaml").read_bytes()+ world.command("install", identifier=origin.as_uri(), ref=sha, no_enable=True, allow_removed=True)+ assert world.selected() == selected+ assert (world.home / "config.yaml").read_bytes() == facts+ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True)+ monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True)+ def eof(*args, **kwargs):+ raise EOFError+ monkeypatch.setattr("rich.console.Console.input", eof)+ world.command("enable", name="plugin-worker-proof")+ config = yaml.safe_load((world.home / "config.yaml").read_text())+ assert config["plugins"]["entries"]["plugin-worker-proof"]["allow_tool_override"] is False+ assert world.selected() == selected+ assert receipt.latest()["venv_rebuild"]["ok"] is False++ bundled = world.core / "plugins/trusted-fixture"+ bundled.mkdir(parents=True)+ (bundled / "plugin.yaml").write_text("name: trusted-fixture\n", encoding="utf-8")+ monkeypatch.setattr("hermes_cli.plugins.get_bundled_plugins_dir", lambda: world.core / "plugins")+ def unexpected(*args, **kwargs):+ pytest.fail("bundled plugin requested privilege consent")+ monkeypatch.setattr("rich.console.Console.input", unexpected)+ world.command("enable", name="trusted-fixture")+ config = yaml.safe_load((world.home / "config.yaml").read_text())+ assert "trusted-fixture" not in config["plugins"]["entries"]- assert world.selected() == selected++ assert world.selected() == selected++++[email protected]("config_changes", [False, True])++def test_fallback_compares_the_preinteraction_selection(plugin_world, monkeypatch, config_changes):++ from hermes_cli import plugins_cmd++ from pm import receipt++++ world = plugin_world++ origin, sha = world.origin()++ world.command("install", identifier=origin.as_uri(), ref=sha, no_enable=True, allow_removed=True)++ world.command("enable", name="plugin-worker-proof", no_allow_tool_override=True)++ config_path = world.home / "config.yaml"++ before = config_path.read_bytes()++ selected = world.selected()++ monkeypatch.setattr("hermes_cli.plugins.get_bundled_plugins_dir", lambda: world.core / "plugins")++ monkeypatch.setattr(plugins_cmd, "_provider_categories", lambda: [])++ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True)++ monkeypatch.setitem(plugins_cmd.sys.modules, "curses", None)++ answers = iter(("1", ""))++ edited = before + b"model: edited-during-input\n"++++ def respond(_prompt):++ answer = next(answers)++ if config_changes and answer == "1":++ config_path.write_bytes(edited)++ return answer++++ monkeypatch.setattr("builtins.input", respond)++ plugins_cmd.cmd_toggle()++ latest = receipt.latest()++ assert latest is not None++ if config_changes:++ assert config_path.read_bytes() == edited++ assert world.enabled() == ["plugin-worker-proof"]++ assert world.selected() == selected++ assert latest["outcome"] == "failed"++ world.imports()++ else:++ assert world.enabled() == []++ assert yaml.safe_load(config_path.read_text())["plugins"]["disabled"] == ["plugin-worker-proof"]++ assert latest["outcome"] == "ok"diff --cc tests/hermes_cli/test_update_apply_shallow_count.pyindex f25b6b60f13,430418351d2..16659ea3cdc--- a/tests/hermes_cli/test_update_apply_shallow_count.py+++ b/tests/hermes_cli/test_update_apply_shallow_count.py@@@ -5,43 -15,102 +5,43 @@@ from unittest.mock import Mocimport pytest- from hermes_cli import banner, main, update_cmd-import hermes_cli.update_cmd as update_cmd++from hermes_cli import main, source_check, update_cmdSHA_A = "a" * 40SHA_B = "b" * 40-def _git_responder(*, shallow: bool, count: str):- """Answer the git subprocess calls the count block makes."""-- def fake_run(cmd, **kwargs):- joined = " ".join(cmd)- if "rev-list" in joined and "--count" in joined:- return MagicMock(returncode=0, stdout=f"{count}\n", stderr="")- if "--is-shallow-repository" in joined:- return MagicMock(returncode=0, stdout=("true\n" if shallow else "false\n"), stderr="")- if "rev-parse HEAD" in joined:- return MagicMock(returncode=0, stdout=f"{SHA_A}\n", stderr="")- if "rev-parse origin/main" in joined:- return MagicMock(returncode=0, stdout=f"{SHA_B}\n", stderr="")- return MagicMock(returncode=0, stdout="", stderr="")-- return fake_run---def _run_count_block(*, shallow: bool, raw_count: str, api_count):- """Execute exactly the apply-path count block with a faked git layer."""- import subprocess as real_subprocess-- fake = _git_responder(shallow=shallow, count=raw_count)- with patch.object(update_cmd, "subprocess") as sub:- sub.run = MagicMock(side_effect=fake)- sub.CalledProcessError = real_subprocess.CalledProcessError- with patch("hermes_cli.source_check._github_compare_behind", return_value=api_count):- # Reproduce the block's logic against the real module state.- git_cmd = ["git"]- result = sub.run(- git_cmd + ["rev-list", "HEAD..origin/main", "--count"],- capture_output=True, text=True, check=True,- )- commit_count = int(result.stdout.strip())- apply_is_shallow = (- sub.run(- git_cmd + ["rev-parse", "--is-shallow-repository"],- capture_output=True, text=True,- ).stdout.strip()- == "true"- )- if commit_count > 0 and apply_is_shallow:- from hermes_cli.source_check import _github_compare_behind-- head_sha = sub.run(git_cmd + ["rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()- target_sha = sub.run(- git_cmd + ["rev-parse", "origin/main"], capture_output=True, text=True- ).stdout.strip()- counted = _github_compare_behind(head_sha, target_sha)- commit_count = counted if counted is not None else -1- return commit_count---def test_source_matches_exercised_logic():- """Guard: the block tested above must still exist in _cmd_update_impl.-- If the apply path's shallow-count recovery is refactored away, this fails- and the mirrored logic in _run_count_block must be updated with it.- """- import inspect-- src = inspect.getsource(update_cmd._prepare_checkout_for_update)- assert "apply_is_shallow" in src- assert "_github_compare_behind" in src- # The "count unknown" print stays in _cmd_update_impl, which consumes the plan.- assert "commit count unknown on this shallow checkout" in inspect.getsource(- update_cmd._cmd_update_impl[email protected]("shallow,raw_count,api_count,expected", [+ (False, 7, None, 7),+ (True, 9980, 12, 12),+ (True, 9980, None, -1),+ (True, 3, 0, 0),+ (True, 0, None, 0),+], ids=["full", "shallow-api", "shallow-offline", "local-ahead", "equal-tips"])+def test_apply_plan_counts_supplied_git_results(monkeypatch, tmp_path, shallow, raw_count, api_count, expected):+ monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)+ responses = {+ ("status", "--porcelain"): "",+ ("rev-list", "HEAD..origin/main", "--count"): str(raw_count),+ ("rev-parse", "--is-shallow-repository"): "true" if shallow else "false",+ ("rev-parse", "HEAD"): SHA_A,+ ("rev-parse", "origin/main"): SHA_B,+ }++ def git(cmd, **kwargs):+ assert cmd[0] == "git"+ return subprocess.CompletedProcess(cmd, 0, responses[tuple(cmd[1:])] + "\n", "")++ monkeypatch.setattr(subprocess, "run", git)+ compare = Mock(return_value=api_count)- monkeypatch.setattr(banner, "_github_compare_behind", compare)++ monkeypatch.setattr(source_check, "_github_compare_behind", compare)+ plan = update_cmd._prepare_checkout_for_update(+ ["git"], "main", "main", is_fork=False, assume_yes=False,+ gateway_mode=False, gw_input_fn=None, switch_branch=False,+ _windows_gateway_resume=None,)---def test_full_clone_keeps_exact_count():- assert _run_count_block(shallow=False, raw_count="7", api_count=None) == 7---def test_shallow_bogus_count_recovers_via_compare_api():- """FAIL-BEFORE: reported the bogus 9980 as 'Found 9980 new commit(s)'."""- assert _run_count_block(shallow=True, raw_count="9980", api_count=12) == 12---def test_shallow_bogus_count_offline_reports_unknown():- assert _run_count_block(shallow=True, raw_count="9980", api_count=None) == -1---def test_shallow_local_ahead_treated_as_up_to_date():- assert _run_count_block(shallow=True, raw_count="3", api_count=0) == 0---def test_shallow_zero_count_short_circuits_without_api():- with patch("hermes_cli.source_check._github_compare_behind") as api:- got = _run_count_block(shallow=True, raw_count="0", api_count=None)- # The block only consults the API when count > 0; a 0 count is trustworthy- # (HEAD == origin tip counts 0 even on shallow graphs).- assert got == 0+ assert plan.commit_count == expected+ if shallow and raw_count:+ compare.assert_called_once_with(SHA_A, SHA_B)+ else:- compare.assert_not_called()++ compare.assert_not_called()diff --cc tests/hermes_cli/test_update_autostash.pyindex 737a9349ba6,737a9349ba6..a36d6313aca--- a/tests/hermes_cli/test_update_autostash.py+++ b/tests/hermes_cli/test_update_autostash.py@@@ -11,7 -11,7 +11,7 @@@ from hermes_cli import update_cm@pytest.fixture(autouse=True)--def _patch_gateway_discovery(monkeypatch):++def _patch_gateway_discovery(monkeypatch, isolated_source_completion):"""Keep cmd_update's gateway auto-restart phase off this machine's gateways.Tests in this file that reach the full success path (e.g. the #87694@@@ -31,7 -31,7 +31,7 @@@monkeypatch.setattr(hermes_main, "_resume_windows_gateways_after_update", lambda *a: None)monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)monkeypatch.setattr(update_cmd, "_prepare_updated_checkout", lambda *a, **kw: None)-- monkeypatch.setattr("hermes_cli.update_cmd_maint._run_post_update_maintenance", lambda *a, **k: None)++ monkeypatch.setattr("hermes_cli.update_cmd_maint._run_post_update_maintenance", lambda *a, **k: True)with patch("hermes_cli.gateway.find_gateway_pids", return_value=[]), \patch("hermes_cli.gateway.supports_systemd_services", return_value=False), \patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]), \diff --cc tests/hermes_cli/test_update_completion_routing.pyindex 00000000000,e9a81d548ea..27f4cd2ffdcmode 000000,100644..100644--- a/tests/hermes_cli/test_update_completion_routing.py+++ b/tests/hermes_cli/test_update_completion_routing.py@@@ -1,0 -1,50 +1,67 @@@+ """All source selection routes hand off once, without old-process maintenance."""+ from types import SimpleNamespace+ from unittest.mock import Mock++ import pytest++ from hermes_cli import update_cmd, update_cmd_zip+++ @pytest.mark.parametrize("hook,args,kwargs", [+ (update_cmd._prepare_updated_checkout, ("unused",), {"desktop": False}),+ (update_cmd._reload_config_modules, (), {}),+ (update_cmd._reload_process_scan_modules, (), {}),+ (update_cmd._run_pending_fleet_restart, (), {}),+ ])+ def test_historical_completion_hook_never_reports_success(hook, args, kwargs, capsys):+ with pytest.raises(SystemExit) as error:+ hook(*args, **kwargs)+ assert error.value.code != 0+ assert "update" in capsys.readouterr().err.lower()++++def test_incomplete_handoff_requires_explicit_update_retry(tmp_path, monkeypatch, capsys):++ from hermes_cli import main++++ monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)++ completion = Mock()++ monkeypatch.setattr(update_cmd, "run_completion", completion)++ with pytest.raises(SystemExit) as error:++ update_cmd._complete_source_update(None)++ assert error.value.code == 1++ completion.assert_not_called()++ output = capsys.readouterr()++ assert "run `hermes update` again" in output.err++ assert "Update complete" not in output.out++ assert not (tmp_path / ".update-incomplete").exists()++ assert not (tmp_path / ".lazy-refresh-incomplete").exists()+++++ @pytest.mark.parametrize("route", ["pulled", "current", "zip"])+ def test_every_route_hands_off_once(route, tmp_path, monkeypatch):+ request = {"branch": "main", "receipt": {"update_id": "c" * 32}}+ handed_off = []+ monkeypatch.setattr(update_cmd, "_complete_source_update", handed_off.append, raising=False)+ monkeypatch.setattr(update_cmd, "_m", lambda: SimpleNamespace(+ PROJECT_ROOT=tmp_path, _resolve_update_branch=lambda args: "main"))+ monkeypatch.setattr(update_cmd, "_verify_head_after_pull", lambda *a, **kw: "new-sha")+ monkeypatch.setattr(update_cmd, "_prepare_updated_checkout", lambda *a, **kw: pytest.fail("old-process preparation"))+ monkeypatch.setattr(update_cmd, "_write_fleet_restart_pending_marker", lambda **kw: None)+ monkeypatch.setattr(update_cmd, "_sweep_bytecode_after_update", lambda *a: None)+ monkeypatch.setattr(update_cmd_zip, "_abort_zip_update_if_dirty_tree", lambda: None)+ swap = Mock()+ monkeypatch.setattr(update_cmd_zip, "_download_and_swap_zip", swap)+ plan = SimpleNamespace(in_place_update=False, auto_stash_ref=None, parked_branch_switched=False,+ upstream_checked=True)+ opts = SimpleNamespace(assume_yes=True, gw_input_fn=None, pre_update_version="old")+ if route == "pulled":+ update_cmd._apply_pulled_update(+ ["git"], "main", "old-sha", plan, opts, is_fork=False, _windows_gateway_resume=None,+ completion_request=request)+ elif route == "current":+ update_cmd._finish_already_up_to_date(+ ["git"], "main", "main", plan, gw_input_fn=None, completion_request=request)+ else:+ assert update_cmd_zip._update_via_zip(SimpleNamespace(), completion_request=request) is True+ swap.assert_called_once()+ assert handed_off == [request]diff --cc tests/hermes_cli/test_update_missing_configured_deps.pyindex 97e80c5ea11,00000000000..9f3de8f0881mode 100644,000000..100644--- a/tests/hermes_cli/test_update_missing_configured_deps.py+++ b/tests/hermes_cli/test_update_missing_configured_deps.py@@@ -1,115 -1,0 +1,109 @@@+"""Configured-feature warnings must describe the selected update child (#10651).++PM's atomic dependency union cannot validate a configured but unselected SDK.+These tests use real PM publication and a fresh interpreter; only expensive+frontend compilation is replaced. SDK anchors exist only in the target tree.+"""+from __future__ import annotations++import json+from pathlib import Path+import sys+import sysconfig++import subprocess++import pytest++import pm- from hermes_cli.runtime_paths import runtime_facts_path, selected_venv, site_packages++from hermes_cli.runtime_paths import activation_environment, runtime_facts_path, selected_venv, site_packages++from hermes_constants import venv_python_path+from tests.pm._fixtures import isolated_python # noqa: F401+from tests.pm.test_source_update_launch import source_launch # noqa: F401+++def configured_update(source_launch, tmp_path, monkeypatch):- from hermes_cli import update_cmd_maint-+ root, _, _ = source_launch+ repository = Path(__file__).resolve().parents[2]+ pm.sync_venv(["launch-extra"], explicit=True, project_root=root)+ selected = selected_venv(root)+ site = site_packages(selected)+ # Reuse installed core libraries without exposing the updater's site tree:+ # neither SDK, executable .pth hooks, nor editable package finders cross over.+ for path in Path(sysconfig.get_path("purelib")).iterdir():+ if (path.name in {"lark_oapi", "mcp", "__pycache__"}+ or path.name.startswith(("lark_oapi-", "mcp-", "__editable__"))+ or path.suffix == ".pth" or (site / path.name).exists()):+ continue+ (site / path.name).symlink_to(path, target_is_directory=path.is_dir())+ # Application source is unchanged; the toy manifest keeps PM resolution+ # offline while exercising the real selected-environment launch boundary.+ for path in repository.iterdir():+ if path.name in {"hermes_cli", "gateway", "agent", "tools", "plugins", "pm"} or path.suffix == ".py":+ (root / path.name).symlink_to(path, target_is_directory=path.is_dir())- run = update_cmd_maint.subprocess.run-- def build_in_child(command, **kwargs):- if command[1:3] == ["-m", "hermes_cli.source_build"]:- assert command[3:] == ["--source", str(root)]- script = (- "import json, sys; from pathlib import Path\n"- "from hermes_cli import source_build\n"- "source_build.source_build_env = lambda **kwargs: {}\n"- "source_build.prepare_source_dependencies = lambda *args, **kwargs: None\n"- "source_build.build_source_tui = lambda *args, **kwargs: None\n"- "source_build.build_source_web = lambda *args, **kwargs: None\n"- f"source_build.build_update_products(Path({str(root)!r}), desktop=False)\n"- "print('TARGET=' + json.dumps({'prefix': sys.prefix, 'python': sys.executable}))\n"- )- command = [command[0], "-c", script]- return run(command, **kwargs)-- monkeypatch.setattr(update_cmd_maint.subprocess, "run", build_in_child)++ def build_in_child():++ script = (++ "import json, sys; from pathlib import Path\n"++ "from hermes_cli import source_build\n"++ "source_build.source_build_env = lambda **kwargs: {}\n"++ "source_build.prepare_source_dependencies = lambda *args, **kwargs: None\n"++ "source_build.build_source_tui = lambda *args, **kwargs: None\n"++ "source_build.build_source_web = lambda *args, **kwargs: None\n"++ f"source_build.build_update_products(Path({str(root)!r}), desktop=False)\n"++ "print('TARGET=' + json.dumps({'prefix': sys.prefix, 'python': sys.executable}))\n"++ )++ subprocess.run([str(venv_python_path(selected)), "-c", script],++ cwd=root, env=activation_environment(root), check=True)+ home = tmp_path / "home"+ config = home / "config.yaml"+ config.write_text(+ "platforms:\n feishu:\n enabled: true\n extra:\n app_id: cli_x\n app_secret: y\n"+ "mcp_servers:\n fixture:\n command: must-not-run\n",+ encoding="utf-8",+ )+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")+ # A stale positive verdict in the updater must not conceal missing child SDKs.+ from types import ModuleType+ for name in ("lark_oapi", "mcp"):+ monkeypatch.setitem(sys.modules, name, ModuleType(name))- return root, selected, site, config, update_cmd_maint++ return root, selected, site, config, build_in_child++[email protected]("posix")+def test_update_names_missing_configured_features_from_selected_child(configured_update, capfd):- root, selected, site, _, maintenance = configured_update++ root, selected, site, _, build = configured_update+ facts = runtime_facts_path(root).read_bytes()- maintenance._prepare_updated_checkout(root, desktop=False)++ build()+ out = capfd.readouterr().out+ assert "fail to load them on restart" in out+ assert "Feishu / Lark" in out and "MCP servers" in out+ assert "hermes setup" in out and "hermes pm" in out+ target = json.loads(next(line.removeprefix("TARGET=") for line in out.splitlines() if line.startswith("TARGET=")))+ assert Path(target["prefix"]) == selected+ assert Path(target["python"]).parent.parent == selected+ assert runtime_facts_path(root).read_bytes() == facts+ assert not (root / ".update-incomplete").exists()++ # Only the target gains the anchors; no updater module/cache is repaired.+ for name in ("lark_oapi", "mcp"):+ (site / f"{name}.py").write_text("# Passive dependency-probe fixture.\n", encoding="utf-8")- maintenance._prepare_updated_checkout(root, desktop=False)++ build()+ assert "fail to load them on restart" not in capfd.readouterr().out+ assert runtime_facts_path(root).read_bytes() == facts++[email protected]("posix")+def test_unconfigured_or_disabled_features_are_quiet(configured_update, capfd):- root, _, _, config, maintenance = configured_update++ root, _, _, config, build = configured_update+ for body in (+ "platforms:\n feishu:\n enabled: false\n extra:\n app_id: cli_x\n app_secret: y\n",+ "platforms:\n feishu:\n enabled: true\n",+ ):+ config.write_text(body, encoding="utf-8")- maintenance._prepare_updated_checkout(root, desktop=False)++ build()+ out = capfd.readouterr().out+ assert "TARGET=" in out+ assert "fail to load them on restart" not in out+ assert "MCP servers" not in out+ assert "Feishu / Lark:" not in out+ assert not (root / ".update-incomplete").exists()diff --cc tests/hermes_cli/test_update_yes_flag.pyindex 8c7b7e0d9c9,8c7b7e0d9c9..4ba8774658a--- a/tests/hermes_cli/test_update_yes_flag.py+++ b/tests/hermes_cli/test_update_yes_flag.py@@@ -73,8 -73,8 +73,8 @@@ class TestUpdateYesConfigMigration"""--yes auto-answers the config-migration prompt and skips API-key prompts."""@patch("hermes_cli.update_cmd._reload_config_modules")-- @patch("hermes_cli.update_cmd._run_migrate_config_fresh")-- @patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 2))++ @patch("hermes_cli.config.migrate_config")++ @patch("hermes_cli.config.check_config_version", return_value=(1, 2))@patch("hermes_cli.config.get_missing_config_fields", return_value=[])@patch("hermes_cli.config.get_missing_env_vars", return_value=["NEW_KEY"])@patch("shutil.which", return_value=None)@@@ -114,8 -114,8 +114,8 @@@assert "Would you like to configure them now?" not in out@patch("hermes_cli.update_cmd._reload_config_modules")-- @patch("hermes_cli.update_cmd._run_migrate_config_fresh")-- @patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 2))++ @patch("hermes_cli.config.migrate_config")++ @patch("hermes_cli.config.check_config_version", return_value=(1, 2))@patch("hermes_cli.config.get_missing_config_fields", return_value=[])@patch("hermes_cli.config.get_missing_env_vars", return_value=["NEW_KEY"])@patch("shutil.which", return_value=None)@@@ -174,8 -174,8 +174,8 @@@ class TestUnicodeDecodeErrorInUpdatePro"""@patch("hermes_cli.update_cmd._reload_config_modules")-- @patch("hermes_cli.update_cmd._run_migrate_config_fresh")-- @patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 2))++ @patch("hermes_cli.config.migrate_config")++ @patch("hermes_cli.config.check_config_version", return_value=(1, 2))@patch("hermes_cli.config.get_missing_config_fields", return_value=[])@patch("hermes_cli.config.get_missing_env_vars", return_value=["NEW_KEY"])@patch("shutil.which", return_value=None)diff --cc tests/hermes_cli/test_update_zip_completion.pyindex 89f9ddb6e86,00000000000..60542b88389mode 100644,000000..100644--- a/tests/hermes_cli/test_update_zip_completion.py+++ b/tests/hermes_cli/test_update_zip_completion.py@@@ -1,220 -1,0 +1,224 @@@+"""ZIP completion uses the Git maintenance/fleet path after a real local swap."""+from __future__ import annotations++import json+from pathlib import Path+import subprocess+from types import SimpleNamespace+from urllib.request import urlretrieve+import zipfile++import pytest++from hermes_cli import main, update_cmd, update_cmd_fleet as fleet, update_cmd_maint as maint+from hermes_cli import update_cmd_zip, update_receipt+from hermes_cli.config_defaults import DEFAULT_CONFIG+from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan+import hermes_yaml++- def zip_update(tmp_path, monkeypatch):++def zip_update(tmp_path, monkeypatch, isolated_source_completion):+ home = tmp_path / "home"+ active = home / ".hermes"+ sibling = active / "profiles/other"+ sibling.mkdir(parents=True)+ monkeypatch.setattr(Path, "home", lambda: home)+ monkeypatch.setenv("HOME", str(home))+ monkeypatch.setenv("HERMES_HOME", str(active))+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "store"))+ for profile in (active, sibling):+ (profile / "config.yaml").write_text(+ f"_config_version: {DEFAULT_CONFIG['_config_version'] - 1}\n"+ "model:\n default: retained-model\n", encoding="utf-8")+ (active / ".env").write_text("EXAMPLE_TOKEN=retained\n", encoding="utf-8")+ jobs = active / "cron/jobs.json"+ jobs.parent.mkdir()+ original_jobs = {"jobs": [{"id": "keep-me", "prompt": "retained schedule"}]}+ jobs.write_text(json.dumps(original_jobs), encoding="utf-8")++ root = tmp_path / "checkout"+ root.mkdir()+ (root / "pyproject.toml").write_text('[project]\nversion="1.0"\n', encoding="utf-8")+ (root / "payload.txt").write_text("old", encoding="utf-8")+ archive = tmp_path / "source.zip"+ with zipfile.ZipFile(archive, "w") as out:+ out.writestr("hermes-agent-main/pyproject.toml", '[project]\nversion="2.0"\n')+ out.writestr("hermes-agent-main/payload.txt", "new")+ # Only redirect transport: extraction, staging, dirty recheck and swap run.+ monkeypatch.setattr("urllib.request.urlretrieve", lambda url, dst: urlretrieve(archive.as_uri(), dst))+ monkeypatch.setattr(main, "PROJECT_ROOT", root)+ events = []+ token = {"resume_needed": True, "profiles": {}, "unmapped": []}+ plan = UpdatePlan(install_method="git", expected_version="1.0", profiles=["default", "other"],+ runtimes=[RuntimeRecord(kind="serve", profile="default", pid=99999999,+ supervisor="manual-serve")])+ monkeypatch.setattr("hermes_cli.update_inventory.collect_runtime_inventory", lambda: plan)+ monkeypatch.setattr(main, "_pause_windows_gateways_for_update", lambda: token)+ monkeypatch.setattr("atexit.register", lambda *args: None)+ monkeypatch.setattr(main, "_desktop_packaged_executable", lambda root: None)+ monkeypatch.setattr(main, "_desktop_dist_exists", lambda root: False)+ monkeypatch.setattr(update_cmd, "_source_update_channel", lambda args: "main")- monkeypatch.setattr(maint, "_sweep_bytecode_after_update", lambda branch: None)++ monkeypatch.setattr(update_cmd, "_sweep_bytecode_after_update", lambda branch: None)++ def prepare(selected, *, desktop):+ assert selected == root and desktop is False+ assert (root / "payload.txt").read_text() == "new"+ events.append("prepare")+ # The pre-update snapshot must reach the real cron-loss safety net.+ jobs.write_text('{"jobs": []}', encoding="utf-8")- monkeypatch.setattr(maint, "_prepare_updated_checkout", prepare)++ monkeypatch.setattr("hermes_cli.source_build.build_update_products", prepare)+ # PM/builds and machine-level repair are independently covered. Keep real+ # config migration, profile env backfill, snapshot recovery and receipts.+ monkeypatch.setattr("hermes_cli.macos_tcc_anchor.ensure_tcc_anchor", lambda: None)+ monkeypatch.setattr(maint, "_print_post_update_notices_and_self_heals", lambda: None)+ monkeypatch.setattr(maint, "_print_bundled_skills_sync_report", lambda: None)+ monkeypatch.setattr("hermes_cli.profiles.seed_profile_skills", lambda *a, **kw: {})+ monkeypatch.setattr("plugins.memory.honcho.cli.sync_honcho_profiles_quiet", lambda: [])+ monkeypatch.setattr(update_cmd, "_reload_config_modules", lambda: None)+ monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None))+ monkeypatch.setattr(fleet, "_print_legacy_units_warning", lambda: None)+ monkeypatch.setattr(maint, "_refresh_dashboard_after_update", lambda **kwargs: None)+ monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])+ monkeypatch.setattr(fleet, "_collect_fleet_snapshot", lambda *args: [])+ monkeypatch.setattr("hermes_cli.gateway_migrate.maybe_auto_migrate_after_update", lambda: None)++ def resume(received):+ assert received is token+ assert token["resume_needed"], "completion must resume only once"+ token["resume_needed"] = False+ events.append("resume")+ monkeypatch.setattr(main, "_resume_windows_gateways_after_update", resume)+ monkeypatch.setattr(update_cmd, "_write_gateway_update_exit_code", lambda ok: events.append(("marker", ok)))++ def restart(received, gateway_mode):- assert received is plan++ assert received.to_dict() == plan.to_dict()+ events.append("restart")+ return fleet._GatewayRestartOutcome(+ incomplete=False, phase_errors=[], pre_restart_gateway_pids=[],+ restarted_services=[], failed_or_stale_units=[], relaunched_profiles=[],+ externally_supervised_profiles=[], killed_pids=set())+ monkeypatch.setattr(update_cmd, "_restart_gateway_fleet_after_update", restart)+ real_finalize = update_receipt.finalize_update_receipt++ def finalize(*args, **kwargs):+ events.append("finalize")+ return real_finalize(*args, **kwargs)+ monkeypatch.setattr(update_receipt, "finalize_update_receipt", finalize)+ yield SimpleNamespace(root=root, active=active, sibling=sibling, jobs=jobs,+ original_jobs=original_jobs, events=events, token=token, plan=plan)+ update_receipt._current.set(None)++[email protected]("route", ["direct", "git-failure"])[email protected]("gateway_mode", [False, True])+def test_zip_command_migrates_profiles_recovers_snapshot_and_verifies_fleet(+ zip_update, monkeypatch, route, gateway_mode, capsys,+):+ state = zip_update+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (route == "direct", ["git"], False))+ monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None)++ def fail_fetch(*args, **kwargs):+ raise subprocess.CalledProcessError(1, ["git", "fetch"])+ monkeypatch.setattr(update_cmd, "_git_run", fail_fetch)+ # Choose the fallback branch without pretending this host is Windows.+ monkeypatch.setattr(update_cmd, "_should_zip_fallback_on_update_error", lambda exc: True)+ update_cmd._cmd_update_impl(SimpleNamespace(branch="main", yes=True), gateway_mode)++ for profile in (state.active, state.sibling):+ config = hermes_yaml.safe_load((profile / "config.yaml").read_text())+ assert config["_config_version"] == DEFAULT_CONFIG["_config_version"]+ assert config["model"]["default"] == "retained-model"+ assert (state.sibling / ".env").read_bytes() == (state.active / ".env").read_bytes()+ assert json.loads(state.jobs.read_text()) == state.original_jobs+ assert (state.root / "payload.txt").read_text() == "new"+ assert "v1.0 → v2.0" in capsys.readouterr().out+ assert state.events == ["prepare", *([("marker", True)] if gateway_mode else []),+ "restart", "resume", "finalize"]+ receipt = json.loads((state.active / "logs/update_receipts/latest.json").read_text())+ assert receipt["outcome"] == "success"+ assert receipt["runtime_outcomes"][0]["outcome"] == "restarted"+ assert update_receipt._current.get() is None+ assert state.token["resume_needed"] is False+ assert not list(state.root.glob("*.hermes-update-*"))++[email protected]("verdict", ["healthy", "unsafe-sqlite", "stale-fleet"])- def test_zip_helper_preserves_bool_contract_after_real_verification(zip_update, monkeypatch, verdict):++def test_zip_helper_propagates_completion_status_after_real_verification(zip_update, monkeypatch, verdict):+ state = zip_update+ args = SimpleNamespace(branch="main", yes=True, gateway=True)+ plan = update_cmd._begin_update_receipt_and_plan(args)+ snapshot = main._run_pre_update_backup(args)+ if verdict == "unsafe-sqlite":+ monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (+ False, SimpleNamespace(sqlite_version_string="unsafe test runtime")))+ elif verdict == "stale-fleet":+ monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [+ {"pid": plan.runtimes[0].pid, "profile": "default"}])- result = update_cmd_zip._update_via_zip(- args, pre_update_snapshot_id=snapshot, _pre_update_plan=plan,- _windows_gateway_resume=state.token)- assert result is (verdict == "healthy")++ request = update_cmd._source_completion_request(++ update_cmd._resolve_update_options(args, True), plan, snapshot, state.token, False, True)++ if verdict == "healthy":++ assert update_cmd_zip._update_via_zip(args, completion_request=request) is True++ else:++ with pytest.raises(SystemExit) as error:++ update_cmd_zip._update_via_zip(args, completion_request=request)++ assert error.value.code == 1+ assert state.events == ["prepare", ("marker", verdict != "unsafe-sqlite"),+ "restart", "resume", "finalize"]+ receipt = json.loads((state.active / "logs/update_receipts/latest.json").read_text())+ assert receipt["outcome"] == ("success" if verdict == "healthy" else "partial")+ assert receipt["runtime_outcomes"][0]["outcome"] == (+ "unaccounted" if verdict == "stale-fleet" else "restarted")+ assert json.loads(state.jobs.read_text()) == state.original_jobs++[email protected]("route", ["direct", "git-failure"])[email protected]("failure", ["swap", "preparation"])+def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, monkeypatch, route, failure):+ import os+ import pm++ state = zip_update+ before = {profile: (profile / "config.yaml").read_bytes()+ for profile in (state.active, state.sibling)}+ old_project = (state.root / "pyproject.toml").read_bytes()+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (route == "direct", ["git"], False))+ monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None)+ monkeypatch.setattr(update_cmd, "_should_zip_fallback_on_update_error", lambda exc: True)++ def fail_fetch(*args, **kwargs):+ raise subprocess.CalledProcessError(1, ["git", "fetch"])+ monkeypatch.setattr(update_cmd, "_git_run", fail_fetch)+ installed = []+ if failure == "swap":+ rename = os.rename++ def fail_second_swap(src, dst):+ if str(src).endswith(".hermes-update-staging"):+ installed.append(dst)+ if len(installed) == 2:+ raise OSError("locked replacement")+ return rename(src, dst)+ monkeypatch.setattr(os, "rename", fail_second_swap)+ expected = SystemExit+ else:+ def fail_preparation(*args, **kwargs):+ assert (state.root / "payload.txt").read_text() == "new"+ raise pm.InstallError("venv", "preparation stopped")- monkeypatch.setattr(maint, "_prepare_updated_checkout", fail_preparation)++ monkeypatch.setattr("hermes_cli.source_build.build_update_products", fail_preparation)+ expected = pm.InstallError+ with pytest.raises(expected) as raised:+ update_cmd._cmd_update_impl(SimpleNamespace(branch="main", yes=True), gateway_mode=True)+ if failure == "swap":+ assert raised.value.code == 1+ assert len(installed) == 2+ assert (state.root / "pyproject.toml").read_bytes() == old_project+ assert (state.root / "payload.txt").read_text() == "old"+ assert state.events == ["resume"]+ assert state.token["resume_needed"] is False+ assert {profile: (profile / "config.yaml").read_bytes() for profile in before} == before+ assert not (state.sibling / ".env").exists()+ assert json.loads(state.jobs.read_text()) == state.original_jobs+ assert not (state.active / "logs/update_receipts/latest.json").exists()+ assert not list(state.root.glob("*.hermes-update-*"))diff --cc tests/hermes_cli/test_update_zip_symlink_reject.pyindex f82191fcd99,f82191fcd99..91a2a669f30--- a/tests/hermes_cli/test_update_zip_symlink_reject.py+++ b/tests/hermes_cli/test_update_zip_symlink_reject.py@@@ -49,6 -49,6 +49,7 @@@ def test_update_via_zip_rejects_symlinkfrom hermes_cli.update_cmd import _update_via_zipmonkeypatch.setattr(hermes_main, "PROJECT_ROOT", fake_root)++ monkeypatch.setattr(update_cmd, "_complete_source_update", lambda request: None)monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)args = type("Args", (), {})()@@@ -76,11 -76,11 +77,12 @@@# That's the contract: a malicious ZIP must fail the update, not# silently materialize a symlink.with pytest.raises(SystemExit) as exc_info:-- _update_via_zip(args)++ _update_via_zip(args, completion_request={})assert exc_info.value.code == 1# Belt: confirm extractall never produced the link.tmp_dir = captured.get("tmp_dir")++ assert tmp_dir is not None, "ZIP validation must run before refusal"if tmp_dir:evil_path = os.path.join(tmp_dir, "hermes-agent-main", "evil-link")assert not os.path.lexists(evil_path), (@@@ -109,6 -109,6 +111,7 @@@ def test_update_via_zip_accepts_normal_from hermes_cli import main as hermes_mainmonkeypatch.setattr(hermes_main, "PROJECT_ROOT", fake_root)++ monkeypatch.setattr(update_cmd, "_complete_source_update", lambda request: None)monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)args = type("Args", (), {})()@@@ -127,7 -127,7 +130,7 @@@patch("subprocess.check_call"):fake_run.return_value = type("R", (), {"returncode": 0, "stdout": "", "stderr": ""})()try:-- update_cmd._update_via_zip(args)++ update_cmd._update_via_zip(args, completion_request={})except SystemExit:passdiff --cc tests/pm/test_environment_build.pyindex 19e13384999,db9a0dafa60..e5a19a1f94a--- a/tests/pm/test_environment_build.py+++ b/tests/pm/test_environment_build.py@@@ -195,55 -215,59 +195,108 @@@ def test_group_only_build_excludes_applcwd=tmp_path, env=env) == "1.0"+def test_worker_sync_reuses_unions_and_reports_real_lock_drift(locked_project, build_worker, tmp_path, monkeypatch):+ import pm+ from hermes_cli.runtime_paths import selected_venv, runtime_facts_path+ from pm.lock import Facts, Lockfile+ from pm import paths++ source, _, env = locked_project+ manifest = source / "pyproject.toml"+ manifest.write_text(manifest.read_text().replace('[tool.uv.workspace]\nmembers=["member"]\n', ""), encoding="utf-8")+ monkeypatch.setattr(paths, "repo_root", lambda: source)+ pm.lock_project(source, offline=True, explicit=True)+ assert pm.check() == []+ parent_path, parent_env = list(sys.path), dict(os.environ)+ # The worker imports its own class; this trap affects only inline installs.+ monkeypatch.setattr("pm.packages.Venv.apply", lambda *a, **kw: pytest.fail("venv apply ran in caller"))++ pm.sync_venv(["chosen"], explicit=True, plugin_dirs=[])+ first = selected_venv(source)+ first_fact = Facts(runtime_facts_path(source)).get("venv")+ pm.sync_venv(["chosen"], explicit=True, plugin_dirs=[])+ assert selected_venv(source) == first+ assert Facts(runtime_facts_path(source)).get("venv") == first_fact+ assert _run([str(first / ("Scripts/python.exe" if os.name == "nt" else "bin/python")), "-I", "-c",+ "import base_dep, chosen_dep, importlib.util; assert importlib.util.find_spec('other_dep') is None; print(chosen_dep.__version__)"],+ cwd=tmp_path, env=env) == "1.0"++ pm.sync_venv(["other"], explicit=True, plugin_dirs=[])+ second = selected_venv(source)+ assert second != first+ assert Facts(runtime_facts_path(source)).get("venv")["extras"] == ["chosen", "other"]+ pm.sync_venv(["chosen"], explicit=True, plugin_dirs=[])+ assert selected_venv(source) == second+ assert _run([str(second / ("Scripts/python.exe" if os.name == "nt" else "bin/python")), "-I", "-c",+ "import chosen_dep, other_dep; print(chosen_dep.__version__, other_dep.__version__)"],+ cwd=tmp_path, env=env) == "1.0 1.0"+ assert pm.check() == []+ _wheel(tmp_path / "wheels", "base_dep", "1.1")+ manifest.write_text(manifest.read_text().replace("base-dep==1.0", "base-dep==1.1"), encoding="utf-8")+ pm.lock_project(source, offline=True, explicit=True)+ assert pm.check() == ["venv: out of sync with uv.lock"]+ lock = Lockfile(paths.lockfile_path())+ lock.set_pin("node", "fixture", {"any": {"url": "https://example.invalid/node", "sha256": "0" * 64}})+ lock.save()+ assert "node: not installed or outdated" in pm.check()+ assert selected_venv(source) == second+ assert list(sys.path) == parent_path and dict(os.environ) == parent_env+ assert not {"base_dep", "chosen_dep", "other_dep"} & sys.modules.keys()+++ @pytest.mark.parametrize("operation", ["sync", "requirements"])+ def test_build_backend_output_is_streamed_before_build_finishes(installable_project, tmp_path, operation):+ import io+ from pm.environment import PythonEnvironment++ source, uv, env = installable_project+ release = tmp_path / "release-build"+ stdout_marker = "construction-root: backend stdout"+ stderr_marker = "construction-root: backend stderr"+ backend = source / "local_backend.py"+ backend.write_text(backend.read_text() + f'''+ import sys+ import time++ original_build = build_wheel++ def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):+ print({stdout_marker!r}, flush=True)+ print({stderr_marker!r}, file=sys.stderr, flush=True)+ release = Path({str(release)!r})+ deadline = time.monotonic() + 10+ while not release.exists() and time.monotonic() < deadline:+ time.sleep(.01)+ assert release.exists(), "backend output was hidden until build exit"+ return original_build(wheel_directory, config_settings, metadata_directory)++ build_editable = build_wheel+ ''', encoding="utf-8")++ class AcknowledgingLog(io.StringIO):+ def write(self, text):+ written = super().write(text)+ if stdout_marker in self.getvalue() and stderr_marker in self.getvalue():+ release.touch()+ return written++ output = AcknowledgingLog()+ environment = PythonEnvironment(+ uv=uv, python=Path(sys.executable), destination=tmp_path / "built",+ cache=tmp_path / "build-cache", offline=True, output=output,+ env=dict(env, UV_NO_INDEX="1", UV_FIND_LINKS=str(tmp_path / "wheels")),+ )+ environment.create()+ if operation == "sync":+ environment.sync(source, timeout=30)+ else:+ environment.install_requirements([source.as_uri()])+ environment.check()+ assert release.is_file(), "both backend streams must arrive during the build"+ assert _run([str(environment.executable), "-I", "-c", "import root_app; print(root_app.VALUE)"],+ cwd=tmp_path, env=env) == "installed from the explicit source"++def test_child_output_is_live_and_keeps_explicit_index_credentials(tmp_path):import iofrom pm.environment import PythonEnvironmentdiff --cc tests/pm/test_startup_activation.pyindex ca200997479,00000000000..c61187e7747mode 100644,000000..100644--- a/tests/pm/test_startup_activation.py+++ b/tests/pm/test_startup_activation.py@@@ -1,114 -1,0 +1,122 @@@+"""Startup consumes one real PM verdict without activating a partial store."""++import importlib+import os+import sys+from pathlib import Path++import pytest++import pm+from pm import paths, registry+from pm.lock import Lockfile+from pm.packages import BinaryPackage+from tests.pm._fixtures import make_tar, served as served+++def checked_store(tmp_path, monkeypatch, served):+ engine = importlib.import_module("pm.ensure")+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "store"))+ monkeypatch.setattr(paths, "repo_root", lambda: tmp_path / "repo")+ monkeypatch.setattr(paths, "lockfile_path", lambda: tmp_path / "lock.json")+ monkeypatch.setattr(registry, "_packages", {})+ docroot, url = served+ lock = Lockfile(paths.lockfile_path())+ binaries = []+ for name in ("first", "second"):+ package = BinaryPackage()+ package.name = name+ package.probe_version = False+ package.binary_rel = {"posix": f"bin/{name}", "win32": f"bin/{name}"}+ registry._packages[name] = package+ archive, digest = make_tar(docroot, f"{name}.tar.gz", {f"bin/{name}": "fixture tool"})+ lock.set_pin(name, "1.0", {"any": {"url": f"{url}/{archive}", "sha256": digest}})+ lock.save()+ engine.ensure(name, explicit=True)+ installed = pm.installed_package(name)+ assert installed is not None and installed.binary is not None+ binaries.append(installed.binary)++ checks = []+ real_check = engine.check++ def counted_check():+ problems = real_check()+ checks.append(problems)+ return problems++ monkeypatch.setattr(engine, "check", counted_check)+ monkeypatch.setattr(pm, "check", counted_check)+ return binaries, checks+++def test_activate_returns_live_verdict_without_partial_environment(checked_store, monkeypatch):+ binaries, checks = checked_store+ original_path = os.environ["PATH"]+ monkeypatch.setenv("PATH", original_path)++ assert pm.activate() == []+ assert checks == [[]]+ active_path = os.environ["PATH"].split(os.pathsep)+ assert all(str(binary.parent) in active_path for binary in binaries)++ # A second invocation must observe fresh damage, even after healthy activation.+ monkeypatch.setenv("PATH", original_path)+ binaries[1].unlink()+ before = dict(os.environ)+ problems = pm.activate()+ assert problems == ["second: not installed or outdated"]+ assert checks == [[], problems]+ assert dict(os.environ) == before++[email protected]("surface", ["gateway", "cli"])[email protected]("damaged", [False, True])+def test_startup_uses_one_verdict(checked_store, monkeypatch, capsys, caplog, surface, damaged):+ binaries, checks = checked_store+ if surface == "gateway":- from gateway.run import _run_pm_startup- start = _run_pm_startup++ from gateway import run++++ async def started(*args, **kwargs):++ return True++++ monkeypatch.setattr(run, "start_gateway", started)++ monkeypatch.setattr(run, "_exit_after_graceful_shutdown", lambda code: None)++ monkeypatch.setattr("hermes_cli.boot_bootstrap.maybe_run_boot_bootstrap", lambda _root: None)++ monkeypatch.setattr(sys, "argv", ["gateway"])++ start = run.main+ else:+ from hermes_cli import main++ # Stop at --help: exercise the actual startup block, not an agent session.+ monkeypatch.setattr("hermes_cli.boot_bootstrap.maybe_run_boot_bootstrap", lambda _root: None)+ for name in ("_set_process_title", "_advertise_agent_env",+ "_sweep_stale_bytecode_if_checkout_changed",+ "_try_termux_fast_tui_launch", "_try_termux_fast_cli_launch",+ "_try_fast_serve_launch", "_try_fast_chat_launch"):+ monkeypatch.setattr(main, name, lambda: None)+ monkeypatch.setattr(sys, "argv", ["hermes", "--help"])++ def start():+ with pytest.raises(SystemExit) as exit_info:+ main.main()+ assert exit_info.value.code == 0++ if damaged:+ binaries[1].unlink()+ original_path = os.environ["PATH"]+ monkeypatch.setenv("PATH", original_path)+ start()++ expected = ["second: not installed or outdated"] if damaged else []+ assert checks == [expected]+ diagnostics = capsys.readouterr().err + caplog.text+ if damaged:+ assert os.environ["PATH"] == original_path+ assert "install out of sync (second: not installed or outdated)" in diagnostics+ else:+ assert all(str(binary.parent) in os.environ["PATH"].split(os.pathsep) for binary in binaries)+ assert "install out of sync" not in diagnosticsdiff --cc tests/pm/test_startup_recovery.pyindex a809a03b4fc,e46153fc4e9..5a752e6dcae--- a/tests/pm/test_startup_recovery.py+++ b/tests/pm/test_startup_recovery.py@@@ -39,8 -47,10 +47,10 @@@ def test_bootstrap_repairs_before_depenshutil.copytree(repo / "pm", core / "pm", ignore=shutil.ignore_patterns("__pycache__"))cli = core / "hermes_cli"cli.mkdir()+ # Include the real preimport protocol, including its ownership check. Do+ # not stub prepare_launch: the same files are also saved in PM's workspace.- for name in ("__init__.py", "runtime_paths.py", "runtime_state.py", "_early_recovery.py", "_parser.py",- "venv_sync.py", "steward.py"):+ for name in ("__init__.py", "runtime_paths.py", "runtime_state.py", "_early_recovery.py",+ "_parser.py", "venv_sync.py", "steward.py"):shutil.copy2(repo / "hermes_cli" / name, cli / name)wheels = tmp_path / "wheels"wheels.mkdir()diff --cc tests/pm/test_worker.pyindex 53dbe39c06c,8e8b046ea35..005b35bddfd--- a/tests/pm/test_worker.py+++ b/tests/pm/test_worker.py@@@ -177,34 -200,35 +170,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")++ (sibling / "plugin.yaml").write_text("name: dependency\npython_dependencies: [fixture-dep==1]\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])diff --cc tests/pm/test_worker_publication.pyindex 00000000000,fb05cda6551..3209f32dd9amode 000000,100644..100644--- a/tests/pm/test_worker_publication.py+++ b/tests/pm/test_worker_publication.py@@@ -1,0 -1,386 +1,388 @@@+ """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])+++ @pytest.mark.parametrize("active", [False, True])+ @pytest.mark.parametrize("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-*"))+++ @pytest.mark.parametrize("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()+++ @pytest.mark.parametrize("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")++ (candidate / "plugin.yaml").write_text("name: candidate\npython_dependencies: [fixture-dep==1]\n")+ _current_environment(tmp_path, monkeypatch, [candidate])+ assert client.venv_is_current(extra_plugin_dirs=[candidate])+ assert 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")++ (candidate / "plugin.yaml").write_text("name: provider\npython_dependencies: [fixture-dep==1]\n")+ monkeypatch.setattr("plugins.memory.find_provider_dir", lambda name: candidate)+ _, inputs = memory_provider_dependency_inputs("provider")+ assert inputs == {"extras": [], "extra_plugin_dirs": [candidate]}+++ @pytest.mark.parametrize(("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-*"))+++ @pytest.mark.parametrize("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")++ (sibling / "plugin.yaml").write_text("name: sibling\npython_dependencies: [fixture-dep==1]\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 / "plugin.yaml").write_text("name: example\npython_dependencies: [fixture-dep==1]\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"++ proposed = "name: sibling\nversion: changed\npython_dependencies: [fixture-dep==2]\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()++ from pm import plugins_state++++ read = plugins_state._read_home_config++ def concurrent_commit(home):++ stale = read(home)+ config.write_text("plugins: {enabled: [first], disabled: []}\n")+ return stale- monkeypatch.setattr(pc, "_get_enabled_set", concurrent_commit)++ monkeypatch.setattr(plugins_state, "_read_home_config", 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 --cc tests/pm/test_workspace_build_inputs.pyindex f315041e421,d2b094f630d..3752b19f5f0--- a/tests/pm/test_workspace_build_inputs.py+++ b/tests/pm/test_workspace_build_inputs.py@@@ -8,7 -8,7 +8,8 @@@ import syimport pytestfrom pm import workspace+from tests.pm import _fixtures+ from pm.environment import managed_environment@pytest.fixture(autouse=True)@@@ -119,10 -227,11 +212,11 @@@ def test_plugin_can_move_compatible_tramonkeypatch.setattr(workspace.paths, "repo_root", lambda: core)monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))baseline, first_env = tmp_path / "baseline", tmp_path / "first-env"- workspace.lock_and_sync([], [], root=baseline, venv_dir=first_env)+ workspace.lock_and_sync([], [], root=baseline, source=core, seed_lock=None,+ environment=managed_environment(first_env))first_lock = (baseline / "uv.lock").read_bytes()assert next(p["version"] for p in tomllib.loads(first_lock.decode())["package"] if p["name"] == "pkgb") == "1.2"- _wheel(wheels, "pkgb", "1.3")+ _fixtures._wheel(wheels, "pkgb", "1.3")plugin = tmp_path / "plugin"plugin.mkdir()(plugin / "pyproject.toml").write_text(diff --cc tests/test_source_launcher_stages.pyindex fd1d084af3f,19729a59718..36e79e548ce--- a/tests/test_source_launcher_stages.py+++ b/tests/test_source_launcher_stages.py@@@ -8,15 -9,54 +8,23 @@@ import subprocesimport pytestfrom hermes_cli.runtime_paths import install_state_dir, site_packages+ from pm.lock import Lockfile-from pm.store import current_targetfrom tests.hermes_cli.test_source_launcher_publication import fixture_treeROOT = Path(__file__).resolve().parents[1]-def bootstrap_inputs(repo):- # Both pre-Python readers need the real lock shape, including artifact- # objects (an empty inline {} does not exercise their brace tracking).[email protected]("windows")[email protected]("shell", ["powershell", "pwsh"])+def test_powershell_stage_publishes_without_a_checkout_venv(tmp_path, monkeypatch, shell):+ repo, home, interpreter = fixture_tree(tmp_path, monkeypatch)++ # Exercise the real pin reader, including the nested artifact objects.+ (repo / 'pm').mkdir()- for name in ('lock.json', 'artifact-mirror.json'):- shutil.copy2(ROOT / 'pm' / name, repo / 'pm' / name)- lock = Lockfile(repo / 'pm/lock.json')- uv_version, py_version = lock.version('uv'), lock.version('python')- assert uv_version and py_version- return uv_version, '.'.join(py_version.split('+')[0].split('.')[:2])---def shell_bootstrap(repo, home, interpreter):- uv_version, py_version = bootstrap_inputs(repo)- entry = home / 'tools' / f'uv-{uv_version}-{current_target()}'- entry.mkdir()++ shutil.copy2(ROOT / 'pm/lock.json', repo / 'pm/lock.json')++ pin = Lockfile(repo / 'pm/lock.json').version('python')++ assert pin++ py_version = '.'.join(pin.split('+')[0].split('.')[:2])+ calls = home / 'uv-calls'- uv = entry / ('uv.exe' if os.name == 'nt' else 'uv')- # Only acquisition is replaced: the real stages still parse the pin, run- # bootstrap Python, and invoke the unmodified shared launcher writer.- uv.write_text(- '#!/usr/bin/env bash\nset -eu\n'- f'printf \'%s\\n\' "$*" >> {shlex.quote(calls.as_posix())}\n'- 'case "$*" in\n'- f' --version) printf \'%s\\n\' "uv {uv_version}" ;;\n'- f' "python install --no-bin {py_version}") test -x {shlex.quote(interpreter.as_posix())} ;;\n'- f' "python find --managed-python {py_version}") printf \'%s\\n\' {shlex.quote(interpreter.as_posix())} ;;\n'- ' *) printf \'unexpected bootstrap uv call: %s\\n\' "$*" >&2; exit 91 ;;\n'- 'esac\n', encoding='utf-8',- )- uv.chmod(0o755)- # Fail closed if a fixture regression tries the installer's download path.- curl = entry / 'curl'- curl.write_text('#!/usr/bin/env bash\necho "unexpected bootstrap download" >&2\nexit 91\n',- encoding='utf-8')- curl.chmod(0o755)- return entry, calls, [f'python install --no-bin {py_version}',- f'python find --managed-python {py_version}']---def selected_environment(repo, value=11):selected = install_state_dir(repo) / 'environments/ready/venv'site = site_packages(selected)site.mkdir(parents=True)@@@ -40,13 -189,14 +63,16 @@@ Stage-Patif (-not $script:publishedPath) { throw 'registry-publication seam was bypassed' }exit 0''', encoding='utf-8-sig')- powershell = Path(os.environ['SystemRoot']) / 'System32/WindowsPowerShell/v1.0/powershell.exe'+ powershell = (Path(os.environ['SystemRoot']) / 'System32/WindowsPowerShell/v1.0/powershell.exe'+ if shell == 'powershell' else Path(shutil.which('pwsh') or pytest.fail('native lane requires PowerShell 7')))env = dict(os.environ, PROBE_INSTALLER=str(ROOT / 'scripts/install.ps1'),- PROBE_REPO=str(repo), PROBE_HOME=str(home), HERMES_HOME=str(tmp_path / 'other-home'),- PROBE_PY_VERSION=py_version, PROBE_PYTHON=str(interpreter), PROBE_UV_CALLS=str(calls),+ PROBE_REPO=str(repo), PROBE_HOME=str(home), PROBE_PYTHON=str(interpreter),- HERMES_HOME=str(tmp_path / 'other-home'), UV_OFFLINE='1', UV_PYTHON_DOWNLOADS='never')++ HERMES_HOME=str(tmp_path / 'other-home'),++ PROBE_PY_VERSION=py_version, PROBE_UV_CALLS=str(calls),+ UV_OFFLINE='1', UV_PYTHON_DOWNLOADS='never')env['PATH'] = os.pathsep.join([str(powershell.parent), str(Path(os.environ['SystemRoot']) / 'System32')])env['PATHEXT'] = '.COM;.EXE;.BAT;.CMD'+ env.pop('UV_PYTHON_INSTALL_DIR', None)result = subprocess.run([str(powershell), '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', str(wrapper)],cwd=tmp_path, env=env, capture_output=True, timeout=90)assert result.returncode == 0, result.stdout + result.stderrdiff --cc website/docs/reference/package-management.mdindex 4bd9bc2f809,0dfd1fe5bef..c075fa6ef0a--- a/website/docs/reference/package-management.md+++ b/website/docs/reference/package-management.md@@@ -33,19 -33,23 +33,24 @@@ loading application dependencies. Faileretry on the next launch; no pending-update marker is required. Developer checkoutsand packaged installations retain their existing owner.-Historical updaters can still be executing old Python code after swapping in this-source tree. Their retired helper names are inert compatibility shims; dependency-entry shims stop the old updater cleanly and ask for a relaunch instead of invoking-PM or falling back to pip. Completion belongs to the new launcher, not that mixed-old-code/new-files process.+Historical updaters can still execute old Python code after replacing the source+tree. Compatibility entry points start a fresh child, wait for completion, and+return its exit status. The child bootstrap asks PM to provision required tools+and select the Python generation before application imports. Completion runs in+that interpreter with the update context and receipt. The parent does not clear+`sys.modules`, import the new application graph, or resume a pip fallback.- Current source updates use one PM sync for the recorded extras and enabled- plugins, then build frontend products in a fresh process on the selected- Python. A retry on an already-current checkout follows the same path.- Dependency or build failures stop completion; the updater does not retry- through pip, reinstall providers separately, or create incomplete markers.- Use `hermes pm repair` for damaged dependency files.+ Current source updates hand the selected checkout to a fresh completion owner.+ Its bootstrap Python disables site-package initialization before asking PM to+ sync the recorded extras and enabled plugins. The selected Python then owns+ frontend builds, profile/configuration maintenance, gateway restarts and runtime+ verification. Git, already-current retries and ZIP fallback use this same path.+ The original command keeps the update lock while waiting; a missing or failed+ completion result cannot report success. Correlated PM failures remain in the+ update receipt, and interrupted restarts retain their fleet obligation.+ Dependency or build failures never retry through pip or a source re-download.+ Use `hermes pm repair` for damaged dependency files. See the developer+ [source completion ownership note](https://github.com/NousResearch/hermes-agent/blob/main/docs/source-update-completion.md).## Source installs and packaged builds@@@ -118,13 -114,21 +123,23 @@@ membership, and currency checks use thPM prepares core requirements, enabled extras, and enabled plugin requirementstogether. It seeds resolution from the existing lock. Compatible transitiveversions can change, but declared constraints and exact pins remain binding.- The generated workspace and extended lock remain outside shipped source.+ Each candidate gets a fresh workspace with explicit source, lock seed, and+ prepared environment inputs. The generated workspace and extended lock remain+ outside shipped source. Repair copies the recorded workspace and lock, including+ plugin 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 silently-disable other plugins. If preparation succeeds, a restart can still be required-to activate the new environment in a running Hermes process.+Plugin selection changes, including pack enables, use the same admission+transaction. PM reads the latest selection under its shared lock before applying+each change. A failed candidate does not replace the selected environment or+silently disable other plugins. If preparation succeeds, a running Hermes process+can still require a restart to activate the new environment.Ordinary Hermes application updates preserve user plugin directories. Explicitplugin updates can change the selected plugin's files. A wrapper with no Python