source_check.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. """Passive source update decisions for one exact installation and profile.
  2. No fetch, lock repair, or Git writes. Desktop, CLI, and dashboard share this owner.
  3. """
  4. from __future__ import annotations
  5. import json
  6. import logging
  7. import os
  8. import shutil
  9. import subprocess
  10. import time
  11. from dataclasses import dataclass
  12. from pathlib import Path
  13. from typing import Optional
  14. from urllib.parse import quote
  15. import urllib.error
  16. import urllib.request
  17. from hermes_constants import get_hermes_home
  18. from hermes_cli.source_releases import OFFICIAL_REPOSITORY, _GITHUB_ORIGIN, resolve_source_target
  19. logger = logging.getLogger(__name__)
  20. UPDATE_AVAILABLE_NO_COUNT = -1
  21. _UPDATE_CHECK_CACHE_SECONDS = 24 * 3600
  22. _UPDATE_CHECK_FAILURE_CACHE_SECONDS = 3600
  23. _RUNTIME_LOOKUP_SECONDS = 8.0
  24. def _quiet(fn, default=None):
  25. try:
  26. return fn()
  27. except Exception:
  28. return default
  29. def source_git_env() -> dict[str, str]:
  30. """Keep read-only Git probes in their explicit cwd, not an inherited worktree.
  31. No probe may lazy-fetch from a partial clone's promisor remote: asking about
  32. an upstream tip the clone never fetched would download its history, and the
  33. probe timeout kills only git itself, orphaning the fetch (see NO_LAZY_FETCH_ENV).
  34. """
  35. from hermes_cli._subprocess_compat import NO_LAZY_FETCH_ENV, noninteractive_git_env
  36. env = noninteractive_git_env()
  37. # Pathspec-mode overrides change how every probe's path arguments match
  38. # (GIT_LITERAL_PATHSPECS turns a ":(literal)" magic prefix into filename text).
  39. for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE",
  40. "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_SHALLOW_FILE", "GIT_NAMESPACE",
  41. "GIT_LITERAL_PATHSPECS", "GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"):
  42. env.pop(key, None)
  43. env["GIT_OPTIONAL_LOCKS"] = "0"
  44. env.update(NO_LAZY_FETCH_ENV)
  45. return env
  46. _GIT_TEXT_KW = {"text": True, "encoding": "utf-8", "errors": "replace"}
  47. def _git_run(args: list[str], *, cwd: Optional[Path] = None, timeout: int = 5, text: bool = True,
  48. git: str = "git"):
  49. """Read Git state without prompts, optional index writes, or inherited targeting."""
  50. from hermes_cli._subprocess_compat import windows_hide_flags
  51. kwargs: dict = {"creationflags": windows_hide_flags(), "env": source_git_env(), "stdin": subprocess.DEVNULL}
  52. try:
  53. return subprocess.run(
  54. [git, *args], capture_output=True, timeout=timeout, cwd=str(cwd) if cwd is not None else None,
  55. **(_GIT_TEXT_KW if text else {}), **kwargs, check=False)
  56. except Exception:
  57. return None
  58. def _git_stdout(args: list[str], *, cwd: Path, timeout: int = 5, git: str = "git") -> Optional[str]:
  59. result = _git_run(args, cwd=cwd, timeout=timeout, git=git)
  60. if result is None or result.returncode != 0:
  61. return None
  62. return (result.stdout or "").strip()
  63. def _git_ok(args: list[str], **kw) -> bool:
  64. """True when ``git <args>`` ran and exited 0 (output discarded)."""
  65. result = _git_run(args, text=False, **kw)
  66. return result is not None and result.returncode == 0
  67. def _git_count(args: list[str], *, cwd: Path) -> Optional[int]:
  68. """``int`` of a successful ``git rev-list --count``-style command, else None."""
  69. result = _git_run(args, cwd=cwd)
  70. if result is not None and result.returncode == 0:
  71. return _quiet(lambda: int(result.stdout.strip()))
  72. return None
  73. def _is_full_sha(value: Optional[str]) -> bool:
  74. return isinstance(value, str) and len(value) == 40 and all(c in "0123456789abcdefABCDEF" for c in value)
  75. def _github_compare(current_rev: str, target_rev: str, repository: str = OFFICIAL_REPOSITORY) -> Optional[dict]:
  76. # Do not memoize this separately: force must bypass failed AND successful network results.
  77. if not (_is_full_sha(current_rev) and _is_full_sha(target_rev)):
  78. return None
  79. payload = _quiet(lambda: json.loads(_request(
  80. f"https://api.github.com/repos/{repository}/compare/{current_rev}...{target_rev}")))
  81. return payload if isinstance(payload, dict) else None
  82. def _github_compare_behind(current_rev: str, target_rev: str, repository: str = OFFICIAL_REPOSITORY) -> Optional[int]:
  83. payload = _github_compare(current_rev, target_rev, repository)
  84. ahead = payload.get("ahead_by") if payload else None
  85. return ahead if isinstance(ahead, int) and not isinstance(ahead, bool) and ahead >= 0 else None
  86. def _request(url: str, accept: str = "application/vnd.github+json") -> str:
  87. """GET an api.github.com resource with the credential ladder in hermes_cli.github_api.
  88. A token GitHub rejects drops this request to anonymous rather than failing the
  89. check on a stale credential: 401, or a 403 that is not a spent rate limit (a
  90. suspended or restricted account's token, still printed by ``gh auth token``, #134335).
  91. """
  92. from hermes_cli.github_api import github_token
  93. token = github_token()
  94. try:
  95. return _request_with(url, accept, token)
  96. except urllib.error.HTTPError as exc:
  97. spent = exc.headers is not None and exc.headers.get("x-ratelimit-remaining") == "0"
  98. if token is None or exc.code not in (401, 403) or spent:
  99. exc.hermes_authenticated = token is not None # which quota a 403/429 spent
  100. raise
  101. logger.debug("GitHub rejected the configured token; retrying anonymously")
  102. try:
  103. return _request_with(url, accept, None)
  104. except urllib.error.HTTPError as exc:
  105. exc.hermes_authenticated = False
  106. raise
  107. def _request_with(url: str, accept: str, token: str | None) -> str:
  108. headers = {"Accept": accept, "User-Agent": "hermes-update-check"}
  109. if token:
  110. headers["Authorization"] = f"Bearer {token}"
  111. req = urllib.request.Request(url, headers=headers)
  112. with urllib.request.urlopen(req, timeout=10) as response:
  113. return response.read(2 * 1024 * 1024).decode("utf-8-sig").strip()
  114. def _branch_tip(repository: str | None, branch: str, root: Path, git: str,
  115. remote: str = "origin") -> tuple[str | None, bool, str | None]:
  116. """``(sha, missing, failure)``: ``missing`` only on a confirmed empty advertisement;
  117. ``failure`` names why no tip could be read, for the user-facing message."""
  118. # A successful empty ref advertisement alone proves a branch was deleted.
  119. # GitHub 404 can also mean a private repository: it must not heal a branch.
  120. failure = None
  121. if repository:
  122. from hermes_cli.github_api import describe_github_failure, github_token
  123. try:
  124. sha = _request(f"https://api.github.com/repos/{repository}/commits/{quote(branch, safe='')}",
  125. "application/vnd.github.sha")
  126. except Exception as exc:
  127. sha = None
  128. failure = describe_github_failure(exc, authenticated=github_token() is not None)
  129. if _is_full_sha(sha):
  130. return sha, False, None
  131. if failure is None:
  132. failure = "api.github.com returned no commit for the branch."
  133. if branch == "main" and remote == "origin":
  134. return None, False, failure
  135. result = _git_run(["ls-remote", "--exit-code", "--heads", remote, f"refs/heads/{branch}"],
  136. cwd=root, git=git, timeout=10)
  137. if result is None:
  138. return None, False, failure or f"`git ls-remote {remote}` could not run."
  139. sha = result.stdout.split()[0] if result.returncode == 0 and result.stdout else None
  140. if _is_full_sha(sha):
  141. return sha, False, None
  142. if result.returncode == 2:
  143. return None, True, None
  144. detail = (result.stderr or "").strip().splitlines()
  145. return None, False, failure or (f"`git ls-remote {remote}` failed: {detail[-1]}" if detail
  146. else f"`git ls-remote {remote}` returned no tip.")
  147. def _commits(payload: dict | None) -> list[dict]:
  148. from datetime import datetime
  149. rows = []
  150. entries = (payload or {}).get("commits", [])
  151. for entry in entries if isinstance(entries, list) else []:
  152. if not isinstance(entry, dict) or not isinstance(entry.get("sha"), str):
  153. continue
  154. commit = entry.get("commit") or {}
  155. when = (commit.get("committer") or {}).get("date") or ""
  156. at = _quiet(lambda: int(datetime.fromisoformat(when).timestamp() * 1000), 0)
  157. rows.append({"sha": entry["sha"], "summary": str(commit.get("message", "")).split("\n", 1)[0],
  158. "author": str((commit.get("author") or {}).get("name", "")), "at": at})
  159. return rows[::-1]
  160. @dataclass(frozen=True)
  161. class _Checkout:
  162. """Read-only facts about the checkout under test, gathered once per check."""
  163. root: Path
  164. git: str
  165. embedded: Optional[str]
  166. head: Optional[str]
  167. current_branch: Optional[str]
  168. origin: str
  169. repository: Optional[str]
  170. dirty: bool
  171. def _read_json(path: Path):
  172. return _quiet(lambda: json.loads(path.read_text(encoding="utf-8-sig")))
  173. def _unsupported_reason(stamp: dict, root: Path, *, explicit_root: bool, embedded: Optional[str]) -> Optional[dict]:
  174. """Fields explaining why this install cannot self-update from Git, or None when it can."""
  175. from hermes_cli.config import detect_install_method
  176. from hermes_cli.update_contract import COMMIT_BUILD_UPDATE_MESSAGE
  177. if stamp.get("source") == "commit-build":
  178. return {"reason": "commit-build", "message": COMMIT_BUILD_UPDATE_MESSAGE}
  179. if stamp.get("payload") in {"bundled", "light", "runtime"} or (
  180. not explicit_root and detect_install_method(root) in {"docker", "apt"}):
  181. return {"reason": "not-a-git-checkout"}
  182. if not embedded and not (root / ".git").exists():
  183. return {"reason": "not-a-git-checkout", "message": "This install has no git checkout to update."}
  184. if stamp.get("updateMechanism") not in (None, "self") and not embedded:
  185. return {"reason": "update-root-steward-owned-git-tree",
  186. "message": "This installation is managed by its install method; use its updater.", "advice": "git pull"}
  187. return None
  188. def _installed_git(git: str) -> str:
  189. """``git`` as given, unless it is a bare ``git`` PATH lacks: then the git ``hermes update`` runs.
  190. A Windows source install's only git is often the copy install.ps1 staged in PM's store, which
  191. is on PATH only inside ``hermes update`` (``expose_pm_git``). Desktop and the dashboard pass a
  192. bare ``git`` there, it dies with WinError 2, and the check reports ``head-unavailable``, which
  193. Desktop shows as "couldn't reach the update server" while ``hermes update`` works.
  194. """
  195. if git != "git" or shutil.which(git):
  196. return git
  197. from hermes_cli.update_pause_record import _git_executable
  198. return _git_executable()
  199. def _read_checkout(root: Path, git: str, embedded: Optional[str]) -> _Checkout:
  200. # An embedded revision has no checkout to ask: it always tracks the official repository.
  201. head = embedded or _git_stdout(["rev-parse", "HEAD"], cwd=root, git=git)
  202. current_branch = None if embedded else _git_stdout(["rev-parse", "--abbrev-ref", "HEAD"], cwd=root, git=git)
  203. origin = "" if embedded else (_git_stdout(["remote", "get-url", "origin"], cwd=root, git=git) or "")
  204. match = _GITHUB_ORIGIN.fullmatch(origin)
  205. repository = OFFICIAL_REPOSITORY if embedded else (match[1] if match else None)
  206. dirty = False if embedded else bool(_git_stdout(["status", "--porcelain"], cwd=root, git=git))
  207. return _Checkout(root, git, embedded, head, current_branch, origin, repository, dirty)
  208. def _configured_branch(desktop_config) -> Optional[str]:
  209. value = desktop_config.get("branch") if isinstance(desktop_config, dict) else None
  210. return (value.strip() or None) if isinstance(value, str) else None
  211. def _checked_out_branch(current_branch: Optional[str], fallback: Optional[str]) -> Optional[str]:
  212. """The checkout's branch, or ``fallback`` when detached or unreadable."""
  213. return current_branch if current_branch and current_branch != "HEAD" else fallback
  214. def _cached_status(cache_file: Path, identity: dict, now: float) -> Optional[dict]:
  215. """A still-fresh supported status cached for exactly this identity, else None.
  216. Failures expire sooner so a transient network error does not hide updates for a day.
  217. """
  218. cached = _read_json(cache_file)
  219. if not (isinstance(cached, dict) and cached.get("identity") == identity
  220. and isinstance(cached.get("status"), dict) and cached["status"].get("supported") is True):
  221. return None
  222. status = cached.get("status", {})
  223. ttl = _UPDATE_CHECK_FAILURE_CACHE_SECONDS if status.get("error") else _UPDATE_CHECK_CACHE_SECONDS
  224. ts = cached.get("ts")
  225. return status if isinstance(ts, (float, int)) and 0 <= now - ts < ttl else None
  226. def _write_cache(cache_file: Path, identity: dict, now: float, result: dict) -> None:
  227. try:
  228. from utils import atomic_json_write
  229. cache_file.parent.mkdir(parents=True, exist_ok=True)
  230. atomic_json_write(cache_file, {"identity": identity, "ts": now, "status": result})
  231. except OSError as exc:
  232. logger.debug("Could not cache source check: %s", exc)
  233. def _read_runtime_verdict(repository: str, sha: str) -> Optional[bool]:
  234. """Read the tree and at most four schema blobs at once, within one lookup deadline."""
  235. from contextvars import copy_context
  236. from fnmatch import fnmatchcase
  237. from itertools import islice
  238. from queue import Empty, Queue
  239. from threading import Thread
  240. from hermes_cli.update_downgrade_guard import STATE_MODULES, defines_runtime
  241. deadline = time.monotonic() + _RUNTIME_LOOKUP_SECONDS
  242. replies: Queue[Optional[str]] = Queue()
  243. def launch(url: str, *, api: bool = False) -> None:
  244. def read() -> None:
  245. replies.put(_quiet(lambda: _request(url) if api else _request_with(url, "*/*", None)))
  246. # A socket timeout alone does not bound a response that keeps trickling bytes. Daemon
  247. # workers let --version return at the deadline without waiting for stalled downloads.
  248. Thread(target=copy_context().run, args=(read,), daemon=True).start()
  249. def receive() -> Optional[str]:
  250. remaining = deadline - time.monotonic()
  251. if remaining <= 0:
  252. raise Empty
  253. return replies.get(timeout=remaining)
  254. launch(f"https://api.github.com/repos/{repository}/git/trees/{sha}", api=True)
  255. try:
  256. tree = _quiet(lambda: json.loads(receive() or ""))
  257. entries = tree.get("tree") if isinstance(tree, dict) and not tree.get("truncated") else None
  258. if not isinstance(entries, list):
  259. return None
  260. paths = [e["path"] for e in entries if isinstance(e, dict) and e.get("type") == "blob"
  261. and isinstance(e.get("path"), str) and fnmatchcase(e["path"], STATE_MODULES)]
  262. if not paths:
  263. return None # not a recognised Hermes tree: no claim either way
  264. urls = iter(f"https://raw.githubusercontent.com/{repository}/{sha}/{quote(path)}" for path in paths)
  265. pending = 0
  266. for url in islice(urls, 4):
  267. launch(url)
  268. pending += 1
  269. while pending:
  270. text = receive()
  271. if text is None:
  272. return None # an unread module may hold the marker
  273. if defines_runtime([text]):
  274. return False
  275. pending -= 1
  276. url = next(urls, None)
  277. if url is not None:
  278. launch(url)
  279. pending += 1
  280. return True
  281. except Empty:
  282. return None
  283. def _github_predates_runtime(repository: str, sha: str, cache_file: Path) -> Optional[bool]:
  284. """Read an unfetched release without Git writes. Definite verdicts are immutable per SHA;
  285. unknown verdicts expire so passive cache hits do not repeatedly contact an unreachable GitHub.
  286. Schema blobs use raw.githubusercontent.com rather than spending the anonymous API quota."""
  287. known = _read_json(cache_file)
  288. known = known if isinstance(known, dict) else {}
  289. cached = known.get(sha)
  290. if isinstance(cached, bool):
  291. return cached
  292. now = time.time()
  293. retry_at = cached.get("retryAt") if isinstance(cached, dict) else None
  294. if isinstance(retry_at, (int, float)) and now < retry_at:
  295. return None
  296. verdict = _read_runtime_verdict(repository, sha)
  297. try:
  298. from utils import atomic_json_write
  299. cache_file.parent.mkdir(parents=True, exist_ok=True)
  300. atomic_json_write(cache_file, {**known, sha: verdict if verdict is not None else
  301. {"retryAt": time.time() + _UPDATE_CHECK_FAILURE_CACHE_SECONDS}})
  302. except OSError as exc:
  303. logger.debug("Could not cache the release schema verdict: %s", exc)
  304. return verdict
  305. def _update_refuses(co: _Checkout, target: str, home: Path) -> bool:
  306. """The updater's downgrade refusal, asked read-only. An embedded checkout has no git to ask."""
  307. if co.embedded:
  308. return False
  309. from hermes_cli.update_downgrade_guard import would_refuse
  310. def git(*args: str) -> int:
  311. result = _git_run(list(args), cwd=co.root, git=co.git, text=False, timeout=20)
  312. return -1 if result is None else result.returncode
  313. def remote(sha: str) -> Optional[bool]:
  314. return _github_predates_runtime(co.repository or OFFICIAL_REPOSITORY, sha,
  315. home / "source-checks" / "release-runtime.json")
  316. return would_refuse(co.root, target, home, git=git, remote=remote)
  317. def _hold_refused_release(result: dict, co: _Checkout, home: Path) -> None:
  318. """Hold an offered release `hermes update` refuses (it predates the gateway runtime these session
  319. stores use). Covers releases off this checkout's history too, which the ancestry-only rollback
  320. test cannot see. Apply only after caching the release facts: stores can gain runtime history,
  321. or the only ledgered profile can be removed, between checks."""
  322. target = result.get("targetSha")
  323. if result.get("updateAvailable") and target and _update_refuses(co, target, home):
  324. result.update(updateAvailable=False, behind=0, held="downgrade", rollback=False)
  325. def _resolve_channel(result: dict, channel: str, co: _Checkout, *, forward_only: bool = False):
  326. """Resolve a release channel's target into ``result``; the SourceTarget, or None on error.
  327. A target with a pinned commit is final; one without names a branch to follow instead.
  328. """
  329. try:
  330. source_target = resolve_source_target(channel, [co.git] if not co.embedded else None, co.root,
  331. repository=co.repository or OFFICIAL_REPOSITORY,
  332. forward_only=forward_only)
  333. except (OSError, ValueError, subprocess.SubprocessError) as exc:
  334. result.update(error="release-unavailable", message=f"Could not resolve the {channel} source channel: {exc}")
  335. return None
  336. if source_target.commit:
  337. target = source_target.commit
  338. result.pop("branch", None)
  339. result.update(channel=channel, targetSha=target, updateAvailable=co.head != target,
  340. behind=0 if co.head == target else UPDATE_AVAILABLE_NO_COUNT,
  341. sourceVersion=source_target.version, buildId=source_target.build_id)
  342. # Forward-only pins the target to this checkout's own HEAD, newer than the release.
  343. # Always present: Desktop names the release only on an explicit False.
  344. result["aheadOfRelease"] = bool(getattr(source_target, "ahead", False))
  345. # A release HEAD already contains moves the checkout back: Desktop names it a rollback,
  346. # not a new update. Local ancestry only; an unknown relation stays an update.
  347. result["rollback"] = bool(co.head and co.head != target and not co.embedded and _git_ok(
  348. ["merge-base", "--is-ancestor", target, co.head], cwd=co.root, git=co.git))
  349. if source_target.retired:
  350. result["retirement"] = {"destination": source_target.channel, "sourceOnly": True}
  351. return source_target
  352. def _branch_remote(co: _Checkout, selected_branch: str) -> str:
  353. official_ssh = (co.repository and co.repository.lower() == OFFICIAL_REPOSITORY.lower()
  354. and co.origin.lower().startswith(("git@", "ssh://")))
  355. # The public official repo does not require the user's SSH credentials.
  356. # Forks must keep their own origin, including its authentication.
  357. return (f"https://github.com/{OFFICIAL_REPOSITORY}.git"
  358. if co.embedded or (official_ssh and selected_branch != "main") else "origin")
  359. def _heal_deleted_branch(branch_config_path: Path, desktop_config: dict) -> None:
  360. """Point the Desktop branch setting back at main after its branch was deleted upstream."""
  361. # Do not overwrite a concurrent choice made while the network probe ran.
  362. if _read_json(branch_config_path) == desktop_config:
  363. from utils import atomic_json_write
  364. atomic_json_write(branch_config_path, {**desktop_config, "branch": "main"})
  365. def _unhealable_reason(co: _Checkout, branch: str) -> Optional[str]:
  366. """Why a branch the remote does not advertise must keep its pin; None when healing loses nothing.
  367. An empty ref advertisement cannot tell "merged and deleted upstream" from "never pushed":
  368. only a branch that was once published (remote-tracking ref or configured upstream, which
  369. survives ``fetch --prune``) and whose commits are all in main may be re-pinned to main.
  370. """
  371. if co.embedded:
  372. return None
  373. local = f"refs/heads/{branch}"
  374. if not _git_ok(["rev-parse", "--verify", "--quiet", local], cwd=co.root, git=co.git):
  375. return None # Nothing in this checkout to abandon.
  376. if not (_git_ok(["rev-parse", "--verify", "--quiet", f"refs/remotes/origin/{branch}"], cwd=co.root, git=co.git)
  377. or _git_ok(["config", "--get", f"branch.{branch}.merge"], cwd=co.root, git=co.git)):
  378. return "never-pushed"
  379. for base in ("refs/remotes/origin/main", "refs/heads/main"):
  380. # `git cherry` also treats rebase-merged commits (same patch, new SHA) as merged.
  381. cherry = _git_run(["cherry", base, local], cwd=co.root, git=co.git, timeout=10)
  382. if cherry is not None and cherry.returncode == 0:
  383. return "unmerged" if any(line.startswith("+") for line in cherry.stdout.splitlines()) else None
  384. return "unmerged" # Unknown merge state keeps the branch.
  385. def _behind_count(co: _Checkout, target: str) -> tuple[int, list[dict]]:
  386. """``(behind, commits)`` for ``target``: local ancestry first, then the GitHub compare API."""
  387. if co.head == target or (not co.embedded and _git_ok(
  388. ["merge-base", "--is-ancestor", target, co.head], cwd=co.root, git=co.git)):
  389. return 0, []
  390. if co.repository:
  391. payload = _github_compare(co.head, target, co.repository)
  392. ahead = (payload or {}).get("ahead_by")
  393. if isinstance(ahead, int) and not isinstance(ahead, bool) and ahead >= 0:
  394. return ahead, (_quiet(lambda: _commits(payload), []) if ahead else [])
  395. return UPDATE_AVAILABLE_NO_COUNT, []
  396. def _check_branch(result: dict, co: _Checkout, selected_branch: str, *,
  397. heal: Optional[tuple[Path, dict]]) -> None:
  398. """Compare the checkout with ``selected_branch``'s remote tip, falling back to main if it was deleted."""
  399. result["branch"] = selected_branch
  400. remote = _branch_remote(co, selected_branch)
  401. target, missing, failure = _branch_tip(co.repository, selected_branch, co.root, co.git, remote)
  402. reason = _unhealable_reason(co, selected_branch) if missing and selected_branch != "main" else None
  403. if reason:
  404. detail = ("has never been pushed" if reason == "never-pushed"
  405. else "is gone from the remote but has commits that are not in main")
  406. result.update(error="branch-local-only", localOnly=True,
  407. message=f"Branch '{selected_branch}' {detail}; keeping it instead of switching to main.")
  408. return
  409. if missing and selected_branch != "main":
  410. result["branch"] = "main"
  411. if heal:
  412. _heal_deleted_branch(*heal)
  413. target, _, failure = _branch_tip(co.repository, "main", co.root, co.git, remote if co.embedded else "origin")
  414. if target is None:
  415. result.update(error="fetch-failed",
  416. message=f"Could not resolve the remote branch tip: {failure}" if failure
  417. else "Could not resolve the remote branch tip.")
  418. return
  419. behind, commits = _behind_count(co, target)
  420. result["commits"] = commits
  421. result.update(targetSha=target, behind=behind, updateAvailable=behind != 0)
  422. def check_for_updates(*, install_root: Path | None = None, home: Path | None = None,
  423. branch: str | None = None, channel: str | None = None,
  424. cache_path: Path | None = None, branch_config_path: Path | None = None,
  425. force: bool = False,
  426. passive: bool = False, git: str = "git") -> dict:
  427. """Return a presentation-ready status. Omitted branch follows the current checkout.
  428. Only the default (running installation) may use HERMES_REVISION. An explicit
  429. target must never inherit the host process's embedded revision or stamp.
  430. """
  431. from hermes_cli.config import get_project_root, require_readable_config_before_write
  432. from hermes_cli.steward import read_install_stamp
  433. from hermes_cli.update_channel import channel_record, install_id, resolve_update_channel, rides_default_channel
  434. from hermes_cli.release_channels import validate_name
  435. embedded = (os.environ.get("HERMES_REVISION") or None) if install_root is None else None
  436. root = Path(install_root if install_root is not None else get_project_root()).resolve()
  437. home = Path(home if home is not None else get_hermes_home()).resolve()
  438. result = {"supported": False, "hermesRoot": str(root), "behind": None, "commits": []}
  439. unsupported = _unsupported_reason(read_install_stamp(root), root,
  440. explicit_root=install_root is not None, embedded=embedded)
  441. if unsupported:
  442. return {**result, **unsupported}
  443. config = require_readable_config_before_write(home / "config.yaml")
  444. if passive and (config.get("updates") or {}).get("check") is False:
  445. return {**result, "reason": "disabled"}
  446. channel = resolve_update_channel(config, root) if channel is None else validate_name(channel)
  447. forward_only = rides_default_channel(channel_record(config, root), channel, root)
  448. co = _read_checkout(root, _installed_git(git), embedded)
  449. desktop_config = _read_json(branch_config_path) if branch_config_path else None
  450. configured_branch = _configured_branch(desktop_config)
  451. selected_branch = branch or configured_branch or _checked_out_branch(co.current_branch, "main")
  452. result.update(supported=True, currentSha=co.head, currentBranch=co.current_branch, dirty=co.dirty)
  453. if channel != "main":
  454. result["channel"] = channel
  455. else:
  456. result["branch"] = selected_branch
  457. identity = {"root": str(root), "home": str(home), "head": co.head, "origin": co.origin, "branch": selected_branch,
  458. "channel": channel, "embedded": embedded, "branchOverride": branch is not None, "channelProtocol": 3,
  459. "forwardOnly": forward_only}
  460. cache_file = Path(cache_path) if cache_path is not None else home / "source-checks" / f"{install_id(root)}.json"
  461. now = time.time()
  462. cached = None if force else _cached_status(cache_file, identity, now)
  463. if cached is not None:
  464. cached = {**cached, "dirty": co.dirty, "currentBranch": co.current_branch}
  465. if cached.get("channel"):
  466. _hold_refused_release(cached, co, home)
  467. return cached
  468. result["fetchedAt"] = int(now * 1000)
  469. source_target = None
  470. if not _is_full_sha(co.head):
  471. result.update(error="head-unavailable", message="Could not read the installed revision.")
  472. elif branch is None:
  473. source_target = _resolve_channel(result, channel, co, forward_only=forward_only)
  474. if source_target is not None and not source_target.commit:
  475. # The record supplies a default, not permission to leave the user's branch.
  476. selected_branch = configured_branch or _checked_out_branch(co.current_branch, source_target.branch)
  477. if "error" not in result and (source_target is None or source_target.branch is not None):
  478. # Only a Desktop-configured branch the caller did not override is healed.
  479. heal = branch_config_path and not branch and configured_branch == selected_branch
  480. _check_branch(result, co, selected_branch,
  481. heal=(branch_config_path, desktop_config) if heal else None)
  482. _write_cache(cache_file, identity, now, result)
  483. if result.get("channel"):
  484. _hold_refused_release(result, co, home)
  485. return result
  486. def main() -> None:
  487. import argparse
  488. import contextlib
  489. import sys
  490. parser = argparse.ArgumentParser(description=__doc__)
  491. parser.add_argument("--install-root", type=Path, required=True)
  492. parser.add_argument("--home", type=Path, required=True)
  493. parser.add_argument("--git", default="git")
  494. parser.add_argument("--branch")
  495. from hermes_cli.release_channels import validate_name
  496. parser.add_argument("--channel", type=validate_name)
  497. parser.add_argument("--cache-path", type=Path)
  498. parser.add_argument("--branch-config-path", type=Path)
  499. parser.add_argument("--force", action="store_true")
  500. parser.add_argument("--set-channel", type=validate_name,
  501. help="Persist this install's channel (the Desktop selector), then report as usual.")
  502. args = parser.parse_args()
  503. with contextlib.redirect_stdout(sys.stderr):
  504. if args.set_channel:
  505. from hermes_constants import set_hermes_home_override
  506. from hermes_cli.update_channel import set_install_channel
  507. # The record belongs in the --home profile's config.yaml, as the check reads it.
  508. set_hermes_home_override(args.home)
  509. set_install_channel(args.set_channel, args.install_root)
  510. args.force = True
  511. result = check_for_updates(**{k: v for k, v in vars(args).items() if k != "set_channel"})
  512. if isinstance(result, dict):
  513. # Older runtimes reject --set-channel; Desktop offers its selector only on this flag.
  514. result["channelSelectable"] = True
  515. print(json.dumps(result))
  516. if __name__ == "__main__":
  517. main()