The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(windows): only the home new consoles use may write the User PATH
emozilla74b644aaa4c7
diff --git a/hermes_cli/_install_repair.py b/hermes_cli/_install_repair.pyindex 2ab15e2c25e..7897340dd64 100644--- a/hermes_cli/_install_repair.py+++ b/hermes_cli/_install_repair.py@@ -257,7 +257,8 @@ def migrate_windows_bin_path(2. verify both launchers are present there — otherwise STOP, leavingthe user PATH untouched (never strip a working entry before itsreplacement is proven);- 3. ensure the managed binary dir is on the user PATH (prepend);+ 3. ensure the managed binary dir is on the user PATH (prepend), only+ when new consoles resolve this home (``_launchers.owns_user_path``);4. strip the legacy entries: ``<root>\\bin`` (in-checkout launcher dirthe update autostash could sweep) and ``<root>\\venv\\Scripts``(shadowed the user's ``python``, #83797).@@ -300,6 +301,14 @@ def migrate_windows_bin_path():return False # staging incomplete — leave the PATH alone+ try:+ from hermes_cli._launchers import owns_user_path++ if not owns_user_path(home):+ return False # new consoles resolve another home; leave the User PATH to it+ except (ImportError, OSError, ValueError): # an old updater's _launchers, or a failed Win32 call+ return False+if read_user_path is None:read_user_path = _read_user_path_rawif write_user_path is None:diff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.pyindex 61ca4d8ef77..1e6eb47bc27 100644--- a/hermes_cli/_launchers.py+++ b/hermes_cli/_launchers.py@@ -740,7 +740,8 @@ def expose_cli(project_root: Path | None = None, *, create: bool = True) -> dictmacOS CLI-first launches link the bundle's signed shims directly; Electronneed not have run. Source installs converge on the store launcher owner.- Shell rc/PATH registration remains installer-owned.+ POSIX shell rc registration remains installer-owned. On Windows the User+ PATH entry is repaired only for the home new consoles use (owns_user_path).Before dependency sync succeeds, create=False maintains only commands wealready own, without loading application config or enabling new exposure.@@ -795,6 +796,96 @@ def expose_cli(project_root: Path | None = None, *, create: bool = True) -> dictreturn {"ok": False, "error": str(exc)}+_TOKEN_DUPLICATE = 0x0002+_TOKEN_QUERY = 0x0008+++def _new_console_environment() -> dict[str, str] | None:+ """The environment Windows gives a new process of this user, or None.++ CreateEnvironmentBlock builds it from the user's stored variables+ (HKCU\\Environment, the profile folders, the system variables) and ignores+ this process's environment. A sandbox that overrides HERMES_HOME or+ LOCALAPPDATA for its own processes does not change the result. Names are+ upper-cased because Windows compares them case-insensitively.+ """+ import ctypes+ from ctypes import wintypes++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)+ userenv = ctypes.WinDLL("userenv", use_last_error=True)+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ advapi32.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]+ userenv.CreateEnvironmentBlock.argtypes = [ctypes.POINTER(ctypes.c_void_p), wintypes.HANDLE, wintypes.BOOL]+ userenv.DestroyEnvironmentBlock.argtypes = [ctypes.c_void_p]++ token = wintypes.HANDLE()+ if not advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), _TOKEN_QUERY | _TOKEN_DUPLICATE,+ ctypes.byref(token)):+ return None+ block = ctypes.c_void_p()+ try:+ if not userenv.CreateEnvironmentBlock(ctypes.byref(block), token, False):+ return None+ return _read_environment_block(block.value)+ finally:+ if block.value:+ userenv.DestroyEnvironmentBlock(block)+ kernel32.CloseHandle(token)+++def _read_environment_block(address: int) -> dict[str, str]:+ """Parse a Windows environment block: NUL-terminated UTF-16 ``NAME=value`` entries, then an empty one.++ The cursor advances by UTF-16 code units, not Python characters: a value+ holding a character outside the Basic Multilingual Plane (an emoji) takes+ two units and one character.+ """+ import ctypes++ environ: dict[str, str] = {}+ cursor = address+ while entry := ctypes.wstring_at(cursor):+ name, _, value = entry.partition("=")+ if name: # "=C:=C:\..." entries carry per-drive directories, not variables+ environ[name.upper()] = value+ cursor += len(entry.encode("utf-16-le", "surrogatepass")) + ctypes.sizeof(ctypes.c_wchar)+ return environ+++def new_console_hermes_root() -> Path | None:+ """The Hermes root that a newly opened console resolves, or None when Windows cannot say."""+ from hermes_constants import hermes_root_for_environment++ environ = _new_console_environment()+ return None if environ is None else hermes_root_for_environment(environ)+++def owns_user_path(root: Path) -> bool:+ """May ``root`` put its commands on the User PATH?++ Every console the user opens reads the User PATH, so only the root that+ new consoles resolve may register there. A custom root qualifies only when+ HERMES_HOME is stored as a user variable. A process whose own HERMES_HOME,+ LOCALAPPDATA or USERPROFILE override selects a different root (a review+ sandbox, a test home, a suffixed data directory) gets False. So does any+ root when Windows cannot report the console environment.+ """+ console_root = new_console_hermes_root()+ if console_root is not None and (+ os.path.normcase(os.path.realpath(root)) == os.path.normcase(os.path.realpath(console_root))+ ):+ return True+ import logging++ logging.getLogger(__name__).info(+ "User PATH left unchanged: new consoles use %s, not %s",+ console_root or "an unknown Hermes home", root)+ return False++def _merge_user_path(existing: str, entry: str) -> str | None:"""``entry`` first, or None when the PATH already names it.@@ -849,7 +940,8 @@ def _expose_windows_user_bin(root: Path, *, create: bool) -> dict:Stage the user-facing commands into ``$HERMES_HOME\\bin`` and register thatdirectory in the User PATH -- the same two things scripts/install.ps1 does --so an update converges a machine installed under the older venv\\Scripts- convention instead of leaving it there forever.+ convention instead of leaving it there forever. The registration happens+ only when new consoles resolve this home (``owns_user_path``)."""from hermes_constants import get_default_hermes_root@@ -863,8 +955,11 @@ def _expose_windows_user_bin(root: Path, *, create: bool) -> dict:written = ensure_install_launchers(root, directory)if len(written) != len(WINDOWS_BIN_LAUNCHERS):return {"ok": False, "error": "source launcher publication failed"}- return {"ok": True, "path": _register_windows_user_path(directory),- "written": [Path(path).name for path in written]}+ names = [Path(path).name for path in written]+ if not owns_user_path(directory.parent):+ # New consoles resolve another home; its launchers stay in its own bin.+ return {"ok": True, "skipped": "User PATH belongs to the home new consoles use", "written": names}+ return {"ok": True, "path": _register_windows_user_path(directory), "written": names}except OSError as exc:return {"ok": False, "error": str(exc)}diff --git a/hermes_constants.py b/hermes_constants.pyindex dc3dfd1599f..98507d5fdb0 100644--- a/hermes_constants.py+++ b/hermes_constants.py@@ -9,7 +9,7 @@ import reimport shutilimport statimport sys-from collections.abc import MutableMapping+from collections.abc import Callable, Mapping, MutableMappingfrom contextvars import ContextVar, Tokenfrom pathlib import Path@@ -48,14 +48,64 @@ def _expand_hermes_home(path: str) -> Path:return Path(os.path.expanduser(os.path.expandvars(path)))-def _get_platform_default_hermes_home() -> Path:- """Return the platform default with the literal data-directory suffix."""- suffix = os.environ.get("HERMES_DATA_DIR_SUFFIX", "")+def _platform_default_hermes_home(environ: Mapping[str, str], user_home: Callable[[], Path]) -> Path:+ """The platform default that *environ* names, with the literal data-directory suffix."""+ suffix = environ.get("HERMES_DATA_DIR_SUFFIX", "")if sys.platform == "win32":- local_appdata = os.environ.get("LOCALAPPDATA", "").strip()- base = Path(local_appdata) if local_appdata else Path.home() / "AppData" / "Local"+ local_appdata = environ.get("LOCALAPPDATA", "").strip()+ base = Path(local_appdata) if local_appdata else user_home() / "AppData" / "Local"return base / ("hermes" + suffix)- return Path.home() / (".hermes" + suffix)+ return user_home() / (".hermes" + suffix)+++def _get_platform_default_hermes_home() -> Path:+ """Return the platform default with the literal data-directory suffix."""+ return _platform_default_hermes_home(os.environ, Path.home)+++def _hermes_root_of(native_home: Path, env_path: Path | None) -> Path:+ """The root that holds *env_path*: the native home, a custom root, or *env_path* itself."""+ if env_path is None:+ return native_home+ try:+ env_path.resolve().relative_to(native_home.resolve()) # under ~/.hermes (normal or profile mode)+ except ValueError: # Docker/custom root: <root>/profiles/<name> -> <root>, else HERMES_HOME itself+ return env_path.parent.parent if env_path.parent.name == "profiles" else env_path+ return native_home+++_ENV_REFERENCE = re.compile(r"%([^%]+)%|\$\{([^}]+)\}|\$([A-Za-z0-9_-]+)")+++def hermes_root_for_environment(environ: Mapping[str, str]) -> Path | None:+ """The Hermes root that a process started with *environ* resolves, or None.++ Applies the root rules of ``get_default_hermes_root`` to another process's+ environment. ``%NAME%``, ``${NAME}`` and ``$NAME`` references and a leading+ ``~`` expand from *environ* alone, never from this process. Returns None+ when the answer depends on anything outside *environ*: a relative+ HERMES_HOME, an undefined variable, or a missing user profile folder.+ """+ names = {key.upper(): value for key, value in environ.items()}+ profile = names.get("USERPROFILE" if sys.platform == "win32" else "HOME", "").strip()++ def user_home() -> Path:+ if not profile:+ raise LookupError("no user profile folder")+ return Path(profile)++ raw = names.get("HERMES_HOME", "").strip()+ try:+ native_home = _platform_default_hermes_home(names, user_home)+ if not raw:+ return native_home+ expanded = _ENV_REFERENCE.sub(lambda match: names[match.group(match.lastindex).upper()], raw)+ if expanded == "~" or expanded.startswith(("~/", "~\\")):+ expanded = str(user_home()) + expanded[1:]+ except LookupError:+ return None+ env_path = Path(expanded)+ return _hermes_root_of(native_home, env_path) if env_path.is_absolute() else Nonedef sudo_invoker_default_home() -> Path | None:@@ -226,12 +276,7 @@ def get_default_hermes_root(*, home: str | Path | None = None) -> Path:memo = _default_hermes_root_memoif memo is not None and memo[:2] == memo_key:return memo[2]- result = native_home- if env_path is not None:- try:- env_path.resolve().relative_to(native_home.resolve()) # under ~/.hermes (normal or profile mode)- except ValueError: # Docker/custom root: <root>/profiles/<name> -> <root>, else HERMES_HOME itself- result = env_path.parent.parent if env_path.parent.name == "profiles" else env_path+ result = _hermes_root_of(native_home, env_path)_default_hermes_root_memo = (*memo_key, result)return resultdiff --git a/scripts/install.ps1 b/scripts/install.ps1index 1e97d13b659..4c905bc9c4e 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -1199,10 +1199,9 @@ function Invoke-SourceCompletion([bool]$Desktop) {}function Publish-UserCommand {- # PATH exposure stays installer-owned on Windows: expose_cli() answers- # "windows-installer-owned" rather than creating the user-facing command,- # so the install-scoped launchers the completion publishes are not the ones- # the user's PATH points at.+ # Stage the user-facing commands into $HermesHome\bin and put that folder on+ # the User PATH. Updates repair this entry through expose_cli(), which edits+ # the User PATH only for the home that new consoles use.$binDir = Join-Path $HermesHome "bin"$bootPy = Get-BootstrapPythonPush-Location $InstallDirdiff --git a/tests/hermes_cli/test_ensure_windows_bin_launchers.py b/tests/hermes_cli/test_ensure_windows_bin_launchers.pyindex de8e414f032..498bbea76fc 100644--- a/tests/hermes_cli/test_ensure_windows_bin_launchers.py+++ b/tests/hermes_cli/test_ensure_windows_bin_launchers.py@@ -31,6 +31,7 @@ import pytest# Real launcher serialization is host-dependent, despite injectable registry I/O.pytestmark = pytest.mark.platforms("windows")+from hermes_cli import _launchersfrom hermes_cli._install_repair import (_WINDOWS_BIN_LAUNCHERS,_normalize_windows_path,@@ -41,13 +42,15 @@ from hermes_cli._install_repair import (def _make_managed(tmp_path, monkeypatch):"""Fake managed layout: HERMES_HOME/hermes-agent/venv (+ a fake venv- python whose path legacy trampolines would embed)."""+ python whose path legacy trampolines would embed). New consoles resolve+ this home, so the PATH migration may edit the (injected) User PATH."""home = tmp_path / "hermes"root = home / "hermes-agent"(root / "venv" / "Scripts").mkdir(parents=True)(root / "venv" / "Scripts" / "python.exe").write_bytes(b"MZ fake venv python")(root / "venv" / "pyvenv.cfg").write_text("home = X\n", encoding="utf-8")monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(_launchers, "new_console_hermes_root", lambda: home)return home, root@@ -365,6 +368,36 @@ def test_migration_refuses_empty_store_without_changing_path(tmp_path, monkeypatassert state["writes"] == 0+def test_migration_leaves_path_when_new_consoles_use_another_home(managed_install, tmp_path, monkeypatch):+ """A sandbox's managed clone stages its own launchers but never edits the User PATH."""+ home, root = managed_install+ monkeypatch.setattr(_launchers, "new_console_hermes_root", lambda: tmp_path / "real-home")+ state, read, write = _fake_registry([str(root / "bin"), r"C:\Windows\system32"])++ ok = migrate_windows_bin_path(+ root, windows=True, read_user_path=read, write_user_path=write+ )++ assert not ok+ assert state["writes"] == 0+ for name in _WINDOWS_BIN_LAUNCHERS:+ assert _launcher_files(home / "bin", name)+++def test_migration_fails_closed_when_the_console_check_raises(managed_install, monkeypatch):+ """The migration promises never to raise, so a failing console check leaves the PATH alone."""+ _home, root = managed_install++ def broken():+ raise OSError("CreateEnvironmentBlock failed")++ monkeypatch.setattr(_launchers, "new_console_hermes_root", broken)+ state, read, write = _fake_registry([str(root / "bin")])++ assert not migrate_windows_bin_path(root, windows=True, read_user_path=read, write_user_path=write)+ assert state["writes"] == 0++def test_migration_skips_source_checkouts(tmp_path, monkeypatch):home = tmp_path / "hermes-home"home.mkdir()diff --git a/tests/hermes_cli/test_post_update_expose_cli.py b/tests/hermes_cli/test_post_update_expose_cli.pyindex 4f57c5e222e..ab3b0be481c 100644--- a/tests/hermes_cli/test_post_update_expose_cli.py+++ b/tests/hermes_cli/test_post_update_expose_cli.py@@ -72,6 +72,115 @@ def test_windows_converges_on_the_installer_user_bin(create, monkeypatch, tmp_paassert calls == [create]+def user_path_writes(monkeypatch):+ """User PATH registrations, recorded instead of written to the registry.++ Launcher publication is stubbed: these tests cover only the registration+ decision, and publication has its own tests."""+ registered = []+ monkeypatch.setattr(_launchers, "ensure_install_launchers",+ lambda root, out: [str(out / f"{name}.exe") for name in _launchers.WINDOWS_BIN_LAUNCHERS])+ monkeypatch.setattr(_launchers, "_register_windows_user_path",+ lambda entry: registered.append(Path(entry)) or "added")+ return registered++[email protected]("windows")+def test_sandbox_home_keeps_its_launchers_off_the_user_path(user_path_writes, tmp_path, monkeypatch):+ """A review sandbox's HERMES_HOME publishes into its own bin and never reaches the User PATH.++ The console environment is not stubbed: Windows builds it from the user's+ stored variables, so these overrides are exactly what a sandbox sets."""+ box = tmp_path / "box"+ monkeypatch.setenv("HERMES_HOME", str(box / "hermes"))+ monkeypatch.setenv("LOCALAPPDATA", str(box / "local"))+ monkeypatch.setenv("USERPROFILE", str(box / "user"))++ result = _launchers._expose_windows_user_bin(tmp_path / "checkout", create=True)++ assert result["ok"] and result["skipped"]+ assert result["written"] == [f"{name}.exe" for name in _launchers.WINDOWS_BIN_LAUNCHERS]+ assert user_path_writes == []++[email protected]("windows")[email protected]("hermes_home", [None, ("hermes",), ("hermes", "profiles", "work")])+def test_the_home_new_consoles_use_registers_its_bin(user_path_writes, hermes_home, tmp_path, monkeypatch):+ local = tmp_path / "local"+ monkeypatch.setenv("LOCALAPPDATA", str(local))+ if hermes_home is None:+ monkeypatch.delenv("HERMES_HOME", raising=False)+ else:+ monkeypatch.setenv("HERMES_HOME", str(local.joinpath(*hermes_home)))+ monkeypatch.setattr(_launchers, "_new_console_environment", lambda: {"LOCALAPPDATA": str(local)})++ result = _launchers._expose_windows_user_bin(tmp_path / "checkout", create=True)++ assert result["path"] == "added"+ assert user_path_writes == [local / "hermes" / "bin"]++[email protected]("windows")[email protected]("stored_home, override", [+ ("%LOCALAPPDATA%\\hermes-data", "LOCALAPPDATA"),+ ("~\\hermes-data", "USERPROFILE"),+])+def test_inherited_home_reference_expands_from_the_console_environment(+ user_path_writes, stored_home, override, tmp_path, monkeypatch):+ """A sandbox that inherits a stored HERMES_HOME such as %LOCALAPPDATA%\\x and overrides+ LOCALAPPDATA resolves a different root from a new console, so it must not match."""+ real = tmp_path / "real"+ console = {"LOCALAPPDATA": str(real / "local"), "USERPROFILE": str(real / "user"), "HERMES_HOME": stored_home}+ monkeypatch.setattr(_launchers, "_new_console_environment", lambda: dict(console))+ monkeypatch.setenv("LOCALAPPDATA", console["LOCALAPPDATA"])+ monkeypatch.setenv("USERPROFILE", console["USERPROFILE"])+ monkeypatch.setenv("HERMES_HOME", stored_home)+ monkeypatch.setenv(override, str(tmp_path / "box" / override.lower()))++ result = _launchers._expose_windows_user_bin(tmp_path / "checkout", create=True)++ assert result["skipped"]+ assert user_path_writes == []++[email protected]("windows")+def test_unknown_console_environment_leaves_the_user_path(user_path_writes, tmp_path, monkeypatch):+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local"))+ monkeypatch.delenv("HERMES_HOME", raising=False)+ monkeypatch.setattr(_launchers, "_new_console_environment", lambda: None)++ assert _launchers._expose_windows_user_bin(tmp_path / "checkout", create=True)["skipped"]+ assert user_path_writes == []++[email protected]("windows")+def test_new_console_environment_ignores_this_process(tmp_path, monkeypatch):+ """The real Win32 read: variables set only in this process are absent from a new console's environment."""+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local"))+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))+ monkeypatch.setenv("HERMES_TEST_ONLY_IN_THIS_PROCESS", "1")++ environ = _launchers._new_console_environment()++ assert environ is not None+ assert "HERMES_TEST_ONLY_IN_THIS_PROCESS" not in environ+ assert environ.get("LOCALAPPDATA")+ assert Path(environ["LOCALAPPDATA"]) != tmp_path / "local"+ assert environ.get("HERMES_HOME") != str(tmp_path / "hermes")++[email protected]("windows")+def test_environment_block_reader_counts_utf16_units():+ """An emoji takes two UTF-16 units but one Python character; the variables after it must survive."""+ import ctypes++ block = ctypes.create_unicode_buffer("A=1\0MOOD=\U0001F600\0HERMES_HOME=C:\\h\0=C:=C:\\\0\0")++ assert _launchers._read_environment_block(ctypes.addressof(block)) == {+ "A": "1", "MOOD": "\U0001F600", "HERMES_HOME": "C:\\h"}++def test_registered_as_a_home_step():assert ("expose_cli", _launchers.expose_cli) in post_update.HOME_STEPSdiff --git a/tests/test_hermes_constants.py b/tests/test_hermes_constants.pyindex af1919d8fea..a8a46c8035d 100644--- a/tests/test_hermes_constants.py+++ b/tests/test_hermes_constants.py@@ -70,6 +70,33 @@ class TestGetDefaultHermesRoot:assert get_default_hermes_root() == local_appdata / "hermes"+ @pytest.mark.platforms("windows")+ def test_root_for_another_environment_ignores_this_process(self, tmp_path, monkeypatch):+ """hermes_root_for_environment applies the root rules to the mapping it gets."""+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "sandbox-local"))+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "sandbox-home"))+ local = tmp_path / "local"+ user = tmp_path / "user"+ custom = tmp_path / "data"+ cases = [+ ({"LOCALAPPDATA": str(local)}, local / "hermes"),+ ({"LOCALAPPDATA": str(local), "HERMES_HOME": str(local / "hermes" / "profiles" / "work")},+ local / "hermes"),+ ({"LOCALAPPDATA": str(local), "HERMES_HOME": str(custom / "profiles" / "work")}, custom),+ ({"LOCALAPPDATA": str(local), "HERMES_DATA_DIR_SUFFIX": "-magic"}, local / "hermes-magic"),+ ({"localappdata": str(local), "HERMES_HOME": "%LocalAppData%\\data"}, local / "data"),+ ({"LOCALAPPDATA": str(local), "HERMES_HOME": "$LOCALAPPDATA\\data"}, local / "data"),+ ({"LOCALAPPDATA": str(local), "HERMES_HOME": "${LOCALAPPDATA}\\data"}, local / "data"),+ ({"LOCALAPPDATA": str(local), "USERPROFILE": str(user), "HERMES_HOME": "~\\data"}, user / "data"),+ ({"USERPROFILE": str(user)}, user / "AppData" / "Local" / "hermes"),+ ({"LOCALAPPDATA": str(local), "HERMES_HOME": "relative\\data"}, None),+ ({"LOCALAPPDATA": str(local), "HERMES_HOME": "%UNDEFINED%\\data"}, None),+ ({"LOCALAPPDATA": str(local), "HERMES_HOME": "~\\data"}, None),+ ({}, None),+ ]+ for environ, root in cases:+ assert hermes_constants.hermes_root_for_environment(environ) == root, environ+