The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): keep shared launchers off foreign HERMES_HOME interpreters
Finn7630782256ddd31
diff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.pyindex 5e530c50b40..ec862f301d7 100644--- a/hermes_cli/_launchers.py+++ b/hermes_cli/_launchers.py@@ -405,13 +405,122 @@ def stage_launcher(name: str, repo_root: Path, out_dir: Path) -> Path | None:return None+def _first_token(line: str) -> Path | None:+ """First whitespace-delimited token of *line*, honoring one quote pair.++ The published launchers always carry the interpreter as the first token+ (quoted only when the path holds spaces), so full shell lexing — which+ would also eat Windows backslashes as escapes — is the wrong tool."""+ text = line.strip()+ if not text:+ return None+ if text[0] in "\"'":+ end = text.find(text[0], 1)+ if end == -1:+ return None+ return Path(text[1:end])+ return Path(text.split(None, 1)[0])+++def _launcher_python(target: Path) -> Path | None:+ """Embedded interpreter of an existing launcher, else None.++ Fail-open: an unrecognized layout republishes exactly as before."""+ try:+ data = Path(target).read_bytes()+ except OSError:+ return None+ line: str | None = None+ suffix = Path(target).suffix.lower()+ if suffix == ".exe":+ # distlib native launcher: loader stub, "#!<python> -I" shebang, zip.+ # Anchor on the archive start: the shebang is the last #! line before+ # it. (The stub itself can carry an earlier #! inside a UTF-16 message,+ # and even a stray PK signature, so neither a prefix split nor the+ # first match is reliable.)+ idx = data.find(b"PK\x03\x04")+ if idx == -1:+ return None+ start = data.rfind(b"#!", 0, idx)+ if start == -1:+ return None+ end = data.find(b"\n", start, idx)+ if end == -1:+ return None+ try:+ line = data[start + 2:end].decode("utf-8").strip()+ except UnicodeDecodeError:+ return None+ else:+ try:+ text = data.decode("utf-8-sig")+ except UnicodeDecodeError:+ return None+ lines = text.splitlines()+ if suffix == ".cmd":+ # "@echo off", then '"<python>" -I -c "<code>" %*'. The file's+ # own \r\n pair gains a translated extra \r on Windows writes,+ # so the command may sit past a blank line — never assume its index.+ line = next((entry for entry in lines[1:] if entry.strip()), None)+ if line is None:+ return None+ else:+ # POSIX shell wrapper: "#!/bin/sh", then "exec <python> -I -c ...".+ line = next((entry for entry in lines if entry.startswith("exec ")), None)+ if line is None:+ return None+ line = line.removeprefix("exec ")+ try:+ return _first_token(line)+ except (ValueError, OSError):+ return None+++def _kept_shared_launcher(name: str, local: Path, store: Path) -> Path | None:+ """Existing checkout launcher already bound outside this root's store.++ Checkout launchers are shared by every HERMES_HOME; a launch under one+ data root must never repoint them at another root's interpreter (#123238):+ once that root is deleted, every hermes breaks. Keep the file when it+ execs a live interpreter outside *store*. Missing launchers, dead+ interpreters and same-store repins still publish."""+ candidates = [local / name] if not _is_windows() else [local / f"{name}.exe", local / f"{name}.cmd"]+ for target in candidates:+ try:+ present = target.is_file() or target.is_symlink()+ except OSError:+ continue+ if not present:+ continue+ python = _launcher_python(target)+ if python is None or not python.is_file():+ continue+ try:+ foreign = not python.resolve().is_relative_to(store.resolve())+ except (OSError, RuntimeError, ValueError):+ continue+ if foreign:+ return target+ return None++def ensure_install_launchers(repo_root: Path, out_dir: Path) -> list[str]:"""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]+ store = store_root(root)+ written = []+ for name in WINDOWS_BIN_LAUNCHERS:+ # ponytail: one guard here covers every caller (launch, sync, repair,+ # install); per-home outputs below stay unguarded. Upgrade to a stamped+ # owning store if shared checkouts ever need cross-home repins.+ kept = _kept_shared_launcher(name, local, store)+ if kept is not None:+ written.append(str(kept))+ continue+ if (path := stage_launcher(name, root, local)) is not None:+ written.append(str(path))if Path(out_dir).resolve() == local:return writtenif len(written) != len(WINDOWS_BIN_LAUNCHERS):diff --git a/tests/hermes_cli/test_hermes_home_shared_launchers.py b/tests/hermes_cli/test_hermes_home_shared_launchers.pynew file mode 100644index 00000000000..a97279fd79b--- /dev/null+++ b/tests/hermes_cli/test_hermes_home_shared_launchers.py@@ -0,0 +1,156 @@+"""A launch under another HERMES_HOME must not rebind shared launchers (#123238).++The checkout's ``.hermes/bin`` launchers are shared by every data root and by+the ``~/.local/bin`` shims. Rewriting them to the launching root's store+Python bricks ``hermes`` once that root is deleted. The launching process must+still relaunch into its own root's Python.+"""+import json+import os+from pathlib import Path++import pm+from hermes_cli import _launchers+from hermes_cli import venv_sync+++def _make_home(base: Path, name: str) -> tuple[Path, Path]:+ """A fake data root whose store records one live interpreter."""+ home = base / name+ store = home / "tools"+ entry = store / f"python-{name}"+ python = entry / "bin" / "python3"+ python.parent.mkdir(parents=True)+ python.touch()+ exe = entry / "python.exe"+ exe.touch()+ (store / "facts.json").write_text(json.dumps({+ "schema": 1,+ "packages": {"python": {"version": "fixture", "entry": entry.name}},+ }), encoding="utf-8")+ # resolve_store_python answers entry/bin/python3 on POSIX, entry/python.exe on Windows.+ return home, exe if os.name == "nt" else python+++def _repoint_store(home: Path, name: str) -> Path:+ """Move the fake store's recorded interpreter to a new live entry."""+ store = home / "tools"+ entry = store / f"python-{name}"+ python = entry / "bin" / "python3"+ python.parent.mkdir(parents=True)+ python.touch()+ exe = entry / "python.exe"+ exe.touch()+ (store / "facts.json").write_text(json.dumps({+ "schema": 1,+ "packages": {"python": {"version": "fixture", "entry": entry.name}},+ }), encoding="utf-8")+ return exe if os.name == "nt" else python+++def _make_repo(base: Path) -> Path:+ repo = base / "checkout"+ (repo / ".git").mkdir(parents=True)+ (repo / "pyproject.toml").write_text('[project]\nname = "x"\nversion = "0"\n', encoding="utf-8")+ (repo / "install-stamp.json").write_text(json.dumps({"updateMechanism": "self"}), encoding="utf-8")+ return repo+++def _isolate(tmp_path, monkeypatch, home: Path) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ if os.name == "nt":+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.delenv("HERMES_RUNTIME_DIR", raising=False)+ monkeypatch.delenv("HERMES_DISABLE_LAZY_INSTALLS", raising=False)+++def _publish(repo: Path) -> dict[str, bytes]:+ local = repo / ".hermes" / "bin"+ written = _launchers.ensure_install_launchers(repo, local)+ assert len(written) == len(_launchers.ENTRY_POINTS), written+ return {Path(p).name: Path(p).read_bytes() for p in written}+++def test_temp_home_ensure_leaves_shared_launchers_alone(tmp_path, monkeypatch):+ default_home, _ = _make_home(tmp_path, "default")+ temp_home, temp_python = _make_home(tmp_path, "temp")+ repo = _make_repo(tmp_path)++ _isolate(tmp_path, monkeypatch, default_home)+ before = _publish(repo)++ _isolate(tmp_path, monkeypatch, temp_home)+ # The cross-home condition really holds: this root resolves temp's Python.+ temp_resolved = _launchers.resolve_store_python(repo)+ assert temp_resolved is not None+ assert temp_resolved.resolve() == temp_python.resolve()+ again = _launchers.ensure_install_launchers(repo, repo / ".hermes" / "bin")+ assert len(again) == len(_launchers.ENTRY_POINTS)+ for path in again:+ assert Path(path).read_bytes() == before[Path(path).name]+++def test_temp_home_prepare_launch_relaunches_without_rebinding(tmp_path, monkeypatch):+ default_home, _ = _make_home(tmp_path, "default")+ temp_home, temp_python = _make_home(tmp_path, "temp")+ repo = _make_repo(tmp_path)++ _isolate(tmp_path, monkeypatch, default_home)+ before = _publish(repo)++ _isolate(tmp_path, monkeypatch, temp_home)+ monkeypatch.setattr(pm, "venv_is_current", lambda **kwargs: True)+ target = venv_sync.prepare_launch(repo, [])+ assert target is not None+ assert target.resolve() == temp_python.resolve()+ for name, content in before.items():+ assert (repo / ".hermes" / "bin" / name).read_bytes() == content+++def test_missing_dead_and_same_store_launchers_still_publish(tmp_path, monkeypatch):+ default_home, _ = _make_home(tmp_path, "default")+ repo = _make_repo(tmp_path)+ _isolate(tmp_path, monkeypatch, default_home)+ local = repo / ".hermes" / "bin"++ # Missing launchers are published.+ before = _publish(repo)++ # A same-store repin is published.+ repinned = _repoint_store(default_home, "repin")+ repinned_resolved = _launchers.resolve_store_python(repo)+ assert repinned_resolved is not None+ assert repinned_resolved.resolve() == repinned.resolve()+ after = _publish(repo)+ assert after != before++ # A launcher whose interpreter is gone is repaired, not kept.+ doomed = _repoint_store(default_home, "doomed")+ doomed_resolved = _launchers.resolve_store_python(repo)+ assert doomed_resolved is not None+ assert doomed_resolved.resolve() == doomed.resolve()+ doomed.unlink()+ assert _launchers.resolve_store_python(repo) is None+ for path in local.iterdir():+ path.unlink()+ assert _launchers.ensure_install_launchers(repo, local) == []+++def test_launcher_python_reads_posix_shell_wrapper(tmp_path):+ target = tmp_path / "hermes"+ target.write_text(+ '#!/bin/sh\nexec /tmp/fake-home/tools/python-A/bin/python3 -I -c "x" "$@"\n',+ encoding="utf-8",+ )+ assert _launchers._launcher_python(target) == Path("/tmp/fake-home/tools/python-A/bin/python3")+ assert _launchers._launcher_python(tmp_path / "missing") is None+++def test_launcher_python_reads_windows_cmd_fallback(tmp_path):+ target = tmp_path / "hermes.cmd"+ target.write_text(+ '@echo off\r\n"C:\\fake home\\tools\\py\\python.exe" -I -c "eA==" %*\r\n',+ encoding="utf-8",+ )+ assert _launchers._launcher_python(target) == Path("C:\\fake home\\tools\\py\\python.exe")