Skip to content

The agent that grows with you

fix(pm): a borrowed HERMES_HOME leaves the source checkout to the root that owns it

FroRautd2d45b549b90
diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.py
index cf442ea94bc..a14d14ecbd3 100644
--- a/hermes_cli/venv_sync.py
+++ b/hermes_cli/venv_sync.py
@@ -379,6 +379,11 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:
from hermes_cli.update_lock import UpdateLock, read_live_update
current = pm.venv_is_current(project_root=root)
+ from pm.environments import owning_home_root
+
+ owner = owning_home_root(root)
+ if owner is not None:
+ return _prepare_borrowed_launch(root, owner, current=current)
pending = completion_pending_path(root)
owed_to_cli = current and pending.is_file() and _supervised_child()
_may_retry, _attempts, _backoff = completion_retry_state(root)
@@ -436,6 +441,41 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:
return None
+def _prepare_borrowed_launch(root: Path, owner: Path, *, current: bool) -> Path | None:
+ """Launch a checkout that another data root owns (#123238).
+
+ Dependency state is per data root, so a borrowing root -- a test's temporary
+ ``HERMES_HOME``, a per-task home -- still gets an environment of its own, synced exactly
+ as a process spawned under a live update syncs. The rest is the checkout's, and so the
+ owner's: launchers, product builds, post-update maintenance, the install stamp and the
+ owner's own update markers. None of it is armed, run or published from here, so a
+ borrowing launch cannot rebind the shared launchers, rebuild products another root is
+ serving, or race the owner's tail under a lock that lives in a different home.
+ """
+ import os
+ import sys
+ import pm
+ from hermes_cli._launchers import resolve_store_python
+ from hermes_cli.update_lock import UpdateLock
+
+ if not current:
+ lock = UpdateLock()
+ if not lock.acquire():
+ raise RuntimeError("an update is still running; wait for it to exit, then relaunch Hermes")
+ try:
+ _sync_source_dependencies(root, arm=False, borrowed_from=owner)
+ finally:
+ lock.release()
+ if not pm.venv_is_current(project_root=root):
+ # Relaunching would land back here and sync again, forever.
+ raise RuntimeError("dependency sync left this install out of date")
+ python = resolve_store_python(root)
+ if python is None:
+ raise RuntimeError("source update has no managed Python; run `hermes pm install`")
+ same = os.path.normcase(os.path.abspath(python)) == os.path.normcase(os.path.abspath(sys.executable))
+ return python if not current or not same else None
+
+
def _finish_source_update(root: Path, *, current: bool, pending: Path) -> None:
"""Sync dependencies when they are stale, then run the tail the marker still owes."""
import sys
@@ -491,15 +531,22 @@ def _finish_source_update(root: Path, *, current: bool, pending: Path) -> None:
clear_completion(root)
-def _sync_source_dependencies(root: Path, *, arm: bool) -> None:
- """Commit the tree's dependency generation; *arm* also owes the tail afterwards."""
+def _sync_source_dependencies(root: Path, *, arm: bool, borrowed_from: Path | None = None) -> None:
+ """Commit the tree's dependency generation; *arm* also owes the tail afterwards.
+
+ *borrowed_from* names the data root that owns the checkout when this one only borrows
+ it: the sync is this root's own, but the checkout's update markers stay the owner's.
+ """
import sys
import pm
from pm.client import ensure_tools_for_sync
from pm.environments import runtime_facts_path
from pm.extras import legacy_selection
- if not arm:
+ if borrowed_from is not None:
+ print(f"hermes: preparing dependencies for this data root (the checkout's updates belong to "
+ f"{borrowed_from})...", file=sys.stderr, flush=True)
+ elif not arm:
print("hermes: preparing dependencies for this update...", file=sys.stderr, flush=True)
refuse_foreign_owned_venv(root)
if arm:
@@ -514,6 +561,8 @@ def _sync_source_dependencies(root: Path, *, arm: bool) -> None:
ensure_tools_for_sync()
pm.sync_venv(extras, explicit=True, project_root=root, evict_incompatible_plugins=True)
collect_superseded_generations(root)
+ if borrowed_from is not None:
+ return # The checkout's markers describe the owner's environment, not this one.
# These can predate the swap. Once PM commits the replacement they
# must not make early recovery immediately rebuild it a second time.
for name in (".update-incomplete", ".lazy-refresh-incomplete"):
diff --git a/pm/environments.py b/pm/environments.py
index 45734eb05a0..bd4888baff8 100644
--- a/pm/environments.py
+++ b/pm/environments.py
@@ -38,6 +38,34 @@ def install_state_dir(project_root: Path) -> Path:
return installs_root() / install_key(project_root)
+def owning_home_root(project_root: Path) -> Path | None:
+ """The data root that owns this checkout when the active root only borrows it, else ``None``.
+
+ Dependency state is scoped per data root (``<root>/installs/<install_key>``), but a source
+ checkout -- its launchers, product builds and install stamp -- exists once. A launch under
+ another root (a test's temporary ``HERMES_HOME``, a per-task home, a CI service home) borrows
+ it: the root that installed it already holds committed state for it, under the platform
+ default root or the root the checkout sits in (``<root>/hermes-agent``). ``None`` when the
+ active root's state is that state (the owner itself, or one of its profiles), and when no
+ such root has state for this checkout -- a fresh install, or a custom root that owns its own
+ tree -- so those keep today's behaviour (#123238).
+ """
+ from hermes_constants import _get_platform_default_hermes_home
+
+ root = Path(project_root).resolve()
+ key = install_key(root)
+ active = install_state_dir(root)
+ owners = [candidate for candidate in dict.fromkeys((_get_platform_default_hermes_home(), root.parent))
+ if (candidate / "installs" / key / "facts.json").is_file()]
+ for owner in owners:
+ try:
+ if (owner / "installs" / key).resolve() == active.resolve():
+ return None
+ except OSError:
+ continue
+ return owners[0] if owners else None
+
+
def install_state_permission_message(project_root: Path, exc: PermissionError) -> str | None:
"""Describe an access failure inside this install's dependency state."""
if not exc.filename:
@@ -142,12 +170,23 @@ def store_root(project_root: Path, *, honor_runtime_override: bool = True) -> Pa
try:
data = json.loads(stamp.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
- return get_default_hermes_root() / "tools"
+ return _unstamped_store(root)
value = data.get("runtimeDir") if isinstance(data, dict) else None
- return Path(value).resolve() if value else get_default_hermes_root() / "tools"
+ return Path(value).resolve() if value else _unstamped_store(root)
return get_default_hermes_root() / "tools"
+def _unstamped_store(project_root: Path) -> Path:
+ """The store of a stamp that names none (source stamps never do): the owning root's.
+
+ The data root's ``tools/`` is the default, but a borrowing root's would be a new store per
+ temporary home -- a full tool download on its first launch, and an interpreter that dies
+ with the home. The checkout's own launchers exec the owner's interpreter, so a borrowing
+ launch resolves the same one (#123238).
+ """
+ return (owning_home_root(project_root) or get_default_hermes_root()) / "tools"
+
+
def flush_before_selecting() -> None:
"""Make a finished generation tree durable before a selection record names it.
diff --git a/tests/hermes_cli/test_borrowed_home_launch.py b/tests/hermes_cli/test_borrowed_home_launch.py
new file mode 100644
index 00000000000..0d0215124db
--- /dev/null
+++ b/tests/hermes_cli/test_borrowed_home_launch.py
@@ -0,0 +1,206 @@
+"""A launch under a data root that does not own the checkout leaves the checkout to its owner (#123238).
+
+Layout in every test: the user's default root is ``<tmp>/.hermes`` (``Path.home`` is ``<tmp>``) and
+the checkout is ``<tmp>/.hermes/hermes-agent``, the ``install.sh`` layout. A root "has state" for the
+checkout when ``<root>/installs/<install_key>/facts.json`` exists -- the record a committed
+dependency sync leaves.
+"""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import sys
+
+import pytest
+
+from hermes_cli import venv_sync
+from pm.environments import install_key, install_state_dir, owning_home_root, store_root
+
+
[email protected](autouse=True)
+def _no_tool_downloads(monkeypatch):
+ import pm.client
+
+ monkeypatch.setattr(pm.client, "ensure_tools_for_sync", lambda: None)
+
+
+def completion_tail(monkeypatch):
+ spawned: list = []
+ monkeypatch.setattr(venv_sync.subprocess, "call", lambda command, **kw: spawned.append(command) or 0)
+ return spawned
+
+
+def _checkout(tmp_path, monkeypatch, *, parent: Path | None = None) -> Path:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.delenv("HERMES_DISABLE_LAZY_INSTALLS", raising=False)
+ monkeypatch.delenv("HERMES_RUNTIME_DIR", raising=False)
+ root = (parent or tmp_path / ".hermes") / "hermes-agent"
+ root.mkdir(parents=True)
+ (root / ".git").mkdir()
+ (root / "pyproject.toml").write_text("[project]\nname='example'\n", encoding="utf-8")
+ (root / "install-stamp.json").write_text(json.dumps({"updateMechanism": "self", "commit": "abc"}), encoding="utf-8")
+ return root
+
+
+def _state(data_root: Path, checkout: Path) -> Path:
+ facts = data_root / "installs" / install_key(checkout) / "facts.json"
+ facts.parent.mkdir(parents=True, exist_ok=True)
+ facts.write_text(json.dumps({"packages": {"venv": {"stamp": "complete", "extras": ["all"]}}}), encoding="utf-8")
+ return facts
+
+
+def _home(monkeypatch, path: Path) -> Path:
+ path.mkdir(parents=True, exist_ok=True)
+ monkeypatch.setenv("HERMES_HOME", str(path))
+ return path
+
+
+def test_a_temporary_home_borrows_the_default_roots_checkout(tmp_path, monkeypatch):
+ root = _checkout(tmp_path, monkeypatch)
+ owner = tmp_path / ".hermes"
+ _state(owner, root)
+ _home(monkeypatch, tmp_path / "tmp" / "hermes-test-a")
+
+ assert owning_home_root(root) == owner
+ assert store_root(root) == owner / "tools"
+
+
[email protected]("home", ["default", "profile"])
+def test_the_owner_and_its_profiles_are_not_borrowers(tmp_path, monkeypatch, home):
+ root = _checkout(tmp_path, monkeypatch)
+ owner = tmp_path / ".hermes"
+ _state(owner, root)
+ if home == "profile":
+ _home(monkeypatch, owner / "profiles" / "work")
+ else:
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+
+ assert owning_home_root(root) is None
+ assert store_root(root) == owner / "tools"
+
+
+def test_a_fresh_install_and_a_custom_root_keep_their_own_store(tmp_path, monkeypatch):
+ # Nobody has state yet: the launching root is about to become the owner.
+ root = _checkout(tmp_path, monkeypatch, parent=tmp_path / "data" / "h")
+ _home(monkeypatch, tmp_path / "data" / "h")
+ assert owning_home_root(root) is None
+ assert store_root(root) == tmp_path / "data" / "h" / "tools"
+
+ # `install.sh --hermes-home /data/h` owns its tree even if the default root once
+ # borrowed it and kept state of its own.
+ _state(tmp_path / "data" / "h", root)
+ _state(tmp_path / ".hermes", root)
+ assert owning_home_root(root) is None
+ assert store_root(root) == tmp_path / "data" / "h" / "tools"
+
+
+def test_a_service_home_borrows_the_root_the_checkout_sits_in(tmp_path, monkeypatch):
+ """A CI runner whose HOME is its own tool-home runs the host's checkout from PATH: the host's
+ root is the checkout's parent, not this process's platform default."""
+ host = tmp_path / "host" / ".hermes"
+ root = _checkout(tmp_path / "runner", monkeypatch, parent=host)
+ _state(host, root)
+ _home(monkeypatch, tmp_path / "runner" / ".hermes" / "pytest-1")
+
+ assert owning_home_root(root) == host
+ assert store_root(root) == host / "tools"
+
+
[email protected](not hasattr(os, "symlink") or sys.platform == "win32", reason="POSIX symlink")
+def test_a_home_whose_installs_link_back_to_the_owner_is_the_owner(tmp_path, monkeypatch):
+ root = _checkout(tmp_path, monkeypatch)
+ owner = tmp_path / ".hermes"
+ _state(owner, root)
+ task = _home(monkeypatch, tmp_path / "tasks" / "t1")
+ (task / "installs").symlink_to(owner / "installs")
+
+ assert owning_home_root(root) is None
+
+
+def test_an_explicit_runtime_dir_still_wins(tmp_path, monkeypatch):
+ root = _checkout(tmp_path, monkeypatch)
+ _state(tmp_path / ".hermes", root)
+ _home(monkeypatch, tmp_path / "tmp" / "a")
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "runtime"))
+
+ assert store_root(root) == (tmp_path / "runtime").resolve()
+
+
+def test_a_borrowing_launch_syncs_its_own_dependencies_and_nothing_of_the_checkout(
+ tmp_path, monkeypatch, completion_tail
+):
+ """The first launch under a temporary home: its own dependency generation, but no tail (products,
+ maintenance, install stamp), no launcher publication and no owner marker touched."""
+ import pm
+ from hermes_cli import _launchers
+
+ root = _checkout(tmp_path, monkeypatch)
+ _state(tmp_path / ".hermes", root)
+ _home(monkeypatch, tmp_path / "tmp" / "hermes-flash-compat-x" / "a")
+ stamp = (root / "install-stamp.json").read_bytes()
+ owner_marker = root / ".update-incomplete"
+ owner_marker.write_text("owner's update\n", encoding="utf-8")
+ borrowed_facts = install_state_dir(root) / "facts.json"
+ syncs = []
+
+ def sync(extras=None, **kwargs):
+ syncs.append(extras)
+ borrowed_facts.parent.mkdir(parents=True, exist_ok=True)
+ borrowed_facts.write_text("{}", encoding="utf-8")
+
+ python = tmp_path / ".hermes" / "tools" / "python" / "bin" / "python3"
+ monkeypatch.setattr(pm, "venv_is_current", lambda **kw: borrowed_facts.is_file())
+ monkeypatch.setattr(pm, "sync_venv", sync)
+ monkeypatch.setattr(_launchers, "resolve_store_python", lambda _: python)
+ monkeypatch.setattr(venv_sync, "publish_launchers", lambda *a, **kw: pytest.fail("published the owner's launchers"))
+
+ assert venv_sync.prepare_launch(root, ["kanban", "init"]) == python # relaunch into the synced env
+ assert len(syncs) == 1
+ assert completion_tail == [], "a borrowing launch ran the checkout's update tail"
+ assert not venv_sync.completion_pending_path(root).exists(), "a tail was armed for a borrowing root"
+ assert owner_marker.is_file(), "the owner's update marker was removed"
+ assert (root / "install-stamp.json").read_bytes() == stamp
+
+ # Its relaunch finds everything current and does nothing further.
+ monkeypatch.setattr(sys, "executable", str(python))
+ assert venv_sync.prepare_launch(root, ["kanban", "init"]) is None
+ assert len(syncs) == 1 and completion_tail == []
+
+
+def test_a_borrowing_launch_ignores_a_tail_armed_before_the_fix(tmp_path, monkeypatch, completion_tail):
+ import pm
+ from hermes_cli import _launchers
+
+ root = _checkout(tmp_path, monkeypatch)
+ _state(tmp_path / ".hermes", root)
+ _home(monkeypatch, tmp_path / "tmp" / "a")
+ pending = venv_sync.completion_pending_path(root)
+ pending.parent.mkdir(parents=True)
+ pending.write_text("source update tail not finished\n", encoding="utf-8")
+ monkeypatch.setattr(pm, "venv_is_current", lambda **kw: True)
+ monkeypatch.setattr(_launchers, "resolve_store_python", lambda _: Path(sys.executable))
+
+ assert venv_sync.prepare_launch(root, []) is None
+ assert completion_tail == []
+
+
+def test_the_owner_still_owes_and_runs_its_tail(tmp_path, monkeypatch, completion_tail):
+ """Unchanged for the owner: a stale environment syncs, arms and runs the tail."""
+ import pm
+ from hermes_cli import _launchers
+
+ root = _checkout(tmp_path, monkeypatch)
+ facts = _state(tmp_path / ".hermes", root)
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+ facts.unlink()
+ monkeypatch.setattr(pm, "venv_is_current", lambda **kw: facts.is_file())
+ monkeypatch.setattr(pm, "sync_venv", lambda *a, **kw: facts.write_text("{}", encoding="utf-8"))
+ monkeypatch.setattr(_launchers, "resolve_store_python", lambda _: Path(sys.executable))
+ published = []
+ monkeypatch.setattr(venv_sync, "publish_launchers", lambda r, **kw: published.append(r))
+
+ assert venv_sync.prepare_launch(root, []) == Path(sys.executable)
+ assert len(completion_tail) == 1
+ assert published == [root]