Skip to content

The agent that grows with you

fix: preserve source update completion and runtime ownership boundaries

ethernet501ab5eb0921
diff --git a/hermes_cli/__init__.py b/hermes_cli/__init__.py
index 876efa9de87..d7e37a0e854 100644
--- a/hermes_cli/__init__.py
+++ b/hermes_cli/__init__.py
@@ -24,8 +24,19 @@ def __getattr__(name: str) -> str:
if name != "__version__":
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
from hermes_cli.steward import read_install_stamp
- from pm.paths import repo_root
-
+ try:
+ from pm.paths import repo_root
+ except ModuleNotFoundError as exc:
+ if exc.name != "pm" and not (exc.name or "").startswith("pm."):
+ raise
+ # The old editable finder may not know the new pm package yet.
+ import json
+ from pathlib import Path
+ try:
+ stamp = json.loads((Path(__file__).resolve().parents[1] / "install-stamp.json").read_text(encoding="utf-8-sig"))
+ return str(stamp.get("baseVersion") or "0.0.0")
+ except (OSError, ValueError, AttributeError):
+ return "0.0.0"
return str(read_install_stamp(repo_root()).get("baseVersion") or "0.0.0")
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.py
index b33d8cef761..1f61e446eca 100644
--- a/hermes_cli/_early_recovery.py
+++ b/hermes_cli/_early_recovery.py
@@ -180,7 +180,7 @@ def _git_dir(root: Path) -> Path:
"""``root``'s git dir: ``.git`` itself, or where a linked worktree's ``.git`` file points."""
dot_git = root / ".git"
if dot_git.is_file():
- text = dot_git.read_text(encoding="utf-8").strip()
+ text = dot_git.read_text(encoding="utf-8-sig").strip()
if text.startswith("gitdir:"):
return root / text[len("gitdir:"):].strip()
return dot_git
@@ -417,7 +417,7 @@ def restore_interrupted_pull(project_root: Path | None = None) -> bool:
def _restore_holding_claim(root: Path, marker: Path) -> bool:
global _merge_advice_shown
git_dir = marker.parent
- fields = dict(line.partition("=")[::2] for line in marker.read_text(encoding="utf-8").splitlines())
+ fields = dict(line.partition("=")[::2] for line in marker.read_text(encoding="utf-8-sig").splitlines())
try:
owner = int(fields.get("pid", ""))
except ValueError:
@@ -441,7 +441,7 @@ def _restore_holding_claim(root: Path, marker: Path) -> bool:
if any((git_dir / name).exists() for name in _GIT_OPERATION_IN_PROGRESS):
merge_head = git_dir / "MERGE_HEAD"
if (not _merge_advice_shown and merge_head.is_file()
- and merge_head.read_text(encoding="utf-8").strip() == target):
+ and merge_head.read_text(encoding="utf-8-sig").strip() == target):
# The killed updater's own merge: its conflict markers may sit in startup modules.
_merge_advice_shown = True
print(f"⚠ A killed `hermes update` left its merge unfinished. Run `git -C {root} merge --abort`, "
diff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.py
index cdce23c5e60..2113c52932a 100644
--- a/hermes_cli/_launchers.py
+++ b/hermes_cli/_launchers.py
@@ -20,8 +20,7 @@ from pathlib import Path
if __name__ == "__main__":
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from hermes_constants import get_hermes_home
-from pm.environments import dependency_home_root, store_root
+from pm.environments import store_root
def runtime_command(repo_root: Path, args=(), *, module: str = "hermes_cli.main",
@@ -37,12 +36,14 @@ def runtime_command(repo_root: Path, args=(), *, module: str = "hermes_cli.main"
python = python or resolve_store_python(root) or Path(sys.executable)
entry = f"exec({code!r})" if code is not None else (
f"runpy.run_module({module!r}, run_name='__main__', alter_sys=True)")
+ default_home = (f"{str(home)!r}" if home is not None else
+ "str(__import__('hermes_constants').get_default_hermes_root())")
bootstrap = (
"import os, sys, runpy; "
- f"os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or {str(home or get_hermes_home())!r}; "
"os.environ.pop('PYTHONHOME', None); os.environ.pop('PYTHONPATH', None); "
"os.environ.pop('VIRTUAL_ENV', None); "
f"sys.path.insert(0, {str(root)!r}); "
+ f"os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or {default_home}; "
"import hermes_bootstrap; "
+ entry
)
@@ -214,7 +215,6 @@ def mint_launcher(
code = f"import base64; exec(base64.b64decode('{encoded}'))"
body = (
"@echo off\r\n"
- "chcp 65001 >nul\r\n"
f'"{python_exe}" -I -c "{code}" %*\r\n'
)
return _write_atomic(out_dir / f"{name}.cmd", lambda p: p.write_text(body, encoding="utf-8"))
@@ -226,10 +226,11 @@ def _launcher_script(name: str, repo_root: Path, dependencies: Path | None) -> s
# install's dependency root, not whichever profile triggered publication.
return (
"import os, re, sys\n"
- f"os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or {str(dependency_home_root())!r}\n"
"os.environ.pop('PYTHONHOME', None)\n"
"os.environ.pop('PYTHONPATH', None)\n"
f"sys.path.insert(0, {str(repo_root.resolve())!r})\n"
+ "from hermes_constants import get_default_hermes_root\n"
+ "os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or str(get_default_hermes_root())\n"
"if sys.argv[1:2] == ['--print-runtime-command']:\n"
" sys.dont_write_bytecode = True\n"
" from pathlib import Path\n"
diff --git a/hermes_cli/post_update.py b/hermes_cli/post_update.py
index 0fba70a6f87..17e36d591c3 100644
--- a/hermes_cli/post_update.py
+++ b/hermes_cli/post_update.py
@@ -186,7 +186,8 @@ def step_adopt_blessed_checkout(project_root: Path | None = None) -> dict:
if not (root / ".git").exists():
return {"ok": True, "skipped": "not-a-checkout"}
- stamp_path = root / "install-stamp.json"
+ from hermes_cli.steward import install_stamp_path
+ stamp_path = install_stamp_path(root)
if stamp_path.exists():
return {"ok": True, "skipped": "already-stamped"}
diff --git a/hermes_cli/source_completion.py b/hermes_cli/source_completion.py
index 518f8921542..8df1301fb72 100644
--- a/hermes_cli/source_completion.py
+++ b/hermes_cli/source_completion.py
@@ -62,7 +62,11 @@ def complete_source_checkout(
if complete:
from hermes_cli.source_stamp import write_source_stamp
- write_source_stamp(root)
+ try:
+ write_source_stamp(root)
+ except (OSError, ValueError) as exc:
+ print(f"⚠ Source update completed, but the install stamp could not be written: {exc}",
+ file=sys.stderr)
return complete
diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.py
index fb68ca6772e..6920324e3cd 100644
--- a/hermes_cli/update_completion.py
+++ b/hermes_cli/update_completion.py
@@ -139,6 +139,10 @@ def _prepare(request: dict, request_path: Path, result_path: Path) -> int:
root = Path(request["source"])
update_id = request["receipt"]["update_id"]
+ from hermes_cli.venv_sync import arm_completion, refuse_foreign_owned_venv
+
+ refuse_foreign_owned_venv(root)
+ arm_completion(root)
with receipt.worker_context(update_id):
try:
pm.sync_venv(explicit=True, project_root=root)
@@ -177,6 +181,9 @@ def _complete_selected(request: dict) -> None:
pre_update_version=request["pre_update_version"],
completion_message=request.get("completion_message"),
announce=None if request.get("completion_message") else "\n✓ Code updated!")
+ if complete:
+ from hermes_cli.venv_sync import clear_completion
+ clear_completion(root)
# systemctl's KillMode=mixed fallback can kill this whole cgroup. Publish the
# gateway watcher's status BEFORE that operation, and demote on later failure.
if request["gateway_mode"]:
diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.py
index 4f29b8c4dc0..2cfe4c79e90 100644
--- a/hermes_cli/venv_sync.py
+++ b/hermes_cli/venv_sync.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import argparse
import json
+import os
import subprocess
from pathlib import Path
@@ -21,9 +22,8 @@ def _project_root() -> Path:
def _is_sealed(project_root: Path) -> bool:
"""A sealed tree ships its interpreter; only checkouts own a venv.
- The stamp file is the authority (hermes_cli.steward reads the same
- file; restated here to keep the bare import stdlib-and-local). A
- tree with BOTH a stamp and .git is a dev tree — treat as checkout.
+ The stamp file is the authority (shared with hermes_cli.steward).
+ A tree with BOTH a stamp and .git is a dev tree — treat as checkout.
A stamp without a valid ``updateMechanism`` is a build-lane bug and
must not be silently read as "not sealed" (that is exactly the
@@ -32,17 +32,14 @@ def _is_sealed(project_root: Path) -> bool:
"""
if (project_root / ".git").exists():
return False
- try:
- data = json.loads(
- (project_root / "install-stamp.json").read_text(encoding="utf-8-sig")
- )
- except (OSError, ValueError):
- return False
- if not (isinstance(data, dict) and bool(data)):
+ from hermes_cli.steward import install_stamp_path, read_install_stamp
+ stamp_path = install_stamp_path(project_root)
+ data = read_install_stamp(project_root)
+ if not data:
return False
if data.get("updateMechanism") not in UPDATE_MECHANISMS:
raise RuntimeError(
- f"install-stamp.json at {project_root} is missing a valid "
+ f"install-stamp.json at {stamp_path.parent} is missing a valid "
f"'updateMechanism' (one of {', '.join(UPDATE_MECHANISMS)}). The "
"build lane that wrote this stamp must pass --update-mechanism to "
"scripts/write_install_stamp.py."
@@ -53,7 +50,10 @@ def _is_sealed(project_root: Path) -> bool:
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
+ from hermes_cli.steward import read_install_stamp, sealed_steward
+
+ if (Path(project_root) / ".git").exists() and read_install_stamp(project_root).get("updateMechanism") != "self":
+ return None # A developer's checkout does not owe managed products.
problems = pm.activate()
if not problems:
@@ -117,6 +117,7 @@ def sync(project_root: Path | None = None, *, check: bool = False) -> dict:
if check:
return {"state": "would-sync", "ok": True}
publish_stage("Updating Python dependencies")
+ refuse_foreign_owned_venv(root)
pm.sync_venv(explicit=True, project_root=root)
publish_launchers(root)
return {"state": "synced", "ok": True}
@@ -141,6 +142,49 @@ def completion_pending_path(project_root: Path) -> Path:
return install_state_dir(project_root) / "source-completion-pending"
+def arm_completion(project_root: Path) -> Path:
+ """Persist the tail obligation before selecting a new dependency generation."""
+ pending = completion_pending_path(project_root)
+ pending.parent.mkdir(parents=True, exist_ok=True)
+ pending.write_text("source update tail not finished\n", encoding="utf-8")
+ return pending
+
+
+def clear_completion(project_root: Path) -> None:
+ completion_pending_path(project_root).unlink(missing_ok=True)
+
+
+def refuse_foreign_owned_venv(project_root: Path) -> None:
+ """Refuse cross-user mutation before PM changes the selected environment (#83529)."""
+ if not hasattr(os, "geteuid"):
+ return
+ uid = os.geteuid() # windows-footgun: ok — guarded POSIX ownership check
+ root = Path(project_root)
+ # A root-run update on a user's checkout is not safe even if a fresh
+ # generation would be allocated: it publishes root-owned state for them.
+ from pm.environments import selected_venv
+ candidates = [root, root / "venv", root / ".venv", root / ".hermes", selected_venv(root)]
+ for venv in (root / "venv", root / ".venv", candidates[-1]):
+ for directory in (venv / ("Scripts" if os.name == "nt" else "bin"),
+ *venv.glob("lib/python*/site-packages")):
+ if directory.is_dir():
+ candidates.append(directory)
+ for entry in list(directory.iterdir())[:2000]:
+ candidates.append(entry)
+ if entry.name.endswith(".dist-info") and entry.is_dir():
+ candidates.extend(list(entry.iterdir())[:100])
+ for path in candidates:
+ try:
+ owner = path.lstat().st_uid
+ except FileNotFoundError:
+ continue
+ if owner != uid:
+ raise RuntimeError(
+ f"refusing to update {root}: {path} is owned by uid {owner}, "
+ f"not the current uid {uid}; repair ownership before retrying"
+ )
+
+
def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:
"""Finish a self-managed source update before importing app dependencies.
@@ -216,8 +260,8 @@ def _finish_source_update(root: Path, *, current: bool, pending: Path) -> None:
print("hermes: completing source-update dependencies...", file=sys.stderr, flush=True)
# Owed from before the sync commits: a crash between the commit and the
# tail must leave the tail, not a "current" install with nothing built.
- pending.parent.mkdir(parents=True, exist_ok=True)
- pending.write_text("source update tail not finished\n", encoding="utf-8")
+ refuse_foreign_owned_venv(root)
+ arm_completion(root)
# Main-era installers selected [all] but had no PM ledger. Established
# PM installs retain their recorded extras and plugin union instead.
extras = ["all"] if not runtime_facts_path(root).is_file() else None
@@ -251,7 +295,7 @@ def _finish_source_update(root: Path, *, current: bool, pending: Path) -> None:
raise RuntimeError(
"source update completion failed; run `hermes update` to finish it"
)
- pending.unlink()
+ clear_completion(root)
def relaunch_command(
diff --git a/tests/hermes_cli/test_review_update_runtime.py b/tests/hermes_cli/test_review_update_runtime.py
new file mode 100644
index 00000000000..c1b1a8819fc
--- /dev/null
+++ b/tests/hermes_cli/test_review_update_runtime.py
@@ -0,0 +1,87 @@
+"""Source update safety at the bootstrap and completion boundaries."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli import source_completion, venv_sync
+
+
+def test_pre_pm_version_reads_checkout_stamp_without_importing_pm():
+ root = Path(__file__).resolve().parents[2]
+ code = (
+ "import builtins\n"
+ "original = builtins.__import__\n"
+ "def restricted(name, *args, **kwargs):\n"
+ " if name == 'pm' or name.startswith('pm.'):\n"
+ " raise ModuleNotFoundError(\"No module named 'pm'\", name='pm')\n"
+ " return original(name, *args, **kwargs)\n"
+ "builtins.__import__ = restricted\n"
+ "from hermes_cli import __version__\n"
+ "print(__version__)\n"
+ )
+ result = subprocess.run([sys.executable, "-c", code], cwd=root, capture_output=True,
+ text=True, encoding="utf-8", timeout=20)
+ assert result.returncode == 0, result.stderr
+ stamp = root / "install-stamp.json"
+ expected = json.loads(stamp.read_text(encoding="utf-8-sig")).get("baseVersion") if stamp.exists() else None
+ assert result.stdout.strip() == (expected or "0.0.0")
+
+
+def test_foreign_owned_venv_file_refused_before_sync(tmp_path, monkeypatch):
+ from pm import environments
+
+ checkout = tmp_path / "checkout"
+ installer = checkout / "venv/lib/python3.14/site-packages/pkg.dist-info/INSTALLER"
+ installer.parent.mkdir(parents=True)
+ installer.write_text("pip\n", encoding="utf-8")
+ monkeypatch.setattr(environments, "selected_venv", lambda root: checkout / "venv")
+ original_lstat = Path.lstat
+ foreign_uid = os.geteuid() + 1
+
+ def stat(path, *args, **kwargs):
+ if path == installer:
+ return SimpleNamespace(st_uid=foreign_uid)
+ return original_lstat(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "lstat", stat)
+ with pytest.raises(RuntimeError, match="INSTALLER.*owned by uid"):
+ venv_sync.refuse_foreign_owned_venv(checkout)
+
+
+def test_completed_maintenance_survives_stamp_io_error(tmp_path, monkeypatch, capsys):
+ from hermes_cli import source_build, source_stamp, update_cmd_maint
+
+ monkeypatch.setattr(venv_sync, "publish_launchers", lambda root: None)
+ monkeypatch.setattr(source_build, "build_update_products", lambda root, *, desktop: None)
+ monkeypatch.setattr(update_cmd_maint, "_run_post_update_maintenance", lambda **kwargs: True)
+ monkeypatch.setattr(source_stamp, "write_source_stamp", lambda root: (_ for _ in ()).throw(OSError("readonly")))
+ assert source_completion.complete_source_checkout(tmp_path, desktop=False, assume_yes=True)
+ assert "completed, but the install stamp" in capsys.readouterr().err
+
+
+def test_sealed_stamp_reader_honors_external_install_root(tmp_path, monkeypatch):
+ from pm import paths
+
+ stamped = tmp_path / "payload"
+ stamped.mkdir()
+ (tmp_path / "install-stamp.json").write_text(json.dumps({"updateMechanism": "external"}), encoding="utf-8")
+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(tmp_path))
+ # The executing tree may be mapped into a wrapper-owned installation root.
+ monkeypatch.setattr(paths, "repo_root", lambda: stamped)
+ monkeypatch.setattr(paths, "install_root", lambda: tmp_path)
+ assert venv_sync._is_sealed(stamped) is True
+
+
+def test_developer_checkout_skips_managed_runtime_warning(tmp_path, monkeypatch):
+ import pm
+
+ checkout = tmp_path / "checkout"
+ (checkout / ".git").mkdir(parents=True)
+ monkeypatch.setattr(pm, "activate", lambda: pytest.fail("dev checkout activated managed runtime"))
+ assert venv_sync.check_runtime(checkout) is None
diff --git a/tests/hermes_cli/test_source_launcher_publication.py b/tests/hermes_cli/test_source_launcher_publication.py
index ade25b261cc..337bc9156c1 100644
--- a/tests/hermes_cli/test_source_launcher_publication.py
+++ b/tests/hermes_cli/test_source_launcher_publication.py
@@ -42,7 +42,8 @@ def fixture_tree(tmp_path, monkeypatch):
)
for path in (repo / "hermes_cli/main.py", repo / "acp_adapter/entry.py"):
path.write_text(entry, encoding="utf-8")
- home = tmp_path / "custom 'café home"
+ home = tmp_path / ".hermes"
+ monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.delenv("HERMES_RUNTIME_DIR", raising=False)
store = home / "tools"
@@ -105,6 +106,25 @@ def test_source_launchers_boot_selected_generation_from_custom_home(tmp_path, mo
assert not (repo / "venv").exists()
+def test_launcher_resolves_default_home_at_use_not_publication(tmp_path, monkeypatch):
+ repo, published_home, _ = fixture_tree(tmp_path, monkeypatch)
+ launcher = Path(_launchers.ensure_install_launchers(repo, tmp_path / "commands")[0])
+ new_user_home = tmp_path / "second-user"
+ new_user_home.mkdir()
+ monkeypatch.setenv("HOME", str(new_user_home))
+ monkeypatch.setenv("HERMES_HOME", str(new_user_home / ".hermes"))
+ select_generation(repo, "second", "from-second-user")
+ env = dict(os.environ)
+ env.pop("HERMES_HOME")
+ result = subprocess.run([str(launcher)], cwd=tmp_path, env=env,
+ capture_output=True, text=True, encoding="utf-8", timeout=30)
+ assert result.returncode == 7, result.stdout + result.stderr
+ assert json.loads(result.stdout)["home"] == str(new_user_home / ".hermes")
+ assert json.loads(result.stdout)["value"] == "from-second-user"
+ assert published_home != new_user_home / ".hermes"
+
+
@pytest.mark.parametrize("publisher", [
pytest.param("boot", marks=pytest.mark.platforms("posix")),
pytest.param("repair", marks=pytest.mark.platforms("posix")),
diff --git a/tests/hermes_cli/test_update_completion_process.py b/tests/hermes_cli/test_update_completion_process.py
index 9142fc90f10..406f2e1dc03 100644
--- a/tests/hermes_cli/test_update_completion_process.py
+++ b/tests/hermes_cli/test_update_completion_process.py
@@ -72,6 +72,15 @@ def transition(tmp_path):
(package / "venv_sync.py").write_text(
"from hermes_cli.probe import event\n"
"publish_launchers = lambda root: event('launchers')\n"
+ "refuse_foreign_owned_venv = lambda root: None\n"
+ "from pathlib import Path\n"
+ "import os\n"
+ "def arm_completion(root):\n"
+ " path = Path(os.environ['HERMES_HOME']) / 'completion-pending'\n"
+ " path.write_text('owed')\n"
+ " return path\n"
+ "def clear_completion(root):\n"
+ " (Path(os.environ['HERMES_HOME']) / 'completion-pending').unlink()\n"
)
(package / "source_build.py").write_text(
"from hermes_cli.probe import event\n"
@@ -184,6 +193,7 @@ def test_old_process_new_git_tree_completes_in_fresh_python(transition, tmp_path
assert response["exit_code"] == 0
assert response["receipt"]["update_id"] == request["receipt"]["update_id"]
assert response["windows_resume"]["resume_needed"] is False
+ assert not (Path(request["home"]) / "completion-pending").exists()
events = [json.loads(line) for line in (root / "events.jsonl").read_text().splitlines()]
by_name = {event["name"]: event for event in events}
assert by_name["activate"]["pid"] == by_name["build"]["pid"]
@@ -342,6 +352,7 @@ def test_failed_build_preserves_exit_status_without_maintenance(transition):
result = update_completion.run_completion(request)
assert result["exit_code"] == 23
assert result["receipt"]["outcome"] == "failed"
+ assert (Path(request["home"]) / "completion-pending").read_text() == "owed"
events = [json.loads(line)["name"] for line in (root / "events.jsonl").read_text().splitlines()]
assert "maintenance" not in events
assert "restart" not in events