version_info.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. """Canonical runtime identity for Hermes.
  2. Resolution order:
  3. 1. Install stamp (``install-stamp.json``) — written at build time by
  4. ``scripts/write_install_stamp.py`` for every packager (Docker, Nix, and
  5. the desktop app). The stamp is authoritative
  6. for packaged builds.
  7. 2. Live git — for unstamped source/dev installs with a ``.git`` directory.
  8. 3. Unknown — no stamp and no git. The provenance is unknown.
  9. """
  10. from __future__ import annotations
  11. import json
  12. import subprocess
  13. import tomllib
  14. from dataclasses import dataclass
  15. from pathlib import Path
  16. from typing import Literal, cast
  17. from hermes_cli.steward import UPDATE_MECHANISMS
  18. from hermes_cli.update_channel import STABLE_TAG_RE
  19. @dataclass(frozen=True)
  20. class VersionInfo:
  21. base_version: str
  22. derived_version: str
  23. distance: int | None
  24. commit: str | None
  25. branch: str | None
  26. source: Literal["build", "commit-build", "ci", "docker", "fallback", "git", "local", "nix", "unknown"]
  27. dirty: bool = False
  28. commit_date: int | None = None
  29. distribution: Literal["docker", "nix", "desktop-app"] | None = None
  30. @property
  31. def display_version(self) -> str:
  32. """``<base>+<distance>`` when a release is known, else the derived identity.
  33. Keep a tagless checkout's ``git.<sha>`` rather than reducing it to unknown.
  34. """
  35. if self.base_version == "unknown":
  36. return self.derived_version
  37. return _derived_version(self.base_version, self.distance)
  38. def _derived_version(
  39. base_version: str,
  40. distance: int | None,
  41. dirty: bool = False,
  42. short_commit: str | None = None,
  43. ) -> str:
  44. if distance and distance > 0:
  45. suffix = f"{distance}.g{short_commit}" if short_commit else str(distance)
  46. return f"{base_version}+{suffix}{'.dirty' if dirty and short_commit else ''}"
  47. if dirty and distance is None:
  48. return f"{base_version}+?"
  49. return base_version
  50. def _run_git(repo_dir: Path, *args: str) -> str | None:
  51. try:
  52. result = subprocess.run(
  53. ["git", *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=3, cwd=str(repo_dir),
  54. check=False,
  55. )
  56. except (OSError, subprocess.SubprocessError):
  57. return None
  58. value = (result.stdout or "").strip()
  59. return value if result.returncode == 0 and value else None
  60. def _resolve_repo_dir() -> Path | None:
  61. """Use the executing checkout before a profile's optional clone."""
  62. repo_dir = Path(__file__).parent.parent.resolve()
  63. if (repo_dir / ".git").exists():
  64. return repo_dir
  65. # The PROCESS home: this is the running code's identity and is cached
  66. # process-wide, so a profile's context-local override must not pick it.
  67. from hermes_constants import get_process_hermes_home
  68. candidate = get_process_hermes_home() / "hermes-agent"
  69. if (candidate / ".git").exists():
  70. return candidate
  71. return None
  72. def _parse_nonnegative(value: str | None) -> int | None:
  73. try:
  74. parsed = int(value or "")
  75. except ValueError:
  76. return None
  77. return parsed if parsed >= 0 else None
  78. def _calver_release_version(repo_dir: Path) -> tuple[str, int] | None:
  79. """The version the nearest CalVer release shipped, and the commits since it.
  80. Releases before semver tags existed are tagged ``vYYYY.M.D`` only; the
  81. version users actually run is in that tag's pyproject. Without this, a
  82. checkout past such a release would compare as "unknown" against plugins'
  83. ``requires_hermes``.
  84. """
  85. described = _run_git(repo_dir, "describe", "--tags", "--long", "--match", "v2[0-9][0-9][0-9].*", "HEAD")
  86. if not described:
  87. return None
  88. tag, count, _ = described.rsplit("-", 2)
  89. distance = _parse_nonnegative(count)
  90. try:
  91. project = tomllib.loads(_run_git(repo_dir, "show", f"{tag}:pyproject.toml") or "").get("project", {})
  92. except tomllib.TOMLDecodeError:
  93. return None
  94. version = project.get("version")
  95. if distance is None or not isinstance(version, str) or not STABLE_TAG_RE.fullmatch(f"v{version}"):
  96. return None
  97. return version, distance
  98. # --- Install stamp reader ---------------------------------------------------
  99. def _resolve_stamp_file() -> Path | None:
  100. """The executing tree's stamp (pm.paths.install_stamp_path owns the location)."""
  101. from pm.paths import install_stamp_path, repo_root
  102. p = install_stamp_path(repo_root())
  103. return p if p.is_file() else None
  104. def _stamp_version_info() -> VersionInfo | None:
  105. """Read provenance from a build-time install stamp."""
  106. stamp_file = _resolve_stamp_file()
  107. if stamp_file is None:
  108. return None
  109. try:
  110. raw = stamp_file.read_text(encoding="utf-8-sig")
  111. data = json.loads(raw)
  112. except (OSError, json.JSONDecodeError):
  113. return None
  114. if not isinstance(data, dict) or "commit" not in data:
  115. return None
  116. # updateMechanism is required in every stamp. A stamp without it means
  117. # the writing build lane must be fixed, not tolerated.
  118. if data.get("updateMechanism") not in UPDATE_MECHANISMS:
  119. raise RuntimeError(
  120. f"install-stamp.json at {stamp_file} is missing a valid "
  121. f"'updateMechanism' (one of {', '.join(UPDATE_MECHANISMS)}). The "
  122. "build lane that wrote this stamp must pass --update-mechanism to "
  123. "scripts/write_install_stamp.py (or bake the field directly)."
  124. )
  125. # A light artifact ships no Python runtime. Reading a light stamp from
  126. # a Python process means the artifact was mispackaged.
  127. if data.get("payload") == "light":
  128. raise RuntimeError(
  129. f"install-stamp.json at {stamp_file} marks this artifact as 'light' "
  130. "(no agent runtime). No Python process can legitimately run from a "
  131. "light artifact — this build is mispackaged."
  132. )
  133. commit = data.get("commit") or None
  134. if not commit or set(commit) == {"0"}:
  135. # All-zero placeholder = fallback stamp, not real provenance.
  136. return None
  137. stamp_source = str(data.get("source") or "")
  138. if stamp_source == "git" and (stamp_file.parent / ".git").exists():
  139. live_commit = _run_git(stamp_file.parent, "rev-parse", "HEAD")
  140. if live_commit and live_commit != commit:
  141. return None
  142. base_version = data.get("baseVersion") or "unknown"
  143. display_version = data.get("displayVersion") or base_version
  144. distance = data.get("distance")
  145. if isinstance(distance, str):
  146. distance = _parse_nonnegative(distance)
  147. # ``source`` describes build provenance, while ``distribution`` identifies
  148. # the package form users installed. Keep both facts intact for support.
  149. source = (
  150. cast(Literal["build", "commit-build", "ci", "docker", "fallback", "git", "local", "nix", "unknown"], stamp_source)
  151. if stamp_source in {"commit-build", "ci", "docker", "fallback", "git", "local", "nix"}
  152. else "build"
  153. )
  154. distribution = data.get("distribution")
  155. if distribution not in {"docker", "nix", "desktop-app"}:
  156. distribution = None
  157. commit_date = data.get("commitDate")
  158. if not isinstance(commit_date, int):
  159. commit_date = None
  160. return VersionInfo(
  161. base_version,
  162. display_version,
  163. distance if isinstance(distance, int) else None,
  164. commit,
  165. data.get("branch") or None,
  166. source,
  167. bool(data.get("dirty")),
  168. commit_date,
  169. distribution,
  170. )
  171. # --- Git provenance (source/dev installs) -----------------------------------
  172. def _git_version_info(repo_dir: Path, *, include_untracked: bool = False) -> VersionInfo:
  173. commit = _run_git(repo_dir, "rev-parse", "HEAD")
  174. # A detached HEAD has no branch. Leave the field None: every formatter
  175. # already prints the commit separately and handles a missing branch.
  176. branch = _run_git(repo_dir, "branch", "--show-current")
  177. commit_date_raw = _run_git(repo_dir, "log", "-1", "--format=%ct", "HEAD")
  178. commit_date: int | None = None
  179. if commit_date_raw and commit_date_raw.isdigit():
  180. commit_date = int(commit_date_raw)
  181. try:
  182. # -uno: skip the untracked-file scan. This runs on the startup-banner
  183. # path, and a full working-tree walk costs real time on large or cold
  184. # checkouts. Same semantics as write_install_stamp.py.
  185. # The 3 s timeout kills a slow status (a partial clone lazily fetching a tree, a cold or
  186. # scanned disk), and a status killed while refreshing the index strands .git/index.lock:
  187. # the update's own merge then dies on "File exists" (#132089). A read-only probe takes
  188. # no optional lock.
  189. status_command = ["git", "--no-optional-locks", "status", "--porcelain"]
  190. if not include_untracked:
  191. status_command.append("-uno")
  192. dirty_result = subprocess.run(
  193. status_command,
  194. capture_output=True,
  195. text=True, encoding="utf-8", errors="replace",
  196. timeout=3,
  197. cwd=str(repo_dir),
  198. check=False,
  199. )
  200. dirty = dirty_result.returncode == 0 and bool((dirty_result.stdout or "").strip())
  201. except (OSError, subprocess.SubprocessError):
  202. dirty = False
  203. tags = _run_git(repo_dir, "tag", "--merged", "HEAD", "--list", "v[0-9]*")
  204. releases = [
  205. tag[1:]
  206. for tag in (tags or "").splitlines()
  207. if STABLE_TAG_RE.fullmatch(tag)
  208. ]
  209. base_version = (
  210. max(releases, key=lambda value: tuple(int(part) for part in value.split(".")))
  211. if releases else "unknown"
  212. )
  213. distance = _parse_nonnegative(
  214. _run_git(repo_dir, "rev-list", "--count", f"v{base_version}..HEAD")
  215. ) if releases else None
  216. if not releases:
  217. base_version, distance = _calver_release_version(repo_dir) or ("unknown", None)
  218. short_commit = _run_git(repo_dir, "rev-parse", "--short=7", "HEAD")
  219. if base_version == "unknown" and short_commit:
  220. display_version = f"git.{short_commit}{'.dirty' if dirty else ''}"
  221. else:
  222. display_version = _derived_version(base_version, distance, dirty, short_commit)
  223. return VersionInfo(
  224. base_version, display_version, distance, commit, branch, "git", dirty, commit_date
  225. )
  226. # --- Cache + public API -----------------------------------------------------
  227. _cached_version_info: VersionInfo | None = None
  228. def _reset_version_info_cache() -> None:
  229. """Test-only cache reset."""
  230. global _cached_version_info
  231. _cached_version_info = None
  232. def _stamp_or_none() -> VersionInfo | None:
  233. """The install stamp's provenance, or None without a valid stamp.
  234. A malformed stamp (missing/illegal updateMechanism, mispackaged "light"
  235. payload) raises RuntimeError — the build lane that wrote it must be
  236. fixed, but a crashing CLI is the wrong failure mode for every uncached
  237. caller. Degrade to live git / "unknown" and let the authoring lane's own
  238. tests surface the malformed stamp.
  239. """
  240. try:
  241. return _stamp_version_info()
  242. except RuntimeError:
  243. return None
  244. def get_version_info() -> VersionInfo:
  245. """Return cached provenance from install stamp, git, or unknown."""
  246. global _cached_version_info
  247. if _cached_version_info is not None:
  248. return _cached_version_info
  249. # 1. Install stamp (packaged builds: Docker, Nix)
  250. info = _stamp_or_none()
  251. # 2. Live git (source/dev installs)
  252. if info is None:
  253. repo_dir = _resolve_repo_dir()
  254. if repo_dir is not None:
  255. info = _git_version_info(repo_dir)
  256. # 3. Unknown — no stamp, no git
  257. if info is None:
  258. info = VersionInfo("unknown", "unknown", None, None, None, "unknown")
  259. _cached_version_info = info
  260. return info
  261. def hermes_user_agent(product: str = "hermes-cli") -> str:
  262. """``<product>/<base version>`` for an outbound request.
  263. Call it where the request is built, never at module level: a source checkout resolves the
  264. release from git, so a module-level read made every Hermes start pay that walk whether or not
  265. it ever sent the request.
  266. """
  267. return f"{product}/{get_version_info().base_version}"
  268. def get_code_identity(refresh: bool = False) -> dict:
  269. """Return the running install's code identity as a flat dict.
  270. Shape: ``{"sha": full sha | None, "short_sha": str | None, "version":
  271. base package version | None, "source": str, "commit_date": epoch s | None}`` — what the update
  272. receipt, runtime inventory, and gateway status stamping consume.
  273. Backed by :func:`get_version_info` (install stamp first, live git
  274. second, unknown third), so every consumer shares one resolution
  275. policy. Returned dicts are fresh copies, never the shared cache.
  276. ``refresh=True`` drops the per-process cache first — the updater uses
  277. it to re-read identity after swapping the checkout out from under the
  278. running process.
  279. """
  280. global _cached_version_info
  281. if refresh:
  282. _cached_version_info = None
  283. info = get_version_info()
  284. return {
  285. "sha": info.commit,
  286. "short_sha": info.commit[:8] if info.commit else None,
  287. "version": info.base_version,
  288. "source": info.source,
  289. "commit_date": info.commit_date,
  290. }
  291. def read_checkout_sha() -> str | None:
  292. """The running install's commit, re-read now: the stamp's, else ``git rev-parse HEAD``.
  293. Same answer as ``get_code_identity(refresh=True)["sha"]`` for one git call instead of the
  294. whole provenance walk (the tag scan alone costs ~0.35 s in a large clone), which the
  295. pending-restart check on every CLI start was paying just to compare SHAs. Drops the cached
  296. identity like that refresh does: the checkout may have moved under this process.
  297. """
  298. _reset_version_info_cache()
  299. stamp = _stamp_or_none()
  300. if stamp is not None:
  301. return stamp.commit
  302. repo_dir = _resolve_repo_dir()
  303. return _run_git(repo_dir, "rev-parse", "HEAD") if repo_dir is not None else None