Skip to content

The agent that grows with you

fix(pm): repair existing launchers before dependency installation

ethernet5a89533e1c1b
diff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.py
index f852c8108d7..98ccadab341 100644
--- a/hermes_cli/_launchers.py
+++ b/hermes_cli/_launchers.py
@@ -253,10 +253,10 @@ def _launcher_script(name: str, repo_root: Path, dependencies: Path | None) -> s
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 not target.is_symlink() and target.read_bytes() == body.encode("utf-8"):
if os.access(target, os.X_OK):
return target
- except (OSError, UnicodeError):
+ except OSError:
pass
def write(staging: Path) -> None:
@@ -295,13 +295,16 @@ def _owns_launcher(target: Path, root: Path) -> bool:
return False
-def _publish_conveniences(root: Path, out_dir: Path, names) -> dict[Path, bool]:
+def _publish_conveniences(root: Path, out_dir: Path, names, *, create: bool = True) -> dict[Path, bool]:
"""User-bin commands forward to durable local launchers, not a Python pin."""
- out_dir.mkdir(parents=True, exist_ok=True)
+ if create:
+ out_dir.mkdir(parents=True, exist_ok=True)
+ elif not out_dir.is_dir():
+ return {}
published = {}
for name in names:
target = out_dir / name
- if (target.exists() or target.is_symlink()) and not _owns_launcher(target, root):
+ if (not create or 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"]
@@ -347,29 +350,32 @@ def ensure_install_launchers(repo_root: Path, out_dir: Path) -> list[str]:
if (path := stage_launcher(name, root, Path(out_dir))) is not None]
-def expose_cli(project_root: Path | None = None) -> dict:
+def expose_cli(project_root: Path | None = None, *, create: bool = True) -> dict:
"""Repair PATH conveniences without taking over another installation's files.
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.
+
+ Before dependency sync succeeds, create=False maintains only commands we
+ already own, without loading application config or enabling new exposure.
"""
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"}
+ if create:
+ try:
+ from hermes_cli.config import load_config
+ except ImportError:
+ # Installers expose after sync; never invent a config reader here.
+ return {"ok": True, "skipped": "config-unavailable"}
+ 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"}
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":
+ if create and 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":
@@ -385,11 +391,11 @@ def expose_cli(project_root: Path | None = None) -> dict:
# 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):
+ if directory not in dirs and (not create or _owns_launcher(directory / "hermes", root)):
dirs.append(directory)
written = []
for directory in dirs:
- published = _publish_conveniences(root, directory, (*WINDOWS_BIN_LAUNCHERS, "hermes-agent"))
+ published = _publish_conveniences(root, directory, (*WINDOWS_BIN_LAUNCHERS, "hermes-agent"), create=create)
written.extend(path.name for path, changed in published.items() if changed)
return {"ok": True, "written": written}
except OSError as exc:
diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.py
index e36435321ad..02891201f5f 100644
--- a/hermes_cli/venv_sync.py
+++ b/hermes_cli/venv_sync.py
@@ -64,8 +64,8 @@ def check_runtime(project_root: Path) -> str | None:
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."""
+def publish_launchers(project_root: Path, *, create: bool = True) -> None:
+ """Refresh durable commands; bootstrap repairs only existing PATH exposure."""
from hermes_cli._launchers import ENTRY_POINTS, ensure_install_launchers, expose_cli, resolve_store_python
from hermes_cli.steward import read_install_stamp
@@ -78,7 +78,7 @@ def publish_launchers(project_root: Path) -> None:
from pm.package import InstallError
raise InstallError("launchers", "source launcher publication failed", "retry the source update")
- result = expose_cli(root)
+ result = expose_cli(root, create=create)
if not result["ok"]:
import logging
diff --git a/pm/cli.py b/pm/cli.py
index 6b4f21178f2..6b4292dc3d6 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -100,7 +100,7 @@ def _install_names(names: list[str], target: str | None = None) -> int:
if name == "python":
from hermes_cli.venv_sync import publish_launchers
- publish_launchers(repo_root())
+ publish_launchers(repo_root(), create=False)
print(f"✓ {name}", flush=True)
except InstallError as e:
print(f"✗ {e}", flush=True)
diff --git a/tests/hermes_cli/test_post_update_expose_cli.py b/tests/hermes_cli/test_post_update_expose_cli.py
index 03388b37c8e..0f49c89e7ce 100644
--- a/tests/hermes_cli/test_post_update_expose_cli.py
+++ b/tests/hermes_cli/test_post_update_expose_cli.py
@@ -30,7 +30,8 @@ def _write_bundled_stamp(repo_root: Path) -> None:
payload (payload marker + a valid updateMechanism)."""
repo_root.mkdir(parents=True, exist_ok=True)
(repo_root / "install-stamp.json").write_text(
- json.dumps({"payload": "bundled", "updateMechanism": "electron-updater"})
+ json.dumps({"payload": "bundled", "updateMechanism": "electron-updater"}),
+ encoding="utf-8",
)
@@ -44,9 +45,9 @@ def fake_install(tmp_path, monkeypatch):
root = tmp_path / "checkout"
(root / "venv" / "bin").mkdir(parents=True)
- (root / "venv" / "bin" / "python").write_text("#!fake\n")
- (root / "hermes").write_text("# entrypoint\n")
- (root / "run_agent.py").write_text("# agent\n")
+ (root / "venv" / "bin" / "python").write_text("#!fake\n", encoding="utf-8")
+ (root / "hermes").write_text("# entrypoint\n", encoding="utf-8")
+ (root / "run_agent.py").write_text("# agent\n", encoding="utf-8")
monkeypatch.setenv("HERMES_INSTALL_ROOT", str(root))
store = tmp_path / "tools"
store.mkdir()
@@ -54,13 +55,14 @@ def fake_install(tmp_path, monkeypatch):
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]),
- }}}))
+ }}}), encoding="utf-8")
return home, root
@pytest.mark.platforms("windows")
-def test_windows_is_installer_owned():
- assert _launchers.expose_cli() == {
[email protected]("create", [True, False])
+def test_windows_is_installer_owned(create):
+ assert _launchers.expose_cli(create=create) == {
"ok": True,
"skipped": "windows-installer-owned",
}
@@ -71,6 +73,49 @@ def test_registered_as_a_home_step():
class TestExposeCli:
+ @posix_only
+ @pytest.mark.parametrize("hermes", ["missing", "foreign"])
+ def test_repair_only_preserves_missing_and_foreign_commands(self, fake_install, monkeypatch, hermes):
+ home, root = fake_install
+ monkeypatch.setattr("hermes_cli.config.load_config", lambda: pytest.fail("repair read config"))
+ wrapper_dir = home / ".local" / "bin"
+ extra = home / "bin"
+ assert _launchers.expose_cli(create=False) == {"ok": True, "written": []}
+ assert not wrapper_dir.exists()
+ assert not extra.exists()
+ assert {p.name for p in (root / ".hermes/bin").iterdir()} == set(_launchers.ENTRY_POINTS)
+
+ # An owned ACP entry must be repaired even without an owned hermes
+ # sibling admitting this directory. Its old target is already gone.
+ extra.mkdir()
+ dangling = root / "venv/bin/hermes-acp"
+ acp = extra / "hermes-acp"
+ acp.symlink_to(dangling)
+ assert not acp.exists() and acp.is_symlink()
+ foreign = b"#!/bin/sh\n# user-owned caf\xc3\xa9 command\nexit 19\n"
+ if hermes == "foreign":
+ (extra / "hermes").write_bytes(foreign)
+ wrapper_dir.mkdir(parents=True)
+ (wrapper_dir / "hermes").write_bytes(foreign)
+ foreign_link = wrapper_dir / "hermes-acp"
+ foreign_target = home / "other-install/hermes-acp"
+ foreign_link.symlink_to(foreign_target)
+ before = {path: path.lstat().st_mtime_ns for path in (wrapper_dir, wrapper_dir / "hermes", foreign_link)}
+
+ assert _launchers.expose_cli(create=False) == {"ok": True, "written": ["hermes-acp"]}
+ assert acp.is_file() and not acp.is_symlink() and os.access(acp, os.X_OK)
+ assert not dangling.exists()
+ assert not (extra / "hermes-agent").exists()
+ assert not (wrapper_dir / "hermes-agent").exists()
+ if hermes == "foreign":
+ assert (extra / "hermes").read_bytes() == foreign
+ else:
+ assert not (extra / "hermes").exists()
+ assert (wrapper_dir / "hermes").read_bytes() == foreign
+ assert foreign_link.is_symlink() and foreign_link.readlink() == foreign_target
+ assert before == {path: path.lstat().st_mtime_ns for path in before}
+ assert _launchers.expose_cli(create=False) == {"ok": True, "written": []}
+
@posix_only
def test_writes_all_three_wrappers_fresh(self, fake_install):
home, root = fake_install
@@ -79,7 +124,7 @@ class TestExposeCli:
assert sorted(result["written"]) == ["hermes", "hermes-acp", "hermes-agent"]
for name in ("hermes", "hermes-agent", "hermes-acp"):
wrapper = home / ".local" / "bin" / name
- body = wrapper.read_text()
+ body = wrapper.read_text(encoding="utf-8-sig")
assert str(root) in body
assert str(root / ".hermes" / "bin") in body
assert os.access(wrapper, os.X_OK)
@@ -93,9 +138,9 @@ class TestExposeCli:
wrapper_dir = home / ".local" / "bin"
wrapper_dir.mkdir(parents=True)
foreign = f'#!/bin/sh\nexec "{other}/venv/bin/python" "{other}/hermes" "$@"\n'
- (wrapper_dir / "hermes").write_text(foreign)
+ (wrapper_dir / "hermes").write_text(foreign, encoding="utf-8")
result = _launchers.expose_cli()
- assert (wrapper_dir / "hermes").read_text() == foreign
+ assert (wrapper_dir / "hermes").read_text(encoding="utf-8-sig") == foreign
assert "hermes" not in result["written"]
# The other two had no file at all — those ARE written.
assert sorted(result["written"]) == ["hermes-acp", "hermes-agent"]
@@ -118,9 +163,12 @@ class TestExposeCli:
result = _launchers.expose_cli()
assert result == {"ok": True, "skipped": "no-store-python"}
- @pytest.mark.platforms("linux")
+ @pytest.mark.parametrize("create", [
+ pytest.param(True, marks=pytest.mark.platforms("linux")),
+ pytest.param(False, marks=posix_only),
+ ])
def test_bundled_tree_skips_bundle_owns_launchers(
- self, fake_install, monkeypatch, tmp_path
+ self, fake_install, monkeypatch, tmp_path, create
):
"""The bundle owns its shims: on Linux (AppImage: transient mount)
the step names the shape and writes nothing."""
@@ -129,10 +177,13 @@ class TestExposeCli:
(payload / "repo").mkdir()
_write_bundled_stamp(payload / "repo")
for name in ("hermes", "hermes-agent", "hermes-acp"):
- (payload / "bin" / name).write_text("\x7fELF fake shim\n")
+ (payload / "bin" / name).write_text("\x7fELF fake shim\n", encoding="utf-8")
monkeypatch.setenv("HERMES_INSTALL_ROOT", str(payload / "repo"))
- result = _launchers.expose_cli()
+ if not create:
+ monkeypatch.setattr("hermes_cli.config.load_config", lambda: pytest.fail("repair read config"))
+ result = _launchers.expose_cli(create=create)
assert result == {"ok": True, "skipped": "bundle-owns-launchers"}
+ assert not (fake_install[0] / ".local/bin").exists()
@posix_only
def test_unstamped_tree_with_sibling_bin_is_not_a_bundle(
@@ -145,7 +196,7 @@ class TestExposeCli:
(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")
+ (parent / "bin" / "hermes").write_text("#!/bin/sh\n# installer launcher\n", encoding="utf-8")
checkout = parent / "hermes-agent"
checkout.mkdir()
monkeypatch.setenv("HERMES_INSTALL_ROOT", str(checkout))
@@ -161,12 +212,12 @@ class TestExposeCli:
wrapper_dir = home / ".local" / "bin"
wrapper_dir.mkdir(parents=True)
console_script = root / "venv" / "bin" / "hermes"
- console_script.write_text("# real console script\n")
+ console_script.write_text("# real console script\n", encoding="utf-8")
(wrapper_dir / "hermes").symlink_to(console_script)
result = _launchers.expose_cli()
assert "hermes" in result["written"]
# The venv console script survives untouched…
- assert console_script.read_text() == "# real console script\n"
+ assert console_script.read_text(encoding="utf-8-sig") == "# real console script\n"
# …and the link-dir entry is now a real file, not a symlink.
assert not (wrapper_dir / "hermes").is_symlink()
@@ -183,19 +234,19 @@ def test_direct_packaged_cli_exposes_shims_before_electron(tmp_path):
_write_bundled_stamp(repo)
(repo / "install-stamp.json").write_text(json.dumps({
"payload": "bundled", "commit": "abcdef012345", "updateMechanism": "electron-updater",
- }))
+ }), encoding="utf-8")
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.write_text(f'#!/bin/sh\nexec {shlex.join([sys.executable, "-I", "-c", code])} "$@"\n', encoding="utf-8")
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)
+ capture_output=True, text=True, timeout=30, encoding="utf-8")
assert result.returncode == 0, result.stderr
for name in ("hermes", "hermes-agent", "hermes-acp"):
assert (home / ".local/bin" / name).is_symlink()
@@ -216,7 +267,7 @@ class TestSymlinkSealedLaunchers:
payload_bin = tmp_path / "Hermes.app" / "Contents" / "Resources" / "agent-payload" / "bin"
payload_bin.mkdir(parents=True)
for name in ("hermes", "hermes-agent", "hermes-acp"):
- (payload_bin / name).write_text("fake mach-o shim\n")
+ (payload_bin / name).write_text("fake mach-o shim\n", encoding="utf-8")
return home, payload_bin
def test_links_all_three_fresh(self, payload):
@@ -252,12 +303,12 @@ class TestSymlinkSealedLaunchers:
link_dir = home / ".local" / "bin"
link_dir.mkdir(parents=True)
# A real file (pipx-style launcher)…
- (link_dir / "hermes").write_text("#!/bin/sh\n# pipx launcher\n")
+ (link_dir / "hermes").write_text("#!/bin/sh\n# pipx launcher\n", encoding="utf-8")
# …and a live symlink to a different tool.
other = tmp_path / "other-tool"
- other.write_text("other\n")
+ other.write_text("other\n", encoding="utf-8")
(link_dir / "hermes-agent").symlink_to(other)
result = _launchers._symlink_sealed_launchers(payload_bin)
- assert (link_dir / "hermes").read_text() == "#!/bin/sh\n# pipx launcher\n"
+ assert (link_dir / "hermes").read_text(encoding="utf-8-sig") == "#!/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.py
index 7b810f7f71f..58566525670 100644
--- a/tests/hermes_cli/test_source_launcher_publication.py
+++ b/tests/hermes_cli/test_source_launcher_publication.py
@@ -107,6 +107,7 @@ def test_source_launchers_boot_selected_generation_from_custom_home(tmp_path, mo
@pytest.mark.parametrize("publisher", [
pytest.param("boot", marks=pytest.mark.platforms("posix")),
+ pytest.param("repair", marks=pytest.mark.platforms("posix")),
pytest.param("native", marks=pytest.mark.platforms("windows")),
pytest.param("cmd", marks=pytest.mark.platforms("windows")),
])
@@ -158,6 +159,8 @@ def test_profile_publication_preserves_shared_launcher_default_home(tmp_path, mo
result = boot_bootstrap.run_boot_bootstrap(repo)
assert result["home"]["expose_cli"]["ok"], result
assert boot_bootstrap.record_path(repo).is_file()
+ elif publisher == "repair":
+ assert _launchers.expose_cli(repo, create=False)["ok"]
else:
# Windows exposure is installer-owned. Both transports use this writer.
assert _launchers.ensure_install_launchers(repo, out)
@@ -169,7 +172,8 @@ def test_profile_publication_preserves_shared_launcher_default_home(tmp_path, mo
@pytest.mark.platforms("posix")
-def test_posix_materializer_publishes_only_executable_shell_launchers(tmp_path, monkeypatch):
[email protected]("corruption", ["bom", "crlf"])
+def test_posix_materializer_publishes_only_executable_shell_launchers(tmp_path, monkeypatch, corruption):
repo, _home, _interpreter = fixture_tree(tmp_path, monkeypatch)
out = tmp_path / "bin"
out.mkdir()
@@ -179,6 +183,20 @@ def test_posix_materializer_publishes_only_executable_shell_launchers(tmp_path,
assert set(out.iterdir()) == set(launchers)
local = repo / ".hermes" / "bin"
assert {p.name for p in local.iterdir()} == set(_launchers.ENTRY_POINTS)
+ launcher = local / "hermes"
+ expected = launcher.read_bytes()
+ launcher.write_bytes(b"\xef\xbb\xbf" + expected if corruption == "bom" else expected.replace(b"\n", b"\r\n"))
+ assert _launchers.ensure_install_launchers(repo, out)
+ # Shell executables need exact bytes: neither a BOM before #! nor CRLF is
+ # interchangeable with the generated script, even if text decoding agrees.
+ assert launcher.read_bytes() == expected
+ result = subprocess.run([str(out / "hermes"), "--print-runtime-command"],
+ capture_output=True, text=True, encoding="utf-8", timeout=30)
+ assert result.returncode == 0, result.stderr
+ assert Path(json.loads(result.stdout)[0]).samefile(_interpreter)
+ before = launcher.stat().st_mtime_ns
+ assert _launchers.ensure_install_launchers(repo, out)
+ assert launcher.stat().st_mtime_ns == before
def test_materializer_cli_refuses_missing_store_without_publishing(tmp_path, monkeypatch):
@@ -204,25 +222,25 @@ def test_boot_migrates_legacy_conveniences_to_selected_runtime(tmp_path, monkeyp
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").write_text(f'#!/bin/sh\nexec "{repo}/venv/bin/python" "{repo}/hermes" "$@"\n', encoding="utf-8")
(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')
+ f'exec "{out}/hermes" acp "$@"\n', encoding="utf-8")
foreign = f'#!/bin/sh\n# user note about {repo}\nexit 19\n'
- (out / "hermes-agent").write_text(foreign)
+ (out / "hermes-agent").write_text(foreign, encoding="utf-8")
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)
+ capture_output=True, text=True, timeout=30, encoding="utf-8")
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
+ assert (out / "hermes-agent").read_text(encoding="utf-8-sig") == 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()}
@@ -250,7 +268,7 @@ def _command_survives_generation_collection(tmp_path, monkeypatch, surface):
command = [*_resolve_direct_command(str(launcher)), *args]
elif surface == "published":
result = subprocess.run([str(launcher), "--print-runtime-command", "--", *args],
- capture_output=True, text=True, timeout=30)
+ capture_output=True, text=True, timeout=30, encoding="utf-8")
assert result.returncode == 0, result.stderr
command = json.loads(result.stdout)
else:
@@ -270,7 +288,7 @@ def _command_survives_generation_collection(tmp_path, monkeypatch, surface):
if surface not in ("legacy", "systemd", "launchd"):
assert Path(command[0]).samefile(interpreter)
assert collect_generations(repo, min_age_seconds=0) == [selected.parent.parent / "old"]
- result = subprocess.run(command, cwd=tmp_path, capture_output=True, text=True, timeout=30)
+ result = subprocess.run(command, cwd=tmp_path, capture_output=True, text=True, timeout=30, encoding="utf-8")
assert result.returncode == 7, result.stderr
assert json.loads(result.stdout)["value"] == "new"
assert json.loads(result.stdout)["argv"] == args
@@ -306,7 +324,7 @@ def test_windows_repair_upgrades_healthy_old_pm_external_launchers(tmp_path, mon
if not launcher.exists():
launcher = local / "hermes.cmd"
result = subprocess.run([str(launcher), "--print-runtime-command"], capture_output=True,
- text=True, timeout=30)
+ text=True, timeout=30, encoding="utf-8")
assert result.returncode == 0, result.stderr
assert Path(json.loads(result.stdout)[0]).samefile(interpreter)
@@ -321,7 +339,7 @@ def test_dashboard_action_boots_selected_dependencies(tmp_path, monkeypatch):
proc = web_server_gateway._spawn_hermes_action(["--version"], "gateway-restart")
try:
assert proc.wait(timeout=30) == 7
- log = (home / "logs" / web_server_gateway._ACTION_LOG_FILES["gateway-restart"]).read_text()
+ log = (home / "logs" / web_server_gateway._ACTION_LOG_FILES["gateway-restart"]).read_text(encoding="utf-8-sig")
assert json.loads(log.splitlines()[-1])["value"] == "selected"
finally:
if proc.poll() is None:
@@ -331,12 +349,13 @@ def test_dashboard_action_boots_selected_dependencies(tmp_path, monkeypatch):
@pytest.mark.parametrize("layout", ["legacy", "payload"])
def test_pre_pm_base_dependencies_activate_only_at_boot(tmp_path, monkeypatch, layout):
- repo, _, _ = fixture_tree(tmp_path, monkeypatch)
+ repo, home, _ = fixture_tree(tmp_path, monkeypatch)
environment = repo / "venv"
if layout == "payload":
environment = repo.parent / "payload-deps"
(repo.parent / "manifest.json").write_text(
- json.dumps({"repo": repo.name, "venv": environment.name}), encoding="utf-8")
+ json.dumps({"repo": repo.name, "venv": environment.name,
+ "store": (home / "tools").relative_to(repo.parent).as_posix()}), encoding="utf-8")
site = site_packages(environment)
site.mkdir(parents=True)
editable = tmp_path / "editable"
@@ -344,7 +363,7 @@ def test_pre_pm_base_dependencies_activate_only_at_boot(tmp_path, monkeypatch, l
(editable / "selected_probe.py").write_text("VALUE = 'base-pth'\n", encoding="utf-8")
(site / "member.pth").write_text(str(editable) + "\n", encoding="utf-8")
command = _launchers.runtime_command(repo)
- result = subprocess.run(command, cwd=tmp_path, capture_output=True, text=True, timeout=30)
+ result = subprocess.run(command, cwd=tmp_path, capture_output=True, text=True, timeout=30, encoding="utf-8")
assert result.returncode == 7, result.stderr
assert json.loads(result.stdout)["value"] == "base-pth"
@@ -353,7 +372,7 @@ def test_external_interpreter_keeps_its_owned_dependencies(tmp_path, monkeypatch
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "empty-store"))
command = _launchers.runtime_command(ROOT, code="import ruamel.yaml; print('external-runtime-ready')")
- result = subprocess.run(command, cwd=tmp_path, capture_output=True, text=True, timeout=30)
+ result = subprocess.run(command, cwd=tmp_path, capture_output=True, text=True, timeout=30, encoding="utf-8")
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == "external-runtime-ready"
@@ -380,37 +399,56 @@ def test_service_survives_python_tool_replacement(tmp_path, monkeypatch):
assert str(store / version) not in unit
command = shlex.split(next(line.split("=", 1)[1] for line in unit.splitlines() if line.startswith("ExecStart=")))
shutil.rmtree(store / "python-A")
- result = subprocess.run(command, cwd=tmp_path, capture_output=True, text=True, timeout=30)
+ result = subprocess.run(command, cwd=tmp_path, capture_output=True, text=True, timeout=30, encoding="utf-8")
assert result.returncode == 7, result.stderr
assert json.loads(result.stdout)["value"] == "ready"
@pytest.mark.platforms("posix")
-def test_sync_migrates_old_store_wrapper_before_python_collection(tmp_path, monkeypatch):
[email protected]("create", [True, False])
+def test_sync_migrates_old_store_wrapper_before_python_collection(tmp_path, monkeypatch, create):
+ import builtins
+
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")
+ (site / "selected_probe.py").write_text("VALUE = 'ready'\n", encoding="utf-8")
out = home / ".local/bin"
out.mkdir(parents=True)
+ if not create:
+ original_import = builtins.__import__
+
+ def without_config(name, *args, **kwargs):
+ assert name != "hermes_cli.config", "bootstrap publication imported application config"
+ return original_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", without_config)
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}}}))
+ (store / "facts.json").write_text(json.dumps({"schema": 1, "packages": {"python": {"entry": version}}}), encoding="utf-8")
if version == "python-A":
_launchers.mint_launcher("hermes", repo, out, python, None)
else:
- publish_launchers(repo)
+ if create:
+ publish_launchers(repo)
+ else:
+ publish_launchers(repo, create=False)
+ assert set(out.iterdir()) == {out / "hermes"}
+ assert not (home / "bin").exists()
+ assert not (home / "config.yaml").exists()
+ assert not (home / "skills").exists()
shutil.rmtree(store / "python-A")
result = subprocess.run([str(out / "hermes")], cwd=tmp_path,
- capture_output=True, text=True, timeout=30)
+ capture_output=True, text=True, timeout=30, encoding="utf-8")
assert result.returncode == 7, result.stderr
assert json.loads(result.stdout)["value"] == "ready"
+ assert Path(json.loads(result.stdout)["exe"]) == store / "python-B/bin/python3"
def test_update_import_probe_uses_selected_dependencies(tmp_path, monkeypatch):
diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.md
index a80f53615d7..531f97e4ece 100644
--- a/website/docs/reference/package-management.md
+++ b/website/docs/reference/package-management.md
@@ -264,8 +264,10 @@ $env:HERMES_RUNTIME_DIR = Join-Path $env:HERMES_HOME 'tools'
It makes the bootstrap and PM use the same writable store. Do not persist a
path into an installed MSIX or macOS bundle. Activation runs the setup script's
runtime-only path to provision tools and sync the `all` Python extra. It does
-not select `dev` or install JS workspaces. It also skips setup's user-facing
-installation work: shell configuration, launchers, `.env`, and bundled skills.
+not select `dev` or install JS workspaces. It maintains installation-local
+commands and repairs existing owned PATH wrappers, but does not create new PATH
+conveniences or load application configuration. It also skips setup's user-facing
+installation work: shell configuration, `.env`, and bundled skills.
Run the setup script separately if you want that full installation workflow.
Before Python exists, the shell bootstrap acquires the pinned interpreter.