_install_repair.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. """Repair Windows launchers and their registered PATH entries."""
  2. from __future__ import annotations
  3. import contextlib
  4. import os
  5. import sys
  6. from pathlib import Path
  7. def _sync_windows_cli_launchers(root: Path) -> list[Path]:
  8. # Shim to stop the old updater doing work until relaunch. Copy no launchers.
  9. return []
  10. def _is_windows() -> bool:
  11. return sys.platform == "win32"
  12. #: Launcher command names install.ps1's Set-PathVariable exposes from the
  13. #: managed binary dir (the default Hermes root's ``bin``, next to uv.exe)
  14. #: on the user PATH. Keep in lockstep with WINDOWS_BIN_LAUNCHERS in
  15. #: hermes_cli/_launchers.py and scripts/install.ps1.
  16. _WINDOWS_BIN_LAUNCHERS = ("hermes", "hermes-acp")
  17. def _normalize_windows_path(value) -> str:
  18. """Windows path equality key: backslashes, no trailing separator, lowered.
  19. Lowercase via ``.lower()`` (what ``ntpath.normcase`` does) rather than
  20. ``os.path.normcase`` — that is an identity function on POSIX, and this
  21. comparison must behave Windows-correct even when tests exercise the
  22. Windows branch from another host (same rationale as
  23. ``venv_bin_dir(windows=...)``).
  24. """
  25. return str(value).replace("/", "\\").rstrip("\\").lower()
  26. def _windows_user_path_entries() -> list[str]:
  27. """User PATH entries from the registry — the value install.ps1 writes.
  28. Falls back to the process PATH when the registry is unreadable. Only
  29. called on Windows.
  30. """
  31. try:
  32. import winreg
  33. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") as key:
  34. raw, _kind = winreg.QueryValueEx(key, "Path")
  35. value = os.path.expandvars(str(raw))
  36. except (OSError, ImportError):
  37. value = os.environ.get("PATH", "")
  38. return [entry for entry in value.split(";") if entry.strip()]
  39. def ensure_windows_bin_launchers(
  40. root,
  41. *,
  42. windows: bool | None = None,
  43. user_path_entries: list[str] | None = None,
  44. ) -> list[str]:
  45. """Re-stage the Windows ``hermes`` launchers when they vanish or when
  46. they still boot through the venv.
  47. On Windows, ``hermes`` resolves through staged launchers — never
  48. ``venv\\Scripts`` itself on PATH, which would shadow the user's
  49. ``python`` (#83797) — and under pm the launchers boot the pm STORE
  50. python with ``PYTHONPATH=<repo>;<venv>/site-packages``, never the venv
  51. interpreter (no-boot-through-venv; ``pyvenv.cfg`` is inert dead
  52. config). The canonical launcher home is
  53. the managed binary dir — the default Hermes root's ``bin``
  54. (``%LOCALAPPDATA%\\hermes\\bin``, next to the managed uv) — which lives
  55. OUTSIDE the git checkout so no git operation can ever touch it. It is
  56. a per-machine dir shared by every profile: ``get_hermes_home()`` would
  57. point inside ``profiles\\<name>`` under ``hermes -p``, so the anchor
  58. here is :func:`hermes_constants.get_default_hermes_root`.
  59. Earlier installer versions staged them at ``<checkout>\\bin`` instead —
  60. inside the git working tree — where ``hermes update``'s pre-update
  61. autostash (``git stash push --include-untracked``) swept them off disk;
  62. once the desktop updater stopped re-applying stashes (``--keep-stash``)
  63. nothing restored them and ``hermes`` stopped resolving in every new
  64. terminal. That legacy location is re-staged too, during the transition,
  65. for installs whose user PATH still resolves through it.
  66. A name counts as present when an exe exists that does NOT boot the
  67. venv interpreter — legacy copied-venv trampolines (detected by their
  68. embedded interpreter path) and placeholder .cmd delegators are replaced
  69. with a store-python launcher as soon as one can be minted.
  70. Two targets, two gates, both failing toward inaction:
  71. - canonical managed binary dir: only when *root* is the managed clone
  72. (``root.parent == get_default_hermes_root()``), so source checkouts
  73. elsewhere never gain launchers;
  74. - legacy ``<root>\\bin``: only when that dir is on the user PATH
  75. (registry value, process PATH as fallback), i.e. the install opted
  76. into the old layout and still resolves through it.
  77. Writes go through a staging name + ``os.replace`` so concurrent process
  78. starts cannot tear a launcher. Never raises; returns the restored paths.
  79. *windows* and *user_path_entries* are injectable for tests, same pattern
  80. as ``hermes_constants.venv_bin_dir``.
  81. """
  82. if windows is None:
  83. windows = _is_windows()
  84. if not windows:
  85. return []
  86. root = Path(root)
  87. # Per-machine anchor: the DEFAULT Hermes root, not get_hermes_home() —
  88. # under ``hermes -p <name>`` that returns ``profiles\\<name>``, which
  89. # would fail the managed-clone gate below and silently skip the heal
  90. # for profile users. The launcher dir serves the whole machine.
  91. from hermes_constants import get_default_hermes_root
  92. try:
  93. home = Path(get_default_hermes_root())
  94. except Exception:
  95. return []
  96. def _launcher_present(target: Path, name: str) -> bool:
  97. return (target / f"{name}.exe").exists() or (target / f"{name}.cmd").exists()
  98. # Only the launch producer knows the executable/boot contract. Old venv
  99. # paths below identify obsolete artifacts; they never select dependencies.
  100. from hermes_cli._launchers import (
  101. ensure_install_launchers,
  102. exe_is_venv_bound,
  103. stage_launcher,
  104. )
  105. from hermes_constants import project_venv_dir
  106. venv_dir = project_venv_dir(root)
  107. def _needs_attention(target: Path, name: str) -> bool:
  108. """Missing, a placeholder .cmd, or a launcher that still boots the
  109. venv interpreter — anything the store-python launcher should replace."""
  110. exe = target / f"{name}.exe"
  111. if not exe.exists():
  112. return not ((target / f"{name}.cmd").is_file()
  113. and _launcher_present(root / ".hermes" / "bin", name))
  114. return exe_is_venv_bound(exe, venv_dir)
  115. targets: list[Path] = []
  116. restored: list[str] = []
  117. # Canonical target — gate on the managed-clone shape. This runs at
  118. # every hermes_cli.main process start (right after the profile
  119. # override), so the healthy path must stay at a couple of stat calls.
  120. if _normalize_windows_path(root.parent) == _normalize_windows_path(home):
  121. canonical = home / "bin"
  122. local = root / ".hermes" / "bin"
  123. if any(not _launcher_present(local, name) for name in _WINDOWS_BIN_LAUNCHERS):
  124. # Upgrade existing PM installs too: their healthy external launcher
  125. # predates the exact-install command and may lack the runtime query.
  126. try:
  127. canonical.mkdir(parents=True, exist_ok=True)
  128. restored.extend(ensure_install_launchers(root, canonical))
  129. except OSError:
  130. return []
  131. if not restored and any(
  132. _needs_attention(canonical, name) for name in _WINDOWS_BIN_LAUNCHERS
  133. ):
  134. targets.append(canonical)
  135. # Legacy transition target — the pre-migration in-checkout dir. Only
  136. # re-staged while the user PATH still points at it (consent), compared
  137. # as normalized literal strings: the installer wrote the long literal
  138. # path, and realpath'ing arbitrary PATH entries could hang on dead
  139. # network shares. An entry stored some other way (8.3 short path,
  140. # subst drive) misses the re-stage, which fails safe: no-op.
  141. legacy = root / "bin"
  142. if any(_needs_attention(legacy, name) for name in _WINDOWS_BIN_LAUNCHERS):
  143. if user_path_entries is None:
  144. user_path_entries = _windows_user_path_entries()
  145. configured = {_normalize_windows_path(entry) for entry in user_path_entries}
  146. if _normalize_windows_path(legacy) in configured:
  147. targets.append(legacy)
  148. if not targets:
  149. return restored
  150. for target in targets:
  151. try:
  152. target.mkdir(parents=True, exist_ok=True)
  153. except OSError:
  154. continue
  155. for name in _WINDOWS_BIN_LAUNCHERS:
  156. if not _needs_attention(target, name):
  157. # Already a store-python launcher (or a form this heal does
  158. # not understand but that does not boot the venv): leave it.
  159. continue
  160. final = stage_launcher(name, root, target)
  161. if final is not None:
  162. # Windows resolves .exe before .cmd. A surviving venv-bound
  163. # launcher would shadow the successfully staged fallback.
  164. obsolete = target / f"{name}.exe"
  165. if final.suffix == ".cmd" and exe_is_venv_bound(obsolete, venv_dir):
  166. obsolete.unlink()
  167. restored.append(str(final))
  168. if restored:
  169. # Guarded like everything else in this never-raises helper: a
  170. # closed/broken stderr must not turn a successful heal into a crash.
  171. with contextlib.suppress(OSError, ValueError):
  172. print(
  173. " ✓ Restored hermes launcher(s): " + ", ".join(restored),
  174. file=sys.stderr,
  175. )
  176. return restored
  177. def _read_user_path_raw() -> tuple[list[str], int]:
  178. """Raw (unexpanded) user PATH entries + registry value type.
  179. Raw so a rewrite preserves ``%VARS%`` exactly as the user stored them
  180. (same discipline as ``hermes_cli.uninstall``). Only called on Windows.
  181. """
  182. import winreg
  183. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") as key:
  184. try:
  185. raw, kind = winreg.QueryValueEx(key, "Path")
  186. except FileNotFoundError:
  187. return [], winreg.REG_EXPAND_SZ
  188. return [entry for entry in str(raw).split(";") if entry], int(kind)
  189. def _write_user_path_raw(entries: list[str], kind: int) -> None:
  190. """Write the user PATH back, preserving the registry value type."""
  191. import winreg
  192. with winreg.OpenKey(
  193. winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_READ | winreg.KEY_WRITE
  194. ) as key:
  195. winreg.SetValueEx(key, "Path", 0, kind, ";".join(entries))
  196. def migrate_windows_bin_path(
  197. root,
  198. *,
  199. windows: bool | None = None,
  200. read_user_path=None,
  201. write_user_path=None,
  202. ) -> bool:
  203. """One-time PATH migration to the ``HERMES_HOME\\bin`` launcher layout.
  204. Runs from the ``hermes update`` tail (and mirrors what install.ps1's
  205. Set-PathVariable does on fresh installs/repairs, which never reach
  206. existing installs — updates don't run install.ps1):
  207. 1. stage the launcher copies into the managed binary dir (via
  208. :func:`ensure_windows_bin_launchers`);
  209. 2. verify both launchers are present there — otherwise STOP, leaving
  210. the user PATH untouched (never strip a working entry before its
  211. replacement is proven);
  212. 3. ensure the managed binary dir is on the user PATH (prepend), only
  213. when new consoles resolve this home (``_launchers.owns_user_path``);
  214. 4. strip the legacy entries: ``<root>\\bin`` (in-checkout launcher dir
  215. the update autostash could sweep) and ``<root>\\venv\\Scripts``
  216. (shadowed the user's ``python``, #83797).
  217. The legacy ``<root>\\bin`` FILES are deliberately left in place: editor
  218. and ACP configs that captured absolute launcher paths keep working
  219. (the launchers run fine from there — only PATH resolution through a
  220. dir git could sweep was the bug), and the dir is git-ignored so it
  221. cannot dirty the tree.
  222. Registry writes preserve the stored value type and raw ``%VARS%``.
  223. Never raises; returns True when the canonical layout is in place.
  224. *read_user_path*/*write_user_path* are injectable for tests.
  225. """
  226. if windows is None:
  227. windows = _is_windows()
  228. if not windows:
  229. return False
  230. root = Path(root)
  231. # Same per-machine anchor as ensure_windows_bin_launchers (see there).
  232. from hermes_constants import get_default_hermes_root
  233. from pm.environments import venv_bin_dir
  234. try:
  235. home = Path(get_default_hermes_root())
  236. except Exception:
  237. return False
  238. if _normalize_windows_path(root.parent) != _normalize_windows_path(home):
  239. return False # not the managed clone — nothing to migrate
  240. ensure_windows_bin_launchers(root, windows=windows, user_path_entries=[])
  241. home_bin = home / "bin"
  242. if any(
  243. not ((home_bin / f"{name}.exe").is_file() or (home_bin / f"{name}.cmd").is_file())
  244. for name in _WINDOWS_BIN_LAUNCHERS
  245. ):
  246. return False # staging incomplete — leave the PATH alone
  247. try:
  248. from hermes_cli._launchers import owns_user_path
  249. if not owns_user_path(home):
  250. return False # new consoles resolve another home; leave the User PATH to it
  251. except (ImportError, OSError, ValueError): # an old updater's _launchers, or a failed Win32 call
  252. return False
  253. if read_user_path is None:
  254. read_user_path = _read_user_path_raw
  255. if write_user_path is None:
  256. write_user_path = _write_user_path_raw
  257. try:
  258. entries, kind = read_user_path()
  259. except (OSError, ImportError):
  260. return False
  261. legacy_keys = {
  262. _normalize_windows_path(root / "bin"),
  263. # The pre-#83797 installer put the venv's Scripts dir itself on PATH,
  264. # always at the literal `venv` layout (never `.venv`) — this strips
  265. # that stale entry, so it must match what the installer wrote then,
  266. # not where the venv lives now.
  267. _normalize_windows_path(venv_bin_dir(root / "venv", windows=True)),
  268. }
  269. home_bin_key = _normalize_windows_path(home_bin)
  270. def _entry_key(entry: str) -> str:
  271. return _normalize_windows_path(os.path.expandvars(entry))
  272. kept = [e for e in entries if _entry_key(e) not in legacy_keys]
  273. have_home_bin = any(_entry_key(e) == home_bin_key for e in kept)
  274. if not have_home_bin:
  275. kept = [str(home_bin)] + kept
  276. if kept != entries:
  277. try:
  278. write_user_path(kept, kind)
  279. except (OSError, ImportError):
  280. return False
  281. with contextlib.suppress(OSError, ValueError):
  282. print(
  283. f" ✓ hermes launchers now resolve from {home_bin} "
  284. "(legacy PATH entries removed)",
  285. file=sys.stderr,
  286. )
  287. return True