The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(boot): converge runtime checks and launcher maintenance
ethernet1686e54d4f5b
diff --git a/gateway/run.py b/gateway/run.pyindex 35ab82ca1a8..41b9fbae98e 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -1503,28 +1503,6 @@ os.environ["_HERMES_GATEWAY"] = "1"_ensure_ssl_certs()-# pm startup: same contract as the CLI dispatch path (hermes_cli/main.py)-# — the gateway daemon never passes through the CLI fast-launch checks, so-# the store's tools (git/bash/ffmpeg/...) must be on PATH here. O(1) stamp-# checks, no network, no installs; warns, never blocks. Runs from main(),-# not import time: importers of this module (relay runtime, platform-# actions, enrollment) need helpers, not PATH provisioning or a pm verdict-# on their behalf.-def _run_pm_startup() -> None:- try:- import pm-- pm.adopt()- problems = pm.check()- if problems:- logging.getLogger("gateway.run").warning(- f"install out of sync ({'; '.join(problems)}) — run `hermes pm install`"- )- else:- pm.activate()- except Exception:- logging.getLogger("gateway.run").debug("pm startup check failed", exc_info=True)-sys.path.insert(0, str(Path(__file__).parent.parent))from hermes_constants import get_hermes_home, get_hermes_home_override@@ -5400,7 +5378,15 @@ def main():# the post-update bootstrap: the same one-pass record-gated maintenance# registry the CLI dispatch path runs (hermes_cli/main.py) — this# entrypoint bypasses that dispatch, so run it here too. Never raises.- _best_effort(_run_pm_startup)+ try:+ from hermes_cli.boot_bootstrap import default_project_root+ from hermes_cli.venv_sync import check_runtime++ problem = check_runtime(default_project_root())+ if problem:+ logger.warning(problem)+ except Exception:+ logger.debug("pm startup check failed", exc_info=True)try:from hermes_cli.boot_bootstrap import (default_project_root,diff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.pyindex 7c8d0816263..3113106456b 100644--- a/hermes_cli/_launchers.py+++ b/hermes_cli/_launchers.py@@ -247,14 +247,66 @@ def _launcher_script(name: str, repo_root: Path, dependencies: Path | None) -> s)-def _mint_shell_launcher(name: str, out_dir: Path, python_exe: Path, script: str) -> Path | None:- command = shlex.join([str(python_exe), "-I", "-c", script])+def _write_shell(target: Path, command: list[str]) -> Path | None:+ body = f'#!/bin/sh\nexec {shlex.join(command)} "$@"\n'+ try:+ if not target.is_symlink() and target.read_text(encoding="utf-8") == body:+ if os.access(target, os.X_OK):+ return target+ except (OSError, UnicodeError):+ passdef write(staging: Path) -> None:- staging.write_text(f'#!/bin/sh\nexec {command} "$@"\n', encoding="utf-8", newline="\n")+ staging.write_text(body, encoding="utf-8", newline="\n")staging.chmod(0o755)- return _write_atomic(out_dir / name, write)+ return _write_atomic(target, write)+++def _mint_shell_launcher(name: str, out_dir: Path, python_exe: Path, script: str) -> Path | None:+ return _write_shell(out_dir / name, [str(python_exe), "-I", "-c", script])+++def _owns_launcher(target: Path, root: Path) -> bool:+ """Recognize our old source/venv launchers, never a mere mention in a comment."""+ if target.is_symlink():+ return target.resolve().is_relative_to(root)+ try:+ tokens = shlex.split(target.read_text(encoding="utf-8-sig"), comments=True)+ except (OSError, UnicodeError, ValueError):+ return False+ paths = {str(root / p) for p in (+ "hermes", "run_agent.py", "venv/bin/python", "venv/bin/python3",+ ".hermes/bin/hermes", ".hermes/bin/hermes-acp",+ )}+ # Current store launchers pass this Python bootstrap as one shell argument.+ bootstrap = f"sys.path.insert(0, {str(root)!r})"+ if paths.intersection(tokens) or any(bootstrap in token for token in tokens):+ return True+ # The historical updater wrote ACP as a sibling-hermes forwarder. Adopt+ # it only when that sibling demonstrably belongs to this installation.+ if target.name == "hermes-acp":+ sibling = target.with_name("hermes")+ return (tokens == ["exec", str(sibling), "acp", "$@"]+ and _owns_launcher(sibling, root))+ return False+++def _publish_conveniences(root: Path, out_dir: Path, names) -> dict[Path, bool]:+ """User-bin commands forward to durable local launchers, not a Python pin."""+ out_dir.mkdir(parents=True, exist_ok=True)+ published = {}+ for name in names:+ target = out_dir / name+ if (target.exists() or target.is_symlink()) and not _owns_launcher(target, root):+ continue+ before = target.lstat().st_mtime_ns if target.exists() or target.is_symlink() else None+ command = ([str(root / ".hermes/bin/hermes"), "--run-module", "run_agent"]+ if name == "hermes-agent" else [str(root / ".hermes/bin" / name)])+ if _write_shell(target, command) is None:+ raise OSError(f"could not publish launcher {target}")+ published[target] = before != target.lstat().st_mtime_ns+ return publisheddef stage_launcher(name: str, repo_root: Path, out_dir: Path) -> Path | None:@@ -275,23 +327,128 @@ def stage_launcher(name: str, repo_root: Path, out_dir: Path) -> Path | None:def ensure_install_launchers(repo_root: Path, out_dir: Path) -> list[str]:- """Publish exact-install commands and their user-bin conveniences.+ """Publish exact-install commands; conveniences follow them across Python repins."""+ root = Path(repo_root).resolve()+ local = root / ".hermes" / "bin"+ local.mkdir(parents=True, exist_ok=True)+ written = [str(path) for name in WINDOWS_BIN_LAUNCHERS+ if (path := stage_launcher(name, root, local)) is not None]+ if Path(out_dir).resolve() == local:+ return written+ if len(written) != len(WINDOWS_BIN_LAUNCHERS):+ return []+ if not _is_windows():+ return [str(path) for path in _publish_conveniences(root, Path(out_dir), WINDOWS_BIN_LAUNCHERS)]+ Path(out_dir).mkdir(parents=True, exist_ok=True)+ return [str(path) for name in WINDOWS_BIN_LAUNCHERS+ if (path := stage_launcher(name, root, Path(out_dir))) is not None]+++def expose_cli(project_root: Path | None = None) -> dict:+ """Repair PATH conveniences without taking over another installation's files.- Installers/updaters use the local command, since a shared HOME/bin may- have been repointed to another checkout. Return the requested outputs.+ macOS CLI-first launches link the bundle's signed shims directly; Electron+ need not have run. Source installs converge on the store launcher owner.+ Shell rc/PATH registration remains installer-owned."""- repo_root = Path(repo_root)- local = repo_root / ".hermes" / "bin"- local.mkdir(parents=True, exist_ok=True)+ if _is_windows():+ return {"ok": True, "skipped": "windows-installer-owned"}+ try:+ from hermes_cli.config import load_config+ except ImportError:+ # The explicit PM bootstrap publishes Python before application deps.+ # Installers will expose it after sync; never invent a config reader here.+ return {"ok": True, "skipped": "config-unavailable"}+ from hermes_cli.steward import read_install_stamp++ cli_cfg = (load_config() or {}).get("cli", {})+ if isinstance(cli_cfg, dict) and not cli_cfg.get("expose_on_path", True):+ return {"ok": True, "skipped": "config-disabled"}+ root = Path(project_root or os.environ.get("HERMES_INSTALL_ROOT") or Path(__file__).resolve().parents[1]).resolve()+ if _is_bundled_payload(root):+ if sys.platform == "darwin":+ return _symlink_sealed_launchers(root.parent / "bin")+ return {"ok": True, "skipped": "bundle-owns-launchers"}+ if read_install_stamp(root).get("updateMechanism") == "external":+ return {"ok": True, "skipped": "externally-owned"}+ if resolve_store_python(root) is None:+ return {"ok": True, "skipped": "no-store-python"}+ try:+ local = root / ".hermes" / "bin"+ if len(ensure_install_launchers(root, local)) != len(WINDOWS_BIN_LAUNCHERS):+ return {"ok": False, "error": "source launcher publication failed"}+ dirs = [Path.home() / ".local" / "bin"]+ # Repair existing FHS/custom-home exposure, but never create new global+ # entries or reclaim a convenience that was repointed to another root.+ from hermes_constants import get_default_hermes_root+ for directory in (get_default_hermes_root() / "bin", Path("/usr/local/bin")):+ if directory not in dirs and _owns_launcher(directory / "hermes", root):+ dirs.append(directory)+ written = []+ for directory in dirs:+ published = _publish_conveniences(root, directory, (*WINDOWS_BIN_LAUNCHERS, "hermes-agent"))+ written.extend(path.name for path, changed in published.items() if changed)+ return {"ok": True, "written": written}+ except OSError as exc:+ return {"ok": False, "error": str(exc)}+++def _is_bundled_payload(root: Path) -> bool:+ """Is ``root`` a desktop bundle's agent payload? The stamp is the+ authority (payload marker / desktop-app distribution), never a+ sibling-directory sniff; a .git tree is a dev checkout regardless."""+ if (root / ".git").exists():+ return False+ from hermes_cli.steward import STEWARD_DESKTOP, read_install_stamp++ stamp = read_install_stamp(root)+ if not stamp:+ return False+ return bool(stamp.get("payload")) or stamp.get("distribution") == STEWARD_DESKTOP+++def _symlink_sealed_launchers(payload_bin) -> dict:+ """Link ~/.local/bin/{hermes,hermes-agent,hermes-acp} at a sealed+ bundle's own prebuilt shims (macOS only).++ Symlinks, not copies: the shims are signed as part of the app bundle,+ and a copy would both orphan the signature's context and go stale on+ every app update — a symlink into the .app follows the bundle's+ content wherever Squirrel.Mac swaps it.++ Ownership guard mirrors expose_cli's wrapper logic: an existing+ entry is replaced only when it is ours — a symlink into THIS app+ bundle's payload — or missing/broken. A user's own `hermes` (pipx,+ another checkout's wrapper) is never touched.+ """+ link_dir = Path.home() / ".local" / "bin"+ payload_root = payload_bin.parentwritten: list[str] = []- for name in WINDOWS_BIN_LAUNCHERS:- if Path(out_dir).resolve() != local.resolve():- if stage_launcher(name, repo_root, local) is None:+ try:+ link_dir.mkdir(parents=True, exist_ok=True)+ for name in ("hermes", "hermes-agent", "hermes-acp"):+ source = payload_bin / name+ if not source.is_file():continue- path = stage_launcher(name, repo_root, Path(out_dir))- if path is not None:- written.append(str(path))- return written+ target = link_dir / name+ if target.is_symlink():+ current = os.readlink(target)+ if current == str(source):+ continue # already ours and current+ # Ours if it points into this payload (stale app path from+ # a previous version counts — resolve() of a dangling link+ # still yields the old path text) — or dangling entirely.+ points_into_payload = str(Path(current)).startswith(str(payload_root) + os.sep)+ if not points_into_payload and target.exists():+ continue # a live foreign link — user's arrangement+ elif target.exists():+ continue # a real file we did not write — never clobber+ target.unlink(missing_ok=True)+ target.symlink_to(source)+ written.append(name)+ except OSError as exc:+ return {"ok": False, "error": str(exc)}+ return {"ok": True, "written": written, "mode": "sealed-symlinks"}if __name__ == "__main__":diff --git a/hermes_cli/boot_bootstrap.py b/hermes_cli/boot_bootstrap.pyindex 0b0ef9f5ac8..4caa8530c6b 100644--- a/hermes_cli/boot_bootstrap.py+++ b/hermes_cli/boot_bootstrap.py@@ -1,44 +1,18 @@-"""Boot-time post-update bootstrap.--Every install kind (git checkout, desktop bundled payload, docker, nix)-compares two per-install facts at boot:--* current identity — the commit this install IS: ``install-stamp.json``- for sealed trees, git HEAD for checkouts. Reading it is a couple of- file reads (plus one rev-parse for checkouts).-* last-known identity — the commit this install last bootstrapped,- recorded under ``installs/<sha16>/bootstrap/`` keyed by the canonical- install root.--Equal → nothing happens (the fast path, ~2 ms). Different → run the-idempotent post-update steps from ``hermes_cli.post_update`` under a-single-flight lock, then record the new identity.--Two records, one per step scope:--* home record — ``bootstrap/<profile>.json``. Gates home-scoped steps.- HERMES_HOME moves per profile, so each profile bootstraps its own- state once per code change.-* machine record — ``bootstrap/machine.json``. Every profile resolves- the same file, so machine-global steps run once per machine per code- change and the record's lock serializes concurrent profile boots.--The records are an optimization, never the correctness layer: every step-is idempotent and self-gating, so a deleted record costs one redundant-slow path, nothing more.--Ported from the restack branch's boot_bootstrap, rewritten onto this-branch's vocabulary: stamps via ``hermes_cli.steward``, managed tools via-``pm`` (facts.json ledger) instead of the retired ``installation`` package.+"""Bounded home maintenance after an installed revision changes.++A per-install, per-profile record and lock remain because config migrations+must not retry a broken migration on every launch, and the full SQLite+integrity guard is too expensive to run every time. Steps still own their+idempotence and rollback; failure is recorded until the next revision (or+an explicit post-update run). PM owns runtime diagnosis, not this record."""from __future__ import annotations-from hermes_cli.runtime_paths import install_state_dir, installs_root+from hermes_cli.runtime_paths import install_state_dirimport jsonimport loggingimport osimport subprocess-import sysimport timefrom pathlib import Path@@ -137,147 +111,12 @@ def current_install_identity(project_root: Path) -> str | None:# the per-install state folder: installs/<SHA16>/ under the DEFAULT home# ----------------------------------------------------------------------------def ensure_install_dir(project_root: Path) -> Path:- """The state folder, created with its identity record on first touch.-- install.json is the REVERSE map (sha16 → canonical root) that makes- orphan GC possible: `hermes doctor` enumerates installs/*/install.json- and flags entries whose recorded root no longer exists. Written once,- under the same single-flight lock the records use; the steward comes- from hermes_cli.steward so the record says who owns the tree, not who- touched it first.- """- state = install_state_dir(project_root)- marker = state / "install.json"- if marker.is_file():- return state- state.mkdir(parents=True, exist_ok=True)- lock = _RecordLock(state / ".install-json.lock")- if not lock.acquire():- return state # someone else is writing it right now — theirs wins- try:- if not marker.is_file():- from datetime import datetime, timezone-- from hermes_cli.steward import sealed_steward-- steward = sealed_steward(Path(project_root))- payload = {- "root": str(Path(project_root).resolve()),- "steward": steward if steward is not None else "checkout",- "firstSeen": datetime.now(timezone.utc).isoformat(),- }- tmp = marker.with_suffix(".json.tmp")- tmp.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")- os.replace(tmp, marker)- finally:- lock.release()- return state+def record_path(project_root: Path) -> Path:+ """Each profile completes its own home maintenance for this installation."""+ from hermes_cli.profiles import get_active_profile_name--def orphaned_installs() -> list[tuple[Path, str]]:- """State folders whose recorded root no longer exists.-- ``(folder, recorded_root)`` pairs for `hermes doctor`'s sweep. A- folder without a readable install.json is orphaned by definition —- nothing can ever claim it again, because claiming goes through- ensure_install_dir which writes the record first.- """- root = installs_root()- if not root.is_dir():- return []- orphans: list[tuple[Path, str]] = []- for entry in sorted(root.iterdir()):- if not entry.is_dir():- continue- try:- recorded = json.loads(- (entry / "install.json").read_text(encoding="utf-8-sig")- ).get("root", "")- except (OSError, ValueError):- orphans.append((entry, "<unreadable install.json>"))- continue- if not recorded or not Path(recorded).exists():- orphans.append((entry, recorded or "<empty>"))- return orphans---def orphaned_store_entries() -> list[tuple[Path, int]]:- """Tool-store entries the installed-state ledger no longer references.-- ``(entry_dir, size_bytes)`` pairs for `hermes doctor`'s sweep. pm's- facts.json is the only authority consulted — the same ledger- ``pm.ensure`` resolves by, so this can never flag an entry pm would- still hand out. An entry is REFERENCED when facts records it (tool- entries) or when it is a ``fetch-*`` archive cache entry backing a- referenced install. Everything else is bytes no lookup can ever- return: superseded versions left behind by pin bumps.-- Doubt errs toward KEEP: a facts file that exists but cannot be read- aborts the whole sweep (empty result), because its references are- unknowable and any entry might be one of them. No facts file at all- means pm never installed anything — nothing is referenced, but there- is also nothing to GC against, so the sweep reports nothing.- """- from pm import paths as pm_paths- from pm.lock import Facts-- store = pm_paths.store_root()- if not store.is_dir():- return []- facts_file = pm_paths.facts_path()- if not facts_file.is_file():- return []- try:- raw = json.loads(facts_file.read_text(encoding="utf-8-sig"))- if not isinstance(raw, dict):- return []- except (OSError, ValueError):- # Unreadable ledger: references unknowable — keep everything.- return []- referenced = Facts(facts_file).entries_in_use()-- orphans: list[tuple[Path, int]] = []- for entry in sorted(store.iterdir()):- # Scratch dirs (.staging-*), the ledger itself, and stray files- # are pm's own cleanup problem, never GC candidates. fetch-*- # archive cache entries are content-addressed and cheap to keep;- # skip them too (re-fetch avoidance is their whole point).- if not entry.is_dir() or entry.name.startswith("."):- continue- if entry.name.startswith("fetch-"):- continue- if entry.name in referenced:- continue- size = 0- for f in entry.rglob("*"):- try:- if f.is_file() and not f.is_symlink():- size += f.stat().st_size- except OSError:- continue- orphans.append((entry, size))- return orphans---def record_path(project_root: Path, scope: str) -> Path:- """Where the last-known record for ``project_root`` lives.-- Both scopes live INSIDE the per-install state folder:- ``bootstrap/machine.json`` for machine scope, ``bootstrap/<profile>.json``- for home scope — the per-profile semantics ride the FILENAME, not a- per-profile anchor directory.- """- if scope == "home":- from hermes_cli.profiles import get_active_profile_name-- name = get_active_profile_name() or "default"- filename = f"{name}.json"- elif scope == "machine":- filename = "machine.json"- else:- raise ValueError(f"unknown record scope: {scope!r}")- return install_state_dir(project_root) / "bootstrap" / filename+ name = get_active_profile_name() or "default"+ return install_state_dir(project_root) / "bootstrap" / f"{name}.json"def read_last_known(path: Path) -> dict:@@ -301,19 +140,13 @@ def _write_record(path: Path, identity: str, results: dict) -> None:os.replace(tmp, path)-def write_record(project_root: Path, scope: str, identity: str, results: dict | None = None) -> None:- """Record ``identity`` as bootstrapped. Also used by the update phase- after it runs the steps itself, so the next boot skips."""- _write_record(record_path(project_root, scope), identity, results or {})---def needs_bootstrap(project_root: Path, scope: str) -> str | None:+def needs_bootstrap(project_root: Path) -> str | None:"""The new identity when this install changed since its last bootstrap,else None. None identity (broken tree) never bootstraps."""identity = current_install_identity(project_root)if not identity:return None- known = read_last_known(record_path(project_root, scope))+ known = read_last_known(record_path(project_root))if known.get("identity") == identity:return Nonereturn identity@@ -391,89 +224,27 @@ class _RecordLock:# the boot entry point# ----------------------------------------------------------------------------def _report_sealed_runtime_drift(project_root: Path) -> str | None:- """Check a SEALED tree's managed tools against pm's lockfile, loudly.-- pm's artifact-time gates (bundle staging, docker build, nix check)- are the wall; this is the boot-time backstop for artifacts assembled- around them: every boot of a drifted sealed tree prints the problem- list to stderr, so the drift is impossible to not-know about.-- Report, not refusal: this runs inside the never-raises boot path, and- a sealed gateway that boots on stale tools is degraded — but a- gateway that refuses to boot over a tool version is DOWN, remotely,- with the fix (rebuild the artifact) out of the machine's own reach.-- Returns the message when drift was found (for the boot summary), None- otherwise. Checkouts return None without reading anything — they- provision on demand and drift is their normal, self-healing state.- """- root = Path(project_root)- if (root / ".git").exists():- return None- try:- from hermes_cli.steward import sealed_steward-- steward = sealed_steward(root)- if steward is None:- return None- import pm-- problems = pm.check()- except Exception as exc: # noqa: BLE001 — a backstop must not become a gate- logger.debug("sealed runtime drift check failed: %s", exc)- return None- if not problems:- return None- message = (- f"this {steward}-managed install's tools drifted from its pin table: "- + "; ".join(problems)- + " — rebuild the artifact to fix"- )- print(f"\n✗ {message}\n", file=sys.stderr)- return message--def run_boot_bootstrap(project_root: Path) -> dict:- """Run due home- and machine-scoped steps for this install. Returns a- summary dict (for tests/logs); use maybe_run_boot_bootstrap at call- sites."""+ """Bound home maintenance to one attempt per installed revision."""from hermes_cli import post_update- summary: dict = {"home": "skipped", "machine": "skipped"}-- drift_message = _report_sealed_runtime_drift(Path(project_root))- if drift_message:- summary["sealed_runtime_drift"] = drift_message-- for scope, steps in (- ("home", post_update.BOOT_HOME_STEPS),- ("machine", post_update.BOOT_MACHINE_STEPS),- ):- identity = needs_bootstrap(project_root, scope)- if not identity:- continue- record = record_path(project_root, scope)- lock = _RecordLock(record)- if not lock.acquire():- summary[scope] = "lost-race"- continue- try:- # Double-check under the lock: the previous holder may have- # finished between our read and our acquire.- if read_last_known(record).get("identity") == identity:- summary[scope] = "done-by-other"- continue- logger.info(- "post-update bootstrap (%s scope): code changed to %s, running steps",- scope, identity[:12],- )- results = post_update.run_steps(steps)- _write_record(record, identity, results)- summary[scope] = results- finally:- lock.release()- return summary+ identity = needs_bootstrap(project_root)+ if not identity:+ return {"home": "skipped"}+ record = record_path(project_root)+ lock = _RecordLock(record)+ if not lock.acquire():+ return {"home": "lost-race"}+ try:+ # A previous holder may have finished after our first read.+ if read_last_known(record).get("identity") == identity:+ return {"home": "done-by-other"}+ logger.info("home maintenance: code changed to %s, running steps", identity[:12])+ results = post_update.run_steps(post_update.BOOT_HOME_STEPS)+ _write_record(record, identity, results)+ return {"home": results}+ finally:+ lock.release()def maybe_run_boot_bootstrap(project_root: Path) -> None:diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex a2ea0df684f..589aa6ad2ce 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -3397,6 +3397,19 @@ def main():from hermes_cli.boot_bootstrap import default_project_root, maybe_run_boot_bootstrapmaybe_run_boot_bootstrap(default_project_root())+ # Every dispatch, including fast chat/serve, gets one passive PM verdict.+ try:+ from hermes_cli.boot_bootstrap import default_project_root+ from hermes_cli.venv_sync import check_runtime++ problem = check_runtime(default_project_root())+ if problem:+ print(f"⚠ {problem}", file=sys.stderr)+ except Exception:+ import logging++ logging.getLogger(__name__).debug("pm startup check failed", exc_info=True)+if _try_termux_fast_tui_launch():returnif _try_termux_fast_cli_launch():@@ -3406,27 +3419,6 @@ def main():if _try_fast_chat_launch():return- # The startup check: O(1) stamp comparisons, no network, no installs.- # One loud line when the install is damaged; never blocks the command.- # Then provision: prepend the store's tool dirs to PATH so reactive- # which('git'|'bash'|'ffmpeg'|...) resolves the bundled binaries.- try:- import pm-- pm.adopt()- problems = pm.check()- if problems:- print(- f"⚠ install out of sync ({'; '.join(problems)}) — run `hermes pm install`",- file=sys.stderr,- )- else:- pm.activate()- except Exception:- import logging-- logging.getLogger(__name__).debug("pm startup check failed", exc_info=True)-parser, subparsers = _build_cli_parser()# NixOS container mode routes ALL invocations into the managed container.diff --git a/hermes_cli/post_update.py b/hermes_cli/post_update.pyindex 3eac173365c..776cacf9e2b 100644--- a/hermes_cli/post_update.py+++ b/hermes_cli/post_update.py@@ -1,29 +1,21 @@-"""Post-update maintenance steps shared by ``hermes update`` and boot bootstrap.+"""Home maintenance shared by explicit updates and bounded boot maintenance.-Each step operates on user state (config.yaml, skills, state.db) or machine-state (managed tools), never on the install tree. Every step is idempotent-and self-gating: running it twice, or from two installs that share one-HERMES_HOME, converges. The caller (boot_bootstrap, update_cmd) decides WHEN-steps run; this module owns WHAT they do.--Steps declare a scope:--* ``home`` — mutates the active HERMES_HOME (per profile).-* ``machine`` — machine-global state shared by every profile.--The scopes must match the record that gates them in ``boot_bootstrap``-(home record vs machine record).+Config migration owns backup/rollback; skills sync owns content merging; the+SQLite guard detects damage without repairing it. Boot bounds these home+steps per revision. The explicit scope CLI also provisions runtimes through+PM. Launcher publication belongs to hermes_cli._launchers."""from __future__ import annotationsimport loggingimport osimport shutil-import sysfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Iterable+from hermes_cli._launchers import expose_cli+logger = logging.getLogger(__name__)@@ -245,38 +237,27 @@ def step_adopt_blessed_checkout(project_root: Path | None = None) -> dict:def step_provision_runtimes() -> dict:- """Refresh managed tools (node, uv, git, gh, ripgrep, the venv) against- pm's lockfile after a code change.-- ``pm.check()`` is the cheap verdict: stamp comparisons of the- installed-state ledger against pm/lock.json, no network. Anything it- names is re-ensured through the same ``pm.ensure``/``pm.sync_venv``- calls every other install path uses — pm stays the single authority- on tool versions (a pin bump rides in exactly like node or ripgrep;- cua-driver gets no bespoke refresh step for the same reason).-- ``explicit=True`` because reaching this step IS the deliberate remedy- (the code just changed under this install — the same trust `hermes- update` carries); the lazy-install policy still gates the whole sweep- so a policy-locked machine skips instead of installing.+ """Explicit refresh of PM's drifted packages; never selected by boot.++ PM supplies package identities, not diagnostic text to parse. Its own+ ensure/sync operations own freshness checks and publication under lock."""import pmfrom pm.ensure import lazy_installs_allowed, sealed- problems = pm.check()+ problems = pm.drift()if not problems:return {"ok": True, "skipped": "current"}if sealed():# A sealed payload's tools ship with the artifact; drift here is- # a packaging bug boot_bootstrap reports, not something to fix.+ # an artifact build problem, not something to repair in place.return {"ok": True, "skipped": "sealed"}if not lazy_installs_allowed():return {"ok": True, "skipped": "lazy-installs-disabled"}refreshed: list[str] = []errors: list[str] = []- for problem in problems:- name = problem.split(":", 1)[0].strip()+ for name in problems:try:if name == "venv":pm.sync_venv(explicit=True)@@ -291,206 +272,6 @@ def step_provision_runtimes() -> dict:return {"ok": True, "refreshed": refreshed}-def step_report_runtime_drift() -> dict:- """CHECK-ONLY machine step for automatic boot.-- ``pm.check()`` is O(1) stamp comparisons against the installed-state- ledger — no network, no installs. Drift is reported loudly (the same- verdict the CLI startup block prints) so the user knows to run- ``hermes pm install``; boot itself never installs anything. The- installing pass is MACHINE_STEPS below, selected by the scope CLI.- Automatic boot must not run network installers.- """- import pm-- problems = pm.check()- if not problems:- return {"ok": True, "skipped": "current"}- logger.warning(- "install out of sync (%s) — run `hermes pm install`", "; ".join(problems)- )- return {"ok": True, "drift": problems}---def step_expose_cli() -> dict:- """Keep the user-facing ``hermes`` launchers alive across updates.-- The installers write POSIX wrapper scripts into the link dir- (``~/.local/bin`` and friends) exactly once, at install time — so a- moved checkout, a recreated venv, or a user's stray ``rm`` leaves- stale or missing launchers that nothing repairs until a full- reinstall. This step makes the POST-UPDATE side own the recurring- maintenance: rewrite the three wrappers (hermes, hermes-agent,- hermes-acp) whenever their recorded shape drifts from what this- tree would write today. First-time PATH bootstrapping (shell-rc- edits, Windows registry) stays installer-side on purpose — a- boot-time step must not edit rc files on every update.-- Config-gated by ``cli.expose_on_path`` (default true). Windows is a- no-op: venv Scripts are already User-PATH-persisted by the installer.- """- if sys.platform == "win32":- return {"ok": True, "skipped": "windows-installer-owned"}-- try:- from hermes_cli.config import load_config-- cli_cfg = (load_config() or {}).get("cli", {})- if isinstance(cli_cfg, dict) and not bool(cli_cfg.get("expose_on_path", True)):- return {"ok": True, "skipped": "config-disabled"}- except Exception as exc: # noqa: BLE001 — config trouble must not kill the step- logger.debug("Could not read cli.expose_on_path: %s", exc)-- root = _install_root()-- # Shape FIRST, capability second. The stamp is the shape authority: a- # bundled desktop payload never gets installer-written wrappers — its- # launchers SHIP in agent-payload/bin as prebuilt signed shims. macOS- # is the one platform where nothing at install time can expose them- # (a dragged .app runs no installer), so there — and only there —- # link the user's bin dir at the bundle's own shims. A Linux AppImage- # mounts at a transient path a symlink to which would dangle the- # moment the app exits.- if _is_bundled_payload(root):- if sys.platform == "darwin":- return _symlink_sealed_launchers(root.parent / "bin")- return {"ok": True, "skipped": "bundle-owns-launchers"}-- # pm-store-managed install: the launchers are owned by- # hermes_cli._launchers (staged by install.ps1 / _install_repair —- # boot the STORE python with a repo-first PYTHONPATH, never- # venv/Scripts|bin python). This step's venv-wrapper shape is NOT- # that shape; writing it here would rewrite a store launcher into a- # venv boot. No alternate writer: the existing owner maintains- # these (per-name, at install and at process-start repair).- try:- from hermes_cli._launchers import resolve_store_python-- if resolve_store_python(root) is not None:- return {"ok": True, "skipped": "store-launchers-owned"}- except Exception as exc: # noqa: BLE001 — never kill boot over a probe- logger.debug("store-python probe failed: %s", exc)-- # Capability probe for the checkout shape: the wrapper bodies bake- # these two paths into text, so both must exist to have anything to- # point at. A checkout with a nuked venv lands here — skip; the- # installer/bootstrap owns venv repair, not this step.- venv_python = root / "venv" / "bin" / "python"- entrypoint = root / "hermes"- if not venv_python.is_file() or not entrypoint.is_file():- return {"ok": True, "skipped": "no-venv-layout"}-- link_dir = Path.home() / ".local" / "bin"- wrappers = {- "hermes": f'exec "{venv_python}" "{entrypoint}" "$@"',- "hermes-agent": f'exec "{venv_python}" "{root / "run_agent.py"}" "$@"',- "hermes-acp": f'exec "{venv_python}" "{entrypoint}" acp "$@"',- }-- written: list[str] = []- try:- link_dir.mkdir(parents=True, exist_ok=True)- for name, exec_line in wrappers.items():- target = link_dir / name- body = (- "#!/usr/bin/env bash\n"- "unset PYTHONPATH\n"- "unset PYTHONHOME\n"- f"{exec_line}\n"- )- try:- existing = target.read_text(encoding="utf-8-sig")- except (FileNotFoundError, UnicodeDecodeError, OSError):- existing = None- if existing == body:- continue # current — do not churn mtimes every boot- # A launcher pointing at ANOTHER install is the user's own- # arrangement (two checkouts, one link dir) — leave it alone.- # Ours means: mentions this root in its text, OR is a symlink- # resolving into this root (the pre-#21454 install shape,- # where the link dir pointed straight at the venv console- # script — reading THROUGH it shows no path at all).- is_symlink_into_root = (- target.is_symlink()- and str(target.resolve()).startswith(str(root) + os.sep)- )- if (- existing is not None- and existing.strip()- and str(root) not in existing- and not is_symlink_into_root- ):- continue- # The installers' #21454 lesson: clear first, so writing can- # never follow an old symlink into the venv and clobber a- # console script.- target.unlink(missing_ok=True)- target.write_text(body, encoding="utf-8")- target.chmod(0o755)- written.append(name)- except OSError as exc:- return {"ok": False, "error": str(exc)}- return {"ok": True, "written": written}---def _is_bundled_payload(root: Path) -> bool:- """Is ``root`` a desktop bundle's agent payload? The stamp is the- authority (payload marker / desktop-app distribution), never a- sibling-directory sniff; a .git tree is a dev checkout regardless."""- if (root / ".git").exists():- return False- from hermes_cli.steward import STEWARD_DESKTOP, read_install_stamp-- stamp = read_install_stamp(root)- if not stamp:- return False- return bool(stamp.get("payload")) or stamp.get("distribution") == STEWARD_DESKTOP---def _symlink_sealed_launchers(payload_bin) -> dict:- """Link ~/.local/bin/{hermes,hermes-agent,hermes-acp} at a sealed- bundle's own prebuilt shims (macOS only).-- Symlinks, not copies: the shims are signed as part of the app bundle,- and a copy would both orphan the signature's context and go stale on- every app update — a symlink into the .app follows the bundle's- content wherever Squirrel.Mac swaps it.-- Ownership guard mirrors step_expose_cli's wrapper logic: an existing- entry is replaced only when it is ours — a symlink into THIS app- bundle's payload — or missing/broken. A user's own `hermes` (pipx,- another checkout's wrapper) is never touched.- """- link_dir = Path.home() / ".local" / "bin"- payload_root = payload_bin.parent- written: list[str] = []- try:- link_dir.mkdir(parents=True, exist_ok=True)- for name in ("hermes", "hermes-agent", "hermes-acp"):- source = payload_bin / name- if not source.is_file():- continue- target = link_dir / name- if target.is_symlink():- current = os.readlink(target)- if current == str(source):- continue # already ours and current- # Ours if it points into this payload (stale app path from- # a previous version counts — resolve() of a dangling link- # still yields the old path text) — or dangling entirely.- points_into_payload = str(Path(current)).startswith(str(payload_root) + os.sep)- if not points_into_payload and target.exists():- continue # a live foreign link — user's arrangement- elif target.exists():- continue # a real file we did not write — never clobber- target.unlink(missing_ok=True)- target.symlink_to(source)- written.append(name)- except OSError as exc:- return {"ok": False, "error": str(exc)}- return {"ok": True, "written": written, "mode": "sealed-symlinks"}--# ---------------------------------------------------------------------------# step registries — boot_bootstrap gates each list with the matching record# ---------------------------------------------------------------------------@@ -500,7 +281,7 @@ HOME_STEPS: tuple = (("migrate_config", step_migrate_config),("sync_skills", step_sync_skills),("state_db_guard", step_state_db_guard),- ("expose_cli", step_expose_cli),+ ("expose_cli", expose_cli),)# Startup skill syncing belongs to each entry point. Boot bootstrap must@@ -509,21 +290,11 @@ BOOT_HOME_STEPS: tuple = tuple(step for step in HOME_STEPS if step[0] != "sync_skills")-# Only the explicit scope CLI selects installing machine steps. Automatic-# boot uses the check-only registry below.+# Only the explicit scope CLI installs runtimes. Boot checks PM at startup.MACHINE_STEPS: tuple = (("provision_runtimes", step_provision_runtimes),)-# What AUTOMATIC boot runs for the machine scope: the same pm.check()-# verdict, reported instead of installed (boot must not block on, or-# trigger, network installs — the user runs `hermes pm install` or the-# explicit update pass when they want the repair).-BOOT_MACHINE_STEPS: tuple = (- ("report_runtime_drift", step_report_runtime_drift),-)--def run_steps(steps: Iterable) -> dict:"""Run steps in order; one failure never stops the rest.diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.pyindex cd312df88a0..d9ddb400f69 100644--- a/hermes_cli/venv_sync.py+++ b/hermes_cli/venv_sync.py@@ -49,9 +49,25 @@ def _is_sealed(project_root: Path) -> bool:return 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()+ 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)@@ -63,6 +79,11 @@ def publish_launchers(project_root: Path) -> None:from pm.package import InstallErrorraise InstallError("launchers", "source launcher publication failed", "retry the source update")+ result = expose_cli(root)+ if not result["ok"]:+ import logging++ logging.getLogger(__name__).warning("CLI exposure failed: %s", result["error"])def sync(project_root: Path | None = None, *, check: bool = False) -> dict:diff --git a/pm/__init__.py b/pm/__init__.pyindex 801d1e997be..660c430097a 100644--- a/pm/__init__.py+++ b/pm/__init__.py@@ -15,6 +15,7 @@ from pm.ensure import (activate,adopt,check,+ drift,enabled_extras,env_for,is_installed,@@ -40,6 +41,7 @@ __all__ = ["installed_package","adopt","check",+ "drift","activate","sync_venv","available",diff --git a/pm/ensure.py b/pm/ensure.pyindex 4a1c17516cd..c84b9daf136 100644--- a/pm/ensure.py+++ b/pm/ensure.py@@ -641,17 +641,17 @@ def adopt() -> bool:return True-def check() -> list[str]:- """The startup check: cheap stamp comparisons of the installed state- against the lockfile. Returns problems; empty means healthy. Never+def drift() -> dict[str, str]:+ """Cheap stamp comparisons of the installed state+ against the lockfile. Maps package names to reasons; empty means healthy. Neverinstalls, never touches the network. An install pm has never touched(no installed-state file) reports nothing — pm only vouches for whatit installed. Lockfile packages this build doesn't know (version skewduring a partial update) are skipped, not fatal."""if not paths.facts_path().is_file() and not paths.runtime_facts_path().is_file():- return []+ return {}- problems: list[str] = []+ problems: dict[str, str] = {}lockfile = _lockfile()facts = _facts()store = _store()@@ -666,7 +666,7 @@ def check() -> list[str]:if package.missing_reason(target) is not None:continueif _installed_location(package, lockfile, target) is None:- problems.append(f"{name}: not installed or outdated")+ problems[name] = "not installed or outdated"try:venv = get_package("venv")except KeyError:@@ -674,12 +674,17 @@ def check() -> list[str]:if venv is not None and (paths.runtime_facts_path().is_file() or facts.get("venv") is not None):try:if not venv_is_current():- problems.append("venv: out of sync with uv.lock")+ problems["venv"] = "out of sync with uv.lock"except (OSError, RuntimeError, ValueError) as exc:- problems.append(f"venv: {exc}")+ problems["venv"] = str(exc)return problems+def check() -> list[str]:+ """Human-readable startup diagnostics. Use drift() for package identities."""+ return [f"{name}: {reason}" for name, reason in drift().items()]++def _store_path_dirs() -> list[str]:"""Composed PATH dirs of all installed (non-internal, on_path) storepackages, deps-first, deduped. Includes optional packages that arediff --git a/tests/hermes_cli/test_boot_bootstrap.py b/tests/hermes_cli/test_boot_bootstrap.pyindex 699939217f9..23aaeda439e 100644--- a/tests/hermes_cli/test_boot_bootstrap.py+++ b/tests/hermes_cli/test_boot_bootstrap.py@@ -2,8 +2,7 @@The record files are an optimization layer over idempotent steps; thesetests assert the contracts that keep that safe: identity resolution from-real git trees and stamps, record scoping (per-install AND per-home vs-per-machine), and the lock protocol including the double-check under lock.+real git trees and stamps, record scoping (per-install AND per-home), and the lock protocol including the double-check under lock."""import jsonimport os@@ -24,7 +23,7 @@ from hermes_cli.boot_bootstrap import (read_last_known,record_path,run_boot_bootstrap,- write_record,+ _write_record,)@@ -158,8 +157,8 @@ def test_identity_broken_tree_is_none(tmp_path):def test_record_paths_key_on_install_root(tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))- a = record_path(tmp_path / "install-a", "home")- b = record_path(tmp_path / "install-b", "home")+ a = record_path(tmp_path / "install-a")+ b = record_path(tmp_path / "install-b")assert a != b# The key is a FOLDER (installs/<SHA16>/bootstrap/<profile>.json),# not a filename suffix: same grandparent tree, different key dirs.@@ -168,27 +167,19 @@ def test_record_paths_key_on_install_root(tmp_path, monkeypatch):assert a.name == b.name # the profile filename is the shared part-def test_home_records_differ_per_profile_machine_record_shared(tmp_path, monkeypatch):+def test_home_records_differ_per_profile(tmp_path, monkeypatch):monkeypatch.setattr(Path, "home", lambda: tmp_path)base = tmp_path / ".hermes"profile = base / "profiles" / "coder"install = tmp_path / "install"monkeypatch.setenv("HERMES_HOME", str(base))- home_default = record_path(install, "home")- machine_default = record_path(install, "machine")+ home_default = record_path(install)monkeypatch.setenv("HERMES_HOME", str(profile))- home_profile = record_path(install, "home")- machine_profile = record_path(install, "machine")+ home_profile = record_path(install)assert home_default != home_profile # each profile bootstraps its own home- assert machine_default == machine_profile # machine record is shared---def test_record_path_rejects_unknown_scope(tmp_path):- with pytest.raises(ValueError):- record_path(tmp_path, "galaxy")@pytest.mark.skipif(@@ -200,7 +191,7 @@ def test_symlinked_root_canonicalizes(tmp_path, monkeypatch):real.mkdir()link = tmp_path / "link-install"link.symlink_to(real)- assert record_path(real, "home") == record_path(link, "home")+ assert record_path(real) == record_path(link)# ── needs_bootstrap ──────────────────────────────────────────────────@@ -211,21 +202,21 @@ def test_needs_bootstrap_lifecycle(repo, tmp_path, monkeypatch):sha = _head_sha(repo)# No record yet → identity returned.- assert needs_bootstrap(repo, "home") == sha+ assert needs_bootstrap(repo) == sha- write_record(repo, "home", sha)- assert needs_bootstrap(repo, "home") is None+ _write_record(record_path(repo), sha, {})+ assert needs_bootstrap(repo) is None# New commit → mismatch again.(repo / "f.txt").write_text("2", encoding="utf-8")_git(["add", "."], repo)_git(["commit", "-m", "two"], repo)- assert needs_bootstrap(repo, "home") == _head_sha(repo)+ assert needs_bootstrap(repo) == _head_sha(repo)def test_needs_bootstrap_broken_tree_never_fires(tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))- assert needs_bootstrap(tmp_path / "nope", "home") is None+ assert needs_bootstrap(tmp_path / "nope") is None# ── lock protocol ────────────────────────────────────────────────────@@ -269,20 +260,15 @@ def test_fresh_lock_is_respected(tmp_path):@pytest.fixturedef fake_steps(monkeypatch):- calls = {"home": 0, "machine": 0}+ calls = {"home": 0}def home_step():calls["home"] += 1return {"ok": True}- def machine_step():- calls["machine"] += 1- return {"ok": True}-from hermes_cli import post_updatemonkeypatch.setattr(post_update, "BOOT_HOME_STEPS", (("h", home_step),))- monkeypatch.setattr(post_update, "BOOT_MACHINE_STEPS", (("m", machine_step),))return calls@@ -291,16 +277,15 @@ def test_run_boot_bootstrap_runs_then_noops(repo, tmp_path, monkeypatch, fake_stmonkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))first = run_boot_bootstrap(repo)- assert fake_steps == {"home": 1, "machine": 1}+ assert fake_steps == {"home": 1}assert first["home"] == {"h": {"ok": True}}- assert first["machine"] == {"m": {"ok": True}}second = run_boot_bootstrap(repo)- assert fake_steps == {"home": 1, "machine": 1} # no re-run- assert second == {"home": "skipped", "machine": "skipped"}+ assert fake_steps == {"home": 1} # no re-run+ assert second == {"home": "skipped"}-def test_machine_step_runs_once_across_profiles(repo, tmp_path, monkeypatch, fake_steps):+def test_each_profile_runs_its_own_home_steps(repo, tmp_path, monkeypatch, fake_steps):monkeypatch.setattr(Path, "home", lambda: tmp_path)base = tmp_path / ".hermes"@@ -309,8 +294,8 @@ def test_machine_step_runs_once_across_profiles(repo, tmp_path, monkeypatch, fakmonkeypatch.setenv("HERMES_HOME", str(base / "profiles" / "coder"))run_boot_bootstrap(repo)- # Each home bootstraps itself; the machine step fires once.- assert fake_steps == {"home": 2, "machine": 1}+ # Each home bootstraps itself.+ assert fake_steps == {"home": 2}def test_step_failure_still_writes_record(repo, tmp_path, monkeypatch):@@ -323,15 +308,14 @@ def test_step_failure_still_writes_record(repo, tmp_path, monkeypatch):raise RuntimeError("step exploded")monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", (("boom", boom),))- monkeypatch.setattr(post_update, "BOOT_MACHINE_STEPS", ())run_boot_bootstrap(repo)- record = read_last_known(record_path(repo, "home"))+ record = read_last_known(record_path(repo))assert record["identity"] == _head_sha(repo)assert record["results"]["boom"]["ok"] is False# A broken step must not retrigger the slow path every boot.- assert needs_bootstrap(repo, "home") is None+ assert needs_bootstrap(repo) is Nonedef test_double_check_under_lock(repo, tmp_path, monkeypatch, fake_steps):@@ -346,7 +330,7 @@ def test_double_check_under_lock(repo, tmp_path, monkeypatch, fake_steps):got = real_acquire(self)if got and self.path.name.endswith(".json.lock"):# Simulate the previous holder completing just before us.- write_record(repo, "home", sha)+ _write_record(record_path(repo), sha, {})return gotmonkeypatch.setattr(_RecordLock, "acquire", acquire_after_racer_finished)@@ -363,60 +347,6 @@ def test_maybe_run_never_raises(monkeypatch, tmp_path):boot_bootstrap.maybe_run_boot_bootstrap(tmp_path) # must not raise-def test_boot_machine_scope_is_check_only(repo, tmp_path, monkeypatch):- """Automatic boot NEVER installs: a drifted machine must get a drift- report (and a written record), while pm's ensure/sync_venv stay- reserved for the explicit update pass (MACHINE_STEPS)."""- import pm-- from hermes_cli import post_update-- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))-- installed: list[str] = []- monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated"])-- class _Boom:- @staticmethod- def ensure(*_a, **_kw):- installed.append("ensure")-- @staticmethod- def sync_venv(*_a, **_kw):- installed.append("sync_venv")-- monkeypatch.setitem(sys.modules, "pm.ensure", _Boom)-- result = run_boot_bootstrap(repo)-- assert result["machine"]["report_runtime_drift"]["drift"] == [- "node: not installed or outdated"- ]- assert installed == [], "boot must not install anything"- record = read_last_known(record_path(repo, "machine"))- assert record["results"]["report_runtime_drift"]["ok"] is True- # the installing registry is untouched for the explicit update owner- assert ("provision_runtimes", post_update.step_provision_runtimes) in (- post_update.MACHINE_STEPS- )- assert ("report_runtime_drift", post_update.step_report_runtime_drift) in (- post_update.BOOT_MACHINE_STEPS- )---def test_boot_machine_scope_current_is_skipped(repo, tmp_path, monkeypatch):- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))- import pm-- monkeypatch.setattr(pm, "check", lambda: [])- result = run_boot_bootstrap(repo)- assert result["machine"] == {- "report_runtime_drift": {"ok": True, "skipped": "current"}- }--def test_sealed_tree_bootstrap_end_to_end(tmp_path, monkeypatch):"""The desktop-bundle-swap scenario. A sealed tree (install-stamp.json,no .git) must bootstrap on first boot, no-op on the second, and RE-RUN@@ -428,11 +358,6 @@ def test_sealed_tree_bootstrap_end_to_end(tmp_path, monkeypatch):monkeypatch.setattr(Path, "home", lambda: tmp_path)monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))- # A sealed tree consults pm for drift; keep the test hermetic.- import pm-- monkeypatch.setattr(pm, "check", lambda: [])-sealed = tmp_path / "payload"sealed.mkdir()(sealed / "install-stamp.json").write_text(@@ -446,7 +371,6 @@ def test_sealed_tree_bootstrap_end_to_end(tmp_path, monkeypatch):return {"ok": True}monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", (("h", count),))- monkeypatch.setattr(post_update, "BOOT_MACHINE_STEPS", ())assert run_boot_bootstrap(sealed)["home"] != "skipped"assert calls["n"] == 1@@ -460,194 +384,3 @@ def test_sealed_tree_bootstrap_end_to_end(tmp_path, monkeypatch):assert run_boot_bootstrap(sealed)["home"] != "skipped"assert calls["n"] == 2, "a swapped bundle must re-run the bootstrap"---# ── the per-install state folder ─────────────────────────────────────---def test_ensure_install_dir_writes_the_reverse_map(repo, tmp_path, monkeypatch):- """install.json is the sha16 → root reverse map that makes orphan GC- possible. Written once; a second call must not rewrite firstSeen."""- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) # isolate the default root-- state = boot_bootstrap.ensure_install_dir(repo)-- assert state == boot_bootstrap.install_state_dir(repo)- record = json.loads((state / "install.json").read_text())- assert record["root"] == str(repo.resolve())- assert record["steward"] == "checkout"- first_seen = record["firstSeen"]-- boot_bootstrap.ensure_install_dir(repo)- assert json.loads((state / "install.json").read_text())["firstSeen"] == first_seen---def test_ensure_install_dir_records_the_sealed_steward(tmp_path, monkeypatch):- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) # isolate the default root-- sealed = tmp_path / "payload"- sealed.mkdir()- (sealed / "install-stamp.json").write_text(- json.dumps({"commit": "c" * 40, "distribution": "desktop-app", "updateMechanism": "electron-updater"})- )- state = boot_bootstrap.ensure_install_dir(sealed)- record = json.loads((state / "install.json").read_text())- assert record["steward"] == "desktop-app"---def test_orphan_sweep_flags_only_vanished_roots(repo, tmp_path, monkeypatch):- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) # isolate the default root-- boot_bootstrap.ensure_install_dir(repo) # alive- ghost = tmp_path / "deleted-checkout"- ghost.mkdir()- ghost_state = boot_bootstrap.ensure_install_dir(ghost)- shutil.rmtree(ghost) # the install is gone; its state folder is not-- orphans = boot_bootstrap.orphaned_installs()-- assert [(folder, root) for folder, root in orphans] == [- (ghost_state, str(ghost))- ]---def test_bootstrap_records_live_inside_the_state_folder(repo, tmp_path, monkeypatch):- """Both scopes share the install's folder; profile identity rides the- FILENAME. One anchor, not two homes."""- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) # isolate the default root-- home = boot_bootstrap.record_path(repo, "home")- machine = boot_bootstrap.record_path(repo, "machine")-- state = boot_bootstrap.install_state_dir(repo)- assert home == state / "bootstrap" / "default.json"- assert machine == state / "bootstrap" / "machine.json"---class TestSealedDriftBackstop:- """_report_sealed_runtime_drift — every boot of a drifted sealed tree- says so; nothing else makes a sound, and nothing ever gates boot."""-- def _sealed_tree(self, tmp_path):- root = tmp_path / "sealed"- root.mkdir()- (root / "install-stamp.json").write_text(- json.dumps({"schemaVersion": 2, "commit": "a" * 40, "distribution": "docker", "updateMechanism": "external"}),- encoding="utf-8",- )- return root-- def test_drifted_sealed_tree_reports_to_stderr(self, tmp_path, capsys, monkeypatch):- import pm-- root = self._sealed_tree(tmp_path)- monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated"])- message = boot_bootstrap._report_sealed_runtime_drift(root)- assert message is not None and "node" in message- err = capsys.readouterr().err- assert "docker" in err and "node" in err-- def test_current_sealed_tree_is_silent(self, tmp_path, capsys, monkeypatch):- import pm-- root = self._sealed_tree(tmp_path)- monkeypatch.setattr(pm, "check", lambda: [])- assert boot_bootstrap._report_sealed_runtime_drift(root) is None- assert capsys.readouterr().err == ""-- def test_checkout_is_silent_even_with_drift(self, tmp_path, capsys, monkeypatch):- """A checkout provisions on demand; drift there is self-healing- and must not produce boot noise."""- import pm-- root = tmp_path / "co"- (root / ".git").mkdir(parents=True)- monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated"])- assert boot_bootstrap._report_sealed_runtime_drift(root) is None- assert capsys.readouterr().err == ""-- def test_a_broken_check_never_gates_boot(self, tmp_path, monkeypatch):- import pm-- root = self._sealed_tree(tmp_path)-- def explode():- raise RuntimeError("facts file corrupted")-- monkeypatch.setattr(pm, "check", explode)- assert boot_bootstrap._report_sealed_runtime_drift(root) is None-- def test_drift_lands_in_the_boot_summary(self, tmp_path, monkeypatch):- import pm-- from hermes_cli import post_update-- root = self._sealed_tree(tmp_path)- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))- monkeypatch.setattr(pm, "check", lambda: ["uv: not installed or outdated"])- monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", ())- monkeypatch.setattr(post_update, "BOOT_MACHINE_STEPS", ())- summary = run_boot_bootstrap(root)- assert "uv" in summary.get("sealed_runtime_drift", "")---class TestOrphanedStoreEntries:- """orphaned_store_entries — pm's facts.json is the only authority,- keep on doubt."""-- @pytest.fixture- def store(self, tmp_path, monkeypatch):- store = tmp_path / "tools"- store.mkdir(parents=True)- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))- return store-- def _publish(self, store, name, payload=b"tool bytes"):- entry = store / name- entry.mkdir(parents=True)- (entry / "tool.bin").write_bytes(payload)- return entry-- def _facts(self, store, packages: dict):- (store / "facts.json").write_text(- json.dumps({"schema": 1, "packages": packages}), encoding="utf-8"- )-- def test_referenced_entries_survive_unreferenced_are_flagged(self, store):- self._publish(store, "ripgrep-15.2.0-win32-x64")- stale = self._publish(store, "ripgrep-14.1.0-win32-x64", b"x" * 512)- self._facts(store, {- "ripgrep": {"entry": "ripgrep-15.2.0-win32-x64", "version": "15.2.0", "env": {}},- })-- orphans = boot_bootstrap.orphaned_store_entries()-- assert [(e.name, s) for e, s in orphans] == [- ("ripgrep-14.1.0-win32-x64", 512)- ]- assert stale.exists() # report-only: nothing was deleted-- def test_no_facts_file_reports_nothing(self, store):- """pm only vouches for what it installed: no ledger, no verdicts."""- self._publish(store, "gh-2.97.0-win32-x64")- assert boot_bootstrap.orphaned_store_entries() == []-- def test_unreadable_facts_err_toward_keep(self, store):- """A busted ledger must cost disk, not flag entries it may own."""- self._publish(store, "gh-2.97.0-win32-x64")- (store / "facts.json").write_text("NOT JSON", encoding="utf-8")- assert boot_bootstrap.orphaned_store_entries() == []-- def test_scratch_fetch_and_files_are_not_candidates(self, store):- """Scratch dirs are pm's own cleanup, fetch-* entries are the- re-download cache, and stray files are not entries at all."""- (store / ".staging-abc123").mkdir()- self._publish(store, "fetch-0123456789abcdef")- (store / "stray.txt").write_text("x", encoding="utf-8")- self._facts(store, {})- assert boot_bootstrap.orphaned_store_entries() == []diff --git a/tests/hermes_cli/test_boot_convergence.py b/tests/hermes_cli/test_boot_convergence.pynew file mode 100644index 00000000000..c1c85f17afe--- /dev/null+++ b/tests/hermes_cli/test_boot_convergence.py@@ -0,0 +1,191 @@+"""Real startup paths share one passive PM verdict, including fast dispatch."""+import json+import sys+from pathlib import Path++import pytest++[email protected]("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(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"++[email protected]("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 --git a/tests/hermes_cli/test_boot_wiring.py b/tests/hermes_cli/test_boot_wiring.pyindex 7cdb2caa66e..f2126874691 100644--- a/tests/hermes_cli/test_boot_wiring.py+++ b/tests/hermes_cli/test_boot_wiring.py@@ -81,11 +81,6 @@ def test_boot_bootstrap_reaches_post_update_registry(hermes_home, tmp_path, monk"BOOT_HOME_STEPS",(("probe_home", lambda: (ran.append("home"), {"ok": True})[1]),),)- monkeypatch.setattr(- post_update,- "BOOT_MACHINE_STEPS",- (("probe_machine", lambda: (ran.append("machine"), {"ok": True})[1]),),- )root = tmp_path / "install"root.mkdir()@@ -102,10 +97,10 @@ def test_boot_bootstrap_reaches_post_update_registry(hermes_home, tmp_path, monkboot_bootstrap.maybe_run_boot_bootstrap(root)- assert sorted(ran) == ["home", "machine"]+ assert sorted(ran) == ["home"]# second boot: record-gated no-op, no doubled maintenanceboot_bootstrap.maybe_run_boot_bootstrap(root)- assert sorted(ran) == ["home", "machine"]+ assert sorted(ran) == ["home"]# ── gateway entry point reaches the registry ─────────────────────────diff --git a/tests/hermes_cli/test_post_update.py b/tests/hermes_cli/test_post_update.pyindex ff8e6b49ad7..0fdf4c2aff8 100644--- a/tests/hermes_cli/test_post_update.py+++ b/tests/hermes_cli/test_post_update.py@@ -166,10 +166,34 @@ def test_provisioning_is_the_machine_scope_driver_path():assert not any("cua" in name for name in names)+def test_provisioning_does_not_use_human_diagnostics(tmp_path, monkeypatch):+ import json+ import importlib+ import pm+ from pm import paths++ engine = importlib.import_module("pm.ensure")+ runtime = tmp_path / "tools"+ runtime.mkdir()+ (runtime / "facts.json").write_text(json.dumps({"schema": 1, "packages": {}}))+ lock = tmp_path / "lock.json"+ lock.write_text(json.dumps({"schema": 1, "packages": {"node": {"version": "test"}}}))+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(runtime))+ monkeypatch.setattr(paths, "lockfile_path", lambda: lock)+ monkeypatch.setattr(engine, "sealed", lambda: False)+ monkeypatch.setattr(engine, "lazy_installs_allowed", lambda: True)+ monkeypatch.setattr(pm, "check", lambda: ["translated diagnostic without a package token"])+ ensured = []+ monkeypatch.setattr(pm, "ensure", lambda name, **kwargs: ensured.append((name, kwargs)))++ assert post_update.main(["--scope", "machine"]) == 0+ assert ensured == [("node", {"explicit": True})]++def test_provision_runtimes_is_a_noop_when_pm_is_current(monkeypatch):import pm- monkeypatch.setattr(pm, "check", lambda: [])+ monkeypatch.setattr(pm, "drift", lambda: {})assert post_update.step_provision_runtimes() == {"ok": True, "skipped": "current"}@@ -184,7 +208,7 @@ def test_provision_runtimes_reensures_only_what_pm_names(monkeypatch):pm_ensure = importlib.import_module("pm.ensure")ensured = []- monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated", "venv: out of sync with uv.lock"])+ monkeypatch.setattr(pm, "drift", lambda: {"node": "outdated", "venv": "out of sync"})monkeypatch.setattr(pm_ensure, "sealed", lambda: False)monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: True)monkeypatch.setattr(pm, "ensure", lambda name, explicit=False: ensured.append((name, explicit)))@@ -203,7 +227,7 @@ def test_provision_runtimes_respects_the_lazy_install_policy(monkeypatch):pm_ensure = importlib.import_module("pm.ensure")- monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated"])+ monkeypatch.setattr(pm, "drift", lambda: {"node": "outdated"})monkeypatch.setattr(pm_ensure, "sealed", lambda: False)monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: False)result = post_update.step_provision_runtimes()diff --git a/tests/hermes_cli/test_post_update_expose_cli.py b/tests/hermes_cli/test_post_update_expose_cli.pyindex c7ea6d98508..fb453400bdc 100644--- a/tests/hermes_cli/test_post_update_expose_cli.py+++ b/tests/hermes_cli/test_post_update_expose_cli.py@@ -1,4 +1,4 @@-"""step_expose_cli — the post-update side owns launcher-wrapper repair.+"""expose_cli — the launcher owner repairs PATH conveniences.The installers write ~/.local/bin/hermes* once, at install time. Thisstep rewrites them when they drift (moved checkout, recreated venv,@@ -20,11 +20,9 @@ from pathlib import Pathimport pytest-from hermes_cli import post_update+from hermes_cli import _launchers, post_update-posix_only = pytest.mark.skipif(- sys.platform == "win32", reason="wrapper exposure is POSIX-only; Windows is installer-owned"-)+posix_only = pytest.mark.platforms("posix")def _write_bundled_stamp(repo_root: Path) -> None:@@ -42,6 +40,7 @@ def fake_install(tmp_path, monkeypatch):home = tmp_path / "home"home.mkdir()monkeypatch.setattr(Path, "home", staticmethod(lambda: home))+ monkeypatch.setenv("HERMES_HOME", str(home))root = tmp_path / "checkout"(root / "venv" / "bin").mkdir(parents=True)@@ -49,50 +48,59 @@ def fake_install(tmp_path, monkeypatch):(root / "hermes").write_text("# entrypoint\n")(root / "run_agent.py").write_text("# agent\n")monkeypatch.setenv("HERMES_INSTALL_ROOT", str(root))+ store = tmp_path / "tools"+ store.mkdir()+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))+ interpreter = Path(sys._base_executable).resolve()+ (store / "facts.json").write_text(json.dumps({"schema": 1, "packages": {"python": {+ "entry": str(interpreter.parent if os.name == "nt" else interpreter.parents[1]),+ }}}))return home, root-def test_windows_is_installer_owned(monkeypatch):- if sys.platform != "win32":- monkeypatch.setattr(post_update.sys, "platform", "win32")- assert post_update.step_expose_cli() == {[email protected]("windows")+def test_windows_is_installer_owned():+ assert _launchers.expose_cli() == {"ok": True,"skipped": "windows-installer-owned",}def test_registered_as_a_home_step():- assert ("expose_cli", post_update.step_expose_cli) in post_update.HOME_STEPS+ assert ("expose_cli", _launchers.expose_cli) in post_update.HOME_STEPS-@posix_onlyclass TestExposeCli:+ @posix_onlydef test_writes_all_three_wrappers_fresh(self, fake_install):home, root = fake_install- result = post_update.step_expose_cli()+ result = _launchers.expose_cli()assert result["ok"] is Trueassert sorted(result["written"]) == ["hermes", "hermes-acp", "hermes-agent"]for name in ("hermes", "hermes-agent", "hermes-acp"):wrapper = home / ".local" / "bin" / namebody = wrapper.read_text()assert str(root) in body- assert "PYTHONPATH" in body+ assert str(root / ".hermes" / "bin") in bodyassert os.access(wrapper, os.X_OK)+ @posix_onlydef test_second_run_is_a_no_op(self, fake_install):- post_update.step_expose_cli()- result = post_update.step_expose_cli()+ _launchers.expose_cli()+ result = _launchers.expose_cli()assert result == {"ok": True, "written": []}+ @posix_onlydef test_repairs_a_stale_same_install_wrapper(self, fake_install):home, root = fake_install- post_update.step_expose_cli()+ _launchers.expose_cli()wrapper = home / ".local" / "bin" / "hermes"wrapper.write_text(f'#!/bin/sh\nexec "{root}/venv/bin/python" OLD-SHAPE\n')- result = post_update.step_expose_cli()+ result = _launchers.expose_cli()assert "hermes" in result["written"]assert "OLD-SHAPE" not in wrapper.read_text()+ @posix_onlydef test_leaves_another_installs_wrapper_alone(self, fake_install):home, root = fake_installother = "/somewhere/else/checkout"@@ -100,28 +108,31 @@ class TestExposeCli:wrapper_dir.mkdir(parents=True)foreign = f'#!/bin/sh\nexec "{other}/venv/bin/python" "{other}/hermes" "$@"\n'(wrapper_dir / "hermes").write_text(foreign)- result = post_update.step_expose_cli()+ result = _launchers.expose_cli()assert (wrapper_dir / "hermes").read_text() == foreignassert "hermes" not in result["written"]# The other two had no file at all — those ARE written.assert sorted(result["written"]) == ["hermes-acp", "hermes-agent"]+ @posix_onlydef test_config_gate_disables(self, fake_install, monkeypatch):monkeypatch.setattr("hermes_cli.config.load_config",lambda: {"cli": {"expose_on_path": False}},)- result = post_update.step_expose_cli()+ result = _launchers.expose_cli()assert result == {"ok": True, "skipped": "config-disabled"}+ @posix_onlydef test_sealed_tree_without_venv_skips(self, fake_install, monkeypatch, tmp_path):+ (tmp_path / "tools" / "facts.json").unlink()bare = tmp_path / "sealed"bare.mkdir()monkeypatch.setenv("HERMES_INSTALL_ROOT", str(bare))- result = post_update.step_expose_cli()- assert result == {"ok": True, "skipped": "no-venv-layout"}+ result = _launchers.expose_cli()+ assert result == {"ok": True, "skipped": "no-store-python"}- @pytest.mark.skipif(sys.platform == "darwin", reason="darwin takes the symlink branch")+ @pytest.mark.platforms("linux")def test_bundled_tree_skips_bundle_owns_launchers(self, fake_install, monkeypatch, tmp_path):@@ -134,9 +145,10 @@ class TestExposeCli:for name in ("hermes", "hermes-agent", "hermes-acp"):(payload / "bin" / name).write_text("\x7fELF fake shim\n")monkeypatch.setenv("HERMES_INSTALL_ROOT", str(payload / "repo"))- result = post_update.step_expose_cli()+ result = _launchers.expose_cli()assert result == {"ok": True, "skipped": "bundle-owns-launchers"}+ @posix_onlydef test_unstamped_tree_with_sibling_bin_is_not_a_bundle(self, fake_install, monkeypatch, tmp_path):@@ -144,16 +156,18 @@ class TestExposeCli:PARENT happens to carry a bin/hermes (the installers' launcherdir shares ~/.hermes with the checkout) must skip, not enter thesealed branch — on every platform."""+ (tmp_path / "tools" / "facts.json").unlink()parent = tmp_path / "hermes-home"(parent / "bin").mkdir(parents=True)(parent / "bin" / "hermes").write_text("#!/bin/sh\n# installer launcher\n")checkout = parent / "hermes-agent"checkout.mkdir()monkeypatch.setenv("HERMES_INSTALL_ROOT", str(checkout))- result = post_update.step_expose_cli()- assert result == {"ok": True, "skipped": "no-venv-layout"}- assert post_update._is_bundled_payload(checkout) is False+ result = _launchers.expose_cli()+ assert result == {"ok": True, "skipped": "no-store-python"}+ assert _launchers._is_bundled_payload(checkout) is False+ @posix_onlydef test_replaces_a_dangling_symlink_from_old_installs(self, fake_install):"""#21454: `cat >` used to follow an old symlink into the venv andclobber the console script. The step must unlink FIRST."""@@ -163,7 +177,7 @@ class TestExposeCli:console_script = root / "venv" / "bin" / "hermes"console_script.write_text("# real console script\n")(wrapper_dir / "hermes").symlink_to(console_script)- result = post_update.step_expose_cli()+ result = _launchers.expose_cli()assert "hermes" in result["written"]# The venv console script survives untouched…assert console_script.read_text() == "# real console script\n"@@ -171,11 +185,42 @@ class TestExposeCli:assert not (wrapper_dir / "hermes").is_symlink()[email protected]("macos")+def test_direct_packaged_cli_exposes_shims_before_electron(tmp_path):+ import subprocess+ import shlex++ home = tmp_path / "home"+ home.mkdir()+ payload = tmp_path / "Hermes.app/Contents/Resources/agent-payload"+ repo = payload / "repo"+ _write_bundled_stamp(repo)+ (repo / "install-stamp.json").write_text(json.dumps({+ "payload": "bundled", "commit": "abcdef012345", "updateMechanism": "electron-updater",+ }))+ bin_dir = payload / "bin"+ bin_dir.mkdir()+ code = f"import sys; sys.path.insert(0, {str(Path(__file__).resolve().parents[2])!r}); from hermes_cli.main import main; main()"+ for name in ("hermes", "hermes-agent", "hermes-acp"):+ shim = bin_dir / name+ shim.write_text(f'#!/bin/sh\nexec {shlex.join([sys.executable, "-I", "-c", code])} "$@"\n')+ shim.chmod(0o755)+ env = dict(os.environ, HOME=str(home), HERMES_HOME=str(home / ".hermes"),+ HERMES_INSTALL_ROOT=str(repo), HERMES_RUNTIME_DIR=str(tmp_path / "tools"))+ # Execute the package CLI directly. No Electron process or linking helper runs.+ result = subprocess.run([str(bin_dir / "hermes"), "--version"], env=env,+ capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ for name in ("hermes", "hermes-agent", "hermes-acp"):+ assert (home / ".local/bin" / name).is_symlink()+ assert (home / ".local/bin" / name).resolve() == bin_dir / name++@posix_onlyclass TestSymlinkSealedLaunchers:"""The macOS sealed-bundle exposure helper, tested directly — thesymlink/ownership logic is platform-free; only its call site in- step_expose_cli is darwin-gated."""+ expose_cli is darwin-gated."""@pytest.fixturedef payload(self, tmp_path, monkeypatch):@@ -190,7 +235,7 @@ class TestSymlinkSealedLaunchers:def test_links_all_three_fresh(self, payload):home, payload_bin = payload- result = post_update._symlink_sealed_launchers(payload_bin)+ result = _launchers._symlink_sealed_launchers(payload_bin)assert result["ok"] is Trueassert sorted(result["written"]) == ["hermes", "hermes-acp", "hermes-agent"]for name in ("hermes", "hermes-agent", "hermes-acp"):@@ -200,8 +245,8 @@ class TestSymlinkSealedLaunchers:def test_second_run_is_a_no_op(self, payload):_, payload_bin = payload- post_update._symlink_sealed_launchers(payload_bin)- result = post_update._symlink_sealed_launchers(payload_bin)+ _launchers._symlink_sealed_launchers(payload_bin)+ result = _launchers._symlink_sealed_launchers(payload_bin)assert result["written"] == []def test_retargets_own_link_after_app_moved(self, payload, tmp_path):@@ -212,7 +257,7 @@ class TestSymlinkSealedLaunchers:link_dir = home / ".local" / "bin"link_dir.mkdir(parents=True)(link_dir / "hermes").symlink_to(old / "hermes") # dangling, old payload path- result = post_update._symlink_sealed_launchers(payload_bin)+ result = _launchers._symlink_sealed_launchers(payload_bin)assert "hermes" in result["written"]assert os.readlink(link_dir / "hermes") == str(payload_bin / "hermes")@@ -226,7 +271,7 @@ class TestSymlinkSealedLaunchers:other = tmp_path / "other-tool"other.write_text("other\n")(link_dir / "hermes-agent").symlink_to(other)- result = post_update._symlink_sealed_launchers(payload_bin)+ result = _launchers._symlink_sealed_launchers(payload_bin)assert (link_dir / "hermes").read_text() == "#!/bin/sh\n# pipx launcher\n"assert os.readlink(link_dir / "hermes-agent") == str(other)assert sorted(result["written"]) == ["hermes-acp"]diff --git a/tests/hermes_cli/test_source_launcher_publication.py b/tests/hermes_cli/test_source_launcher_publication.pyindex d021a4eaf03..9be313a7981 100644--- a/tests/hermes_cli/test_source_launcher_publication.py+++ b/tests/hermes_cli/test_source_launcher_publication.py@@ -127,6 +127,45 @@ def test_materializer_cli_refuses_missing_store_without_publishing(tmp_path, monassert not out.exists() or not list(out.iterdir())[email protected]("posix")+def test_boot_migrates_legacy_conveniences_to_selected_runtime(tmp_path, monkeypatch):+ repo, home, interpreter = fixture_tree(tmp_path, monkeypatch)+ monkeypatch.setattr(Path, "home", lambda: home)+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(repo))+ selected = install_state_dir(repo) / "environments" / "current" / "venv"+ site = site_packages(selected)+ site.mkdir(parents=True)+ (selected / "pyvenv.cfg").write_text("home = fixture\n")+ (site / "selected_probe.py").write_text("VALUE = 'migrated'\n")+ (install_state_dir(repo) / "facts.json").write_text(json.dumps({+ "schema": 1, "packages": {"venv": {"environment": str(selected)}}}))+ out = home / ".local" / "bin"+ out.mkdir(parents=True)+ # Old venv and sibling-ACP wrappers, with an unrelated command sharing bin.+ (out / "hermes").write_text(f'#!/bin/sh\nexec "{repo}/venv/bin/python" "{repo}/hermes" "$@"\n')+ (out / "hermes-acp").write_text(+ '#!/usr/bin/env bash\n# Hermes Agent — ACP launcher (written by `hermes update`).\n'+ f'exec "{out}/hermes" acp "$@"\n')+ foreign = f'#!/bin/sh\n# user note about {repo}\nexit 19\n'+ (out / "hermes-agent").write_text(foreign)++ result = _launchers.expose_cli()+ assert result["ok"], result+ assert set(result["written"]) == {"hermes", "hermes-acp"}+ for name in ("hermes", "hermes-acp"):+ run = subprocess.run([str(out / name), "quoted argument"], cwd=tmp_path,+ capture_output=True, text=True, timeout=30)+ assert run.returncode == 7, run.stderr+ receipt = json.loads(run.stdout)+ assert receipt["value"] == "migrated"+ assert receipt["argv"] == ["quoted argument"]+ assert Path(receipt["exe"]).samefile(interpreter)+ assert (out / "hermes-agent").read_text() == foreign+ before = {p: p.stat().st_mtime_ns for p in out.iterdir()}+ assert _launchers.expose_cli()["written"] == []+ assert before == {p: p.stat().st_mtime_ns for p in out.iterdir()}++def _command_survives_generation_collection(tmp_path, monkeypatch, surface):from hermes_cli.runtime_state import collect_generations@@ -297,6 +336,34 @@ def test_service_survives_python_tool_replacement(tmp_path, monkeypatch):assert json.loads(result.stdout)["value"] == "ready"[email protected]("posix")+def test_sync_migrates_old_store_wrapper_before_python_collection(tmp_path, monkeypatch):+ from hermes_cli.venv_sync import publish_launchers++ repo, home, interpreter = fixture_tree(tmp_path, monkeypatch)+ monkeypatch.setattr(Path, "home", lambda: home)+ site = site_packages(repo / "venv")+ site.mkdir(parents=True)+ (site / "selected_probe.py").write_text("VALUE = 'ready'\n")+ out = home / ".local/bin"+ out.mkdir(parents=True)+ store = home / "tools"+ for version in ("python-A", "python-B"):+ python = store / version / "bin/python3"+ python.parent.mkdir(parents=True)+ python.symlink_to(interpreter)+ (store / "facts.json").write_text(json.dumps({"schema": 1, "packages": {"python": {"entry": version}}}))+ if version == "python-A":+ _launchers.mint_launcher("hermes", repo, out, python, None)+ else:+ publish_launchers(repo)+ shutil.rmtree(store / "python-A")+ result = subprocess.run([str(out / "hermes")], cwd=tmp_path,+ capture_output=True, text=True, timeout=30)+ assert result.returncode == 7, result.stderr+ assert json.loads(result.stdout)["value"] == "ready"++def test_update_import_probe_uses_selected_dependencies(tmp_path, monkeypatch):from hermes_cli import update_cmd, update_cmd_validation