The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): judge a release the checkout has not fetched from GitHub
ethernetf1390b5e56c8
diff --git a/hermes_cli/source_check.py b/hermes_cli/source_check.pyindex 34fac01ea60..e7b8c4a2a60 100644--- a/hermes_cli/source_check.py+++ b/hermes_cli/source_check.py@@ -288,6 +288,54 @@ def _write_cache(cache_file: Path, identity: dict, now: float, result: dict) ->logger.debug("Could not cache source check: %s", exc)+def _github_predates_runtime(repository: str, sha: str, cache_file: Path) -> Optional[bool]:+ """Whether release ``sha`` predates the gateway runtime, read from GitHub: the checkout has not+ fetched it, and this check never fetches. None when GitHub cannot tell us.++ One API call lists the release's root tree; the state modules come from raw.githubusercontent.com,+ which does not spend the 60/hour anonymous API quota. A commit's tree never changes, so a definite+ answer is cached per sha for good."""+ from fnmatch import fnmatchcase++ from hermes_cli.update_downgrade_guard import STATE_MODULES, defines_runtime++ known = _read_json(cache_file)+ known = known if isinstance(known, dict) else {}+ if isinstance(known.get(sha), bool):+ return known[sha]+ tree = _quiet(lambda: json.loads(_request(f"https://api.github.com/repos/{repository}/git/trees/{sha}")))+ entries = tree.get("tree") if isinstance(tree, dict) and not tree.get("truncated") else None+ if not isinstance(entries, list):+ return None+ paths = [e["path"] for e in entries+ if isinstance(e, dict) and e.get("type") == "blob" and fnmatchcase(str(e.get("path")), STATE_MODULES)]+ if not paths:+ return None # not a hermes-agent tree we recognise: no claim either way+ unread = []++ def sources():+ for path in paths:+ text = _quiet(lambda: _request_with(+ f"https://raw.githubusercontent.com/{repository}/{sha}/{quote(path)}", "*/*", None))+ if text is None:+ unread.append(path)+ return+ yield text+ if defines_runtime(sources()):+ verdict = False+ elif unread:+ return None # a module we could not read may hold the marker+ else:+ verdict = True+ try:+ from utils import atomic_json_write+ cache_file.parent.mkdir(parents=True, exist_ok=True)+ atomic_json_write(cache_file, {**known, sha: verdict})+ except OSError as exc:+ logger.debug("Could not cache the release schema verdict: %s", exc)+ return verdict++def _update_refuses(co: _Checkout, target: str, home: Path) -> bool:"""The updater's downgrade refusal, asked read-only. An embedded checkout has no git to ask."""if co.embedded:@@ -297,14 +345,18 @@ def _update_refuses(co: _Checkout, target: str, home: Path) -> bool:def git(*args: str) -> int:result = _git_run(list(args), cwd=co.root, git=co.git, text=False, timeout=20)return -1 if result is None else result.returncode- return would_refuse(co.root, target, home, git=git)++ def remote(sha: str) -> Optional[bool]:+ return _github_predates_runtime(co.repository or OFFICIAL_REPOSITORY, sha,+ home / "source-checks" / "release-runtime.json")+ return would_refuse(co.root, target, home, git=git, remote=remote)def _hold_refused_release(result: dict, co: _Checkout, home: Path) -> None:"""Hold an offered release `hermes update` refuses (it predates the gateway runtime these sessionstores use). Covers releases off this checkout's history too, which the ancestry-only rollback- test cannot see. Runs on cached offers as well: the stores gain runtime history between checks,- and a release object the checkout has not fetched yet proves nothing until the update fetches it."""+ test cannot see. Runs on cached offers as well, because the stores gain runtime history between+ checks."""target = result.get("targetSha")if result.get("updateAvailable") and target and _update_refuses(co, target, home):result.update(updateAvailable=False, behind=0, held="downgrade")diff --git a/hermes_cli/update_cmd_check.py b/hermes_cli/update_cmd_check.pyindex 80dd1b12a85..f04b962b676 100644--- a/hermes_cli/update_cmd_check.py+++ b/hermes_cli/update_cmd_check.py@@ -62,10 +62,12 @@ def report_pack_tidy(root: Path) -> None:print(f" (git cleanup stopped at its {TIDY_BUDGET_SECONDS}s limit; the next update continues it)")-def _refuses(git_cmd: list[str], root: Path, target: str) -> bool:+def _refuses(git_cmd: list[str], root: Path, target: str, repository: str) -> bool:"""`hermes update` would refuse ``target`` (see update_downgrade_guard), so --check must not offer it."""from hermes_cli.update_downgrade_guard import would_refusefrom hermes_cli._subprocess_compat import NO_LAZY_FETCH_ENV, noninteractive_git_env+ from hermes_cli.source_check import _github_predates_runtime+ from hermes_constants import get_hermes_homedef git(*args: str) -> int:try:@@ -73,7 +75,10 @@ def _refuses(git_cmd: list[str], root: Path, target: str) -> bool:timeout=20).returncodeexcept (OSError, subprocess.SubprocessError):return -1- return would_refuse(root, target, git=git)++ def remote(sha: str):+ return _github_predates_runtime(repository, sha, get_hermes_home() / "source-checks" / "release-runtime.json")+ return would_refuse(root, target, git=git, remote=remote)def channel_compare_branch(selected_channel: str, git_cmd: list[str], root: Path) -> str | None:@@ -102,7 +107,7 @@ def channel_compare_branch(selected_channel: str, git_cmd: list[str], root: Pathprint(f"✓ No newer release: {target.label}.")elif _uc()._capture_head_sha(git_cmd, root) == target.commit:print(f"✓ Up to date with the latest release ({target.label}).")- elif _refuses(git_cmd, root, target.commit):+ elif _refuses(git_cmd, root, target.commit, target.repository):# Before the rollback branch: a release this checkout contains is held too, not moved back to.print(f"→ Holding at this build: {target.label} predates the gateway runtime your sessions use.")print(" `hermes update` stays on this build; the next release that includes the runtime"diff --git a/hermes_cli/update_downgrade_guard.py b/hermes_cli/update_downgrade_guard.pyindex 3812b99c0e3..5fc81824f34 100644--- a/hermes_cli/update_downgrade_guard.py+++ b/hermes_cli/update_downgrade_guard.py@@ -11,13 +11,14 @@ reason to refuse, and a target that descends from the running commit is a forwarfrom __future__ import annotationsimport sqlite3-from collections.abc import Callable+from collections.abc import Callable, Iterablefrom contextlib import closingfrom pathlib import Pathfrom typing import Optional# The runtime ledger DDL: a target whose state-store modules lack it predates the cutover._RUNTIME_SCHEMA_MARKER = "CREATE TABLE IF NOT EXISTS session_admissions"+STATE_MODULES = "hermes_state*.py" # git pathspec and fnmatch pattern alike (``*`` crosses ``/`` in both)_LEDGER_PROBE = ("SELECT EXISTS(SELECT 1 FROM session_admissions) ""OR EXISTS(SELECT 1 FROM worker_executions)")_DOCS = "https://hermes-agent.nousresearch.com/docs/getting-started/updating#rolling-back-to-an-older-release"@@ -36,19 +37,30 @@ def _updater_git(git_cmd, root: Path) -> Callable[..., int]:return git+def defines_runtime(sources: Iterable[str]) -> bool:+ """Whether any of a tree's ``STATE_MODULES`` sources defines the runtime ledger. Lazy: stops at+ the first match, so a caller reading sources over the network fetches no more than it needs."""+ return any(_RUNTIME_SCHEMA_MARKER in source for source in sources)++def target_predates_runtime(git_cmd, root: Path, target_ref: str, *,- git: Optional[Callable[..., int]] = None) -> bool:+ git: Optional[Callable[..., int]] = None,+ remote: Optional[Callable[[str], Optional[bool]]] = None) -> bool:"""True when ``target_ref`` does not descend from HEAD and none of its ``hermes_state*.py`` filesdefines the runtime ledger. The pathspec keeps a blobless partial clone from fetching the wholetree. Any git failure proves nothing (False). ``git`` runs one git command and returns its exit- code; the update check passes its own read-only probe."""+ code; the update check passes its own read-only probe.++ ``remote`` answers the same question for a target this checkout has not fetched (True, False, or+ None when it cannot tell). The update check passes one because it never fetches, and a release+ off the checkout's tracked branch is usually absent until ``hermes update`` fetches it."""git = git or _updater_git(git_cmd, root)if git("merge-base", "--is-ancestor", "HEAD", target_ref) == 0:return False # forward update: whatever the target's schema, it was written knowing this oneif git("cat-file", "-e", f"{target_ref}^{{commit}}") != 0:- return False+ return remote is not None and remote(target_ref) is True# Exit 1 = no match (the target lacks the ledger); 0 = found; anything else is a git error.- return git("grep", "-q", "-F", _RUNTIME_SCHEMA_MARKER, target_ref, "--", "hermes_state*.py") == 1+ return git("grep", "-q", "-F", _RUNTIME_SCHEMA_MARKER, target_ref, "--", STATE_MODULES) == 1def _has_ledger_rows(db_path: Path) -> bool:@@ -99,10 +111,13 @@ def _ledgered_profiles(home: Path | None) -> list[tuple[str, Path]]:return [(name, h) for name, h in profiles if _has_ledger_rows(h / "state.db")]-def would_refuse(root: Path, target_ref: str, home: Path | None = None, *, git: Callable[..., int]) -> bool:+def would_refuse(root: Path, target_ref: str, home: Path | None = None, *, git: Callable[..., int],+ remote: Optional[Callable[[str], Optional[bool]]] = None) -> bool:"""Whether ``hermes update`` would refuse ``target_ref`` here: the update check's read-only twin of- :func:`downgrade_refusal`, so a release the updater refuses is never offered as an update."""- return bool(_ledgered_profiles(home)) and target_predates_runtime(None, root, target_ref, git=git)+ :func:`downgrade_refusal`, so a release the updater refuses is never offered as an update.+ The store scan runs first, so ``remote`` is only consulted when some store has runtime history."""+ return bool(_ledgered_profiles(home)) and target_predates_runtime(+ None, root, target_ref, git=git, remote=remote)def downgrade_refusal(git_cmd, root: Path, target_ref: str, home: Path | None = None) -> str | None:diff --git a/tests/hermes_cli/test_source_check.py b/tests/hermes_cli/test_source_check.pyindex eece237a1ce..b3676145bd9 100644--- a/tests/hermes_cli/test_source_check.py+++ b/tests/hermes_cli/test_source_check.py@@ -89,7 +89,7 @@ def installation(tmp_path, monkeypatch):def local(request, *args, **kwargs):url = urlsplit(request.full_url)- assert url.hostname in {"api.github.com", "hermes-assets.nousresearch.com"}+ assert url.hostname in {"api.github.com", "hermes-assets.nousresearch.com", "raw.githubusercontent.com"}rewritten = urllib.request.Request(f"http://127.0.0.1:{server.server_port}{url.path}" + (f"?{url.query}" if url.query else ""),headers=dict(request.header_items()))@@ -631,3 +631,51 @@ def test_stable_release_the_updater_refuses_is_held_not_offered(installation, tm_ledgered_store(home)cached = check_for_updates(install_root=root, home=home, channel="stable")assert cached["updateAvailable"] is False and cached.get("held") == "downgrade", cached++[email protected]("ledgered", [True, False])+def test_an_unfetched_release_is_judged_from_github(installation, tmp_path, monkeypatch, ledgered):+ """The usual install tracks only ``main``, so a release cut beside it is absent until `hermes+ update` fetches it, and a local probe proves nothing. The check reads the release's state modules+ from GitHub instead, so it still holds what the update would refuse (#140215 review)."""+ from hermes_cli.source_check import check_for_updates+ from tests.hermes_cli.test_update_downgrade_guard import _ledgered_store++ root, _linked, home, base, _head, responses, requests, git = installation+ monkeypatch.setattr("hermes_cli.backup._sibling_profile_homes", lambda h: [])+ # The release lives on origin only: cut in a scratch clone, pushed there, never fetched here.+ bare, cut = tmp_path / "origin.git", tmp_path / "cut"+ git("clone", "-q", "--bare", str(root), str(bare), cwd=tmp_path)+ git("clone", "-q", "--no-local", str(bare), str(cut), cwd=tmp_path)+ git("checkout", "-q", "-b", "release-line", base, cwd=cut)+ git("commit", "-q", "--allow-empty", "-m", "release from the older line", cwd=cut)+ release = git("rev-parse", "HEAD", cwd=cut)+ git("tag", "v1.2.3", release, cwd=cut)+ git("push", "-q", "origin", "v1.2.3", cwd=cut)+ git("remote", "set-url", "origin", str(bare))+ assert subprocess.run(["git", "cat-file", "-e", f"{release}^{{commit}}"], cwd=root,+ stderr=subprocess.DEVNULL, check=False).returncode != 0+ api = "/repos/NousResearch/hermes-agent"+ responses[f"{api}/releases/latest"] = (200, {"draft": False, "prerelease": False, "tag_name": "v1.2.3"})+ responses[f"{api}/commits/v1.2.3"] = (200, {"sha": release})+ responses[f"{api}/compare/{git('rev-parse', 'HEAD')}...{release}"] = (200, {"status": "diverged"})+ responses[f"{api}/git/trees/{release}"] = (200, {"truncated": False, "tree": [+ {"path": "hermes_state.py", "type": "blob"}, {"path": "hermes_state_common.py", "type": "blob"},+ {"path": "run_agent.py", "type": "blob"}]})+ responses[f"/NousResearch/hermes-agent/{release}/hermes_state.py"] = (200, "from hermes_state_common import *\n")+ responses[f"/NousResearch/hermes-agent/{release}/hermes_state_common.py"] = (+ 200, "SCHEMA_SQL = 'CREATE TABLE IF NOT EXISTS sessions (id)'\n")+ if ledgered:+ _ledgered_store(home)++ status = check_for_updates(install_root=root, home=home, channel="stable", force=True)++ assert status.get("targetSha") == release, status+ assert status["updateAvailable"] is not ledgered+ assert status.get("held") == ("downgrade" if ledgered else None)+ # Only a store with runtime history pays for the lookup, and a release tree is read once.+ trees = [p for p in requests if "/git/trees/" in p]+ assert len(trees) == int(ledgered)+ if ledgered:+ check_for_updates(install_root=root, home=home, channel="stable", force=True)+ assert len([p for p in requests if "/git/trees/" in p]) == 1diff --git a/tests/hermes_cli/test_update_downgrade_guard.py b/tests/hermes_cli/test_update_downgrade_guard.pyindex 192b5b2b8d7..f7fd23111b3 100644--- a/tests/hermes_cli/test_update_downgrade_guard.py+++ b/tests/hermes_cli/test_update_downgrade_guard.py@@ -117,7 +117,8 @@ def test_check_holds_a_release_that_update_would_refuse(repo, tmp_path, monkeypa_git(repo, "commit", "-qm", "release from the older line")release = _git(repo, "rev-parse", "HEAD")_git(repo, "checkout", "-q", "main")- target = SimpleNamespace(commit=release, retired=False, ahead=False, label="v1.2.3", branch=None)+ target = SimpleNamespace(commit=release, retired=False, ahead=False, label="v1.2.3", branch=None,+ repository="NousResearch/hermes-agent")monkeypatch.setattr(source_releases, "resolve_source_target", lambda *a, **k: target)update_cmd_check.channel_compare_branch("stable", ["git"], repo)