update_handoff.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """Frozen compat surface for releases that finish `hermes update` via the post-swap hand-off.
  2. Releases from 2026-09-16 (94ced1a2b2) lazily import ``hermes_cli.update_handoff``
  3. from the NEW tree after the checkout swap. Like every other retired updater
  4. hook, this module keeps that import working by routing into the historical
  5. takeover (``hermes_cli._old_updater`` → ``_update_takeover.py``) instead of
  6. re-executing ``hermes update --post-swap``; the pulled tree is never imported
  7. into the pre-pull interpreter.
  8. Guarded by tests/compat/old_updater_surface.json — do not remove a public name
  9. without regenerating the frozen surface and proving no shipped release loads it.
  10. """
  11. from __future__ import annotations
  12. import json
  13. import os
  14. import subprocess
  15. import sys
  16. import time
  17. from pathlib import Path
  18. from typing import Any
  19. # Set on the post-swap child: the receipt header says "continued", the lock is the parent's.
  20. POST_SWAP_ENV = "HERMES_UPDATE_POST_SWAP"
  21. def is_post_swap_child() -> bool:
  22. return os.environ.get(POST_SWAP_ENV) == "1"
  23. def write_handoff(payload: dict[str, Any]) -> Path:
  24. """Persist the post-swap payload beside the receipts (the ROOT home); returns its path."""
  25. from hermes_constants import get_default_hermes_root
  26. directory = get_default_hermes_root() / "logs" / "update_receipts"
  27. directory.mkdir(parents=True, exist_ok=True)
  28. path = directory / f"post_swap_{os.getpid()}.json"
  29. path.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8")
  30. return path
  31. def read_handoff(path: str | Path) -> dict[str, Any]:
  32. payload = json.loads(Path(path).read_text(encoding="utf-8-sig"))
  33. if not isinstance(payload, dict):
  34. raise ValueError(f"post-swap hand-off {path} is not a JSON object")
  35. return payload
  36. def post_swap_python() -> Path:
  37. """Interpreter for the child: the project venv's python when this process runs from (or
  38. under) the project's Windows console shim — the shim can never be re-executed on Windows
  39. because it holds itself open for the whole process lifetime (#88838, #89599) — else the
  40. running interpreter."""
  41. if sys.platform != "win32":
  42. return Path(sys.executable)
  43. from hermes_cli._launchers import _is_windows
  44. from hermes_constants import project_venv_dir
  45. from pm.environments import venv_python
  46. venv_dir = project_venv_dir(Path(__file__).resolve().parents[1])
  47. if venv_dir is not None and _is_windows():
  48. candidate = venv_python(venv_dir, windows=True)
  49. if candidate.is_file():
  50. return candidate
  51. return Path(sys.executable)
  52. def post_swap_command(handoff_path: Path, argv_tail: list[str]) -> list[str]:
  53. """``python -m hermes_cli.main update <original flags> --post-swap <file>``.
  54. Historical command shape; kept so a printed manual-continuation line reads
  55. exactly as older releases expect. The takeover child this tree actually
  56. spawns (see :func:`continue_update_in_fresh_interpreter`) ignores the flag.
  57. """
  58. return [str(post_swap_python()), "-m", "hermes_cli.main", "update", *argv_tail,
  59. "--post-swap", str(handoff_path)]
  60. def post_swap_child_env() -> dict[str, str]:
  61. """Environment for the child. ``HERMES_UPDATE_REEXEC`` marks it as already off the Windows
  62. shim (no second re-exec at the sync boundary). The lock hand-off pid is only claimed when
  63. nobody upstream (Tauri/Electron updater) already named theirs."""
  64. from hermes_cli.update_lock import HANDOFF_PID_ENV
  65. env = {**os.environ, POST_SWAP_ENV: "1", "HERMES_UPDATE_REEXEC": "1"}
  66. env.setdefault(HANDOFF_PID_ENV, str(os.getpid()))
  67. return env
  68. def _takeover_request(payload: dict[str, Any], argv_tail: list[str] | None) -> dict[str, Any]:
  69. """Map a historical post-swap payload onto the takeover request schema.
  70. Payloads written before the takeover seam (e.g. release 0.21.3) name the
  71. desktop flag and the Windows resume token differently and carry no
  72. assume_yes at all; `update_finish.py` reads the new names with bare
  73. subscriptions, so an unmapped payload KeyErrors mid-completion with the
  74. checkout already swapped. New-schema payloads pass through unchanged.
  75. """
  76. request = dict(payload)
  77. request.setdefault("desktop", bool(payload.get("had_desktop_app_before_update", False)))
  78. request.setdefault("windows_resume", payload.get("windows_gateway_resume"))
  79. request.setdefault("assume_yes", "--yes" in (argv_tail or []))
  80. request.setdefault("restart_update", False)
  81. return request
  82. def _continue_legacy_post_swap(handoff_path: str | Path, *, argv_tail: list[str]) -> int:
  83. """Complete the command shape shipped before PM owned source updates.
  84. Those releases start the replacement checkout as ``hermes update <flags>
  85. --post-swap FILE``. The replacement bootstrap calls this before importing
  86. its PM or CLI graph, then the existing takeover child prepares and finishes
  87. the update entirely on replacement code.
  88. """
  89. payload = read_handoff(handoff_path)
  90. try:
  91. Path(handoff_path).unlink()
  92. except OSError:
  93. pass
  94. from hermes_cli._old_updater import _run_child
  95. code, _completed = _run_child(_takeover_request(payload, argv_tail))
  96. return int(code)
  97. def continue_update_in_fresh_interpreter(payload: dict[str, Any], *, argv_tail: list[str] | None = None) -> int | None:
  98. """Run the post-swap tail in a child interpreter on the pulled code.
  99. The old caller's payload carries the same fields the completion request
  100. needs (receipt, plan, windows_resume, gateway_mode, ...); ``argv_tail`` is
  101. accepted and ignored because the takeover tail does not re-parse update
  102. flags. Returns the child's exit code, or ``None`` when no child could be
  103. started (the caller then owns the failure bookkeeping). Ctrl-C semantics
  104. mirror the historical hand-off: wait for the child's cleanup instead of
  105. subprocess.run's kill-on-interrupt.
  106. """
  107. from hermes_cli._old_updater import _run_child
  108. handoff_path = write_handoff(payload)
  109. request = _takeover_request(payload, argv_tail)
  110. cmd = post_swap_command(handoff_path, argv_tail or [])
  111. print(f"→ Post-swap hand-off: completing the update in a fresh interpreter ({handoff_path})")
  112. sys.stdout.flush()
  113. sys.stderr.flush()
  114. try:
  115. code, _completed = _run_child(request)
  116. return int(code)
  117. except OSError as exc:
  118. print(f" ⚠ Could not start the post-update interpreter: {exc}")
  119. print(" The code update is applied. Finish it with:")
  120. print(f" {subprocess.list2cmdline(cmd)}")
  121. return None