From 83f2322e88087b5c8e22396ee2b8ebfb13a3a8f9 Mon Sep 17 00:00:00 2001 From: GordieBox Date: Sat, 26 Sep 2026 02:33:02 -0500 Subject: [PATCH] fix(update): trust the checkout over stale installer metadata The self-updater read the installed revision from Hermes's .install-metadata.json before looking at the plugin's own Git HEAD. That record is only rewritten by `hermes plugins install/update`, so any other way the checkout moves (a fast-forward pull, for example) leaves it pointing at an old commit. On one host it still named a Sep 23 revision while the checkout was eight PRs ahead, and the updater kept reporting and activating against bytes that were no longer on disk. A Git checkout now identifies itself by HEAD first. Archive-style installs, which ship without .git, still fall back to the installer record exactly as before. The same host also showed that a timed_out operation never ends. The phase is non-terminal on purpose so an ambiguous restart never earns a second blind one, but nothing retired it once the ambiguity was gone, so every later `hermes loopdy update` silently re-printed the old operation instead of starting a new one. Reconciliation now fails the operation as superseded only when a newer gateway lifecycle is running different bytes and the installation is positively known to hold different bytes too. An unknown installation, or the target still being installed, keeps the operation held as before. --- loopdy_plugin/plugin_update.py | 72 ++++++++++++++++++++------- tests/test_plugin_update_execution.py | 39 +++++++++++++++ 2 files changed, 93 insertions(+), 18 deletions(-) diff --git a/loopdy_plugin/plugin_update.py b/loopdy_plugin/plugin_update.py index 28d1ee8..ba1e53e 100644 --- a/loopdy_plugin/plugin_update.py +++ b/loopdy_plugin/plugin_update.py @@ -62,6 +62,17 @@ def _hermes_home_for_plugin(plugin_root: Path) -> Path: def _metadata_revision(plugin_root: Path) -> str: + """Revision of the plugin bytes actually installed at ``plugin_root``. + + A Git checkout identifies itself by HEAD. The installer's metadata record is + written only by ``hermes plugins install/update``, so it goes stale when the + checkout moves any other way (for example a fast-forward pull), and trusting + it would report and activate against a revision that is no longer on disk. + Archive-style installs carry no ``.git`` and rely on the metadata record. + """ + head = _git_head_revision(plugin_root) + if head: + return head home = _hermes_home_for_plugin(plugin_root) metadata_path = home / "plugins" / ".install-metadata.json" try: @@ -72,27 +83,29 @@ def _metadata_revision(plugin_root: Path) -> str: return revision except (OSError, ValueError, TypeError): pass - # A directly cloned standalone plugin can identify itself without metadata. - if (plugin_root / ".git").is_dir(): - try: - result = subprocess.run( - ["git", "rev-parse", "HEAD"], - cwd=str(plugin_root), - stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - text=True, - timeout=5, - env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")}, - ) - revision = result.stdout.strip().lower() - if result.returncode == 0 and _REVISION.fullmatch(revision): - return revision - except (OSError, subprocess.TimeoutExpired): - pass return "" +def _git_head_revision(plugin_root: Path) -> str: + if not (plugin_root / ".git").is_dir(): + return "" + try: + result = subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=str(plugin_root), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + timeout=5, + env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")}, + ) + except (OSError, subprocess.TimeoutExpired): + return "" + revision = result.stdout.strip().lower() + return revision if result.returncode == 0 and _REVISION.fullmatch(revision) else "" + + # These values are intentionally fixed at module import. Reading newly installed # files from an old gateway process must never masquerade as activation. LOADED_REVISION = _metadata_revision(_PLUGIN_ROOT) @@ -458,6 +471,29 @@ def _reconcile_completion(self, state: dict[str, Any], operation: dict[str, Any] operation["message"] = "The updated bighelp plugin is active and Link responded." operation["updated_at"] = int(time.time()) return True + active = str(runtime.get("revision") or "") + installed = _metadata_revision(self.plugin_root) + if ( + _REVISION.fullmatch(target) + and fresh + and _REVISION.fullmatch(active) + and active != target + and _REVISION.fullmatch(installed) + and installed != target + ): + # A gateway lifecycle newer than this operation is running other + # bytes, and the installation is positively known to hold other + # bytes too, so this target can never activate and no restart is in + # flight. Without this, the non-terminal phase would refuse every + # later update on this host forever. An unknown installation stays + # held: absence of evidence is not supersession. + operation["phase"] = "failed" + operation["message"] = _bounded_message( + "Superseded: the gateway restarted onto a different installed revision. " + "Start a new update if one is still needed." + ) + operation["updated_at"] = int(time.time()) + return True return False def _trim_operations(self, state: dict[str, Any]) -> None: diff --git a/tests/test_plugin_update_execution.py b/tests/test_plugin_update_execution.py index 260ee88..58cf8dd 100644 --- a/tests/test_plugin_update_execution.py +++ b/tests/test_plugin_update_execution.py @@ -3,6 +3,7 @@ import json import os from pathlib import Path +import shutil import subprocess import sys import tempfile @@ -72,6 +73,44 @@ def test_ambiguous_timeout_does_not_authorize_a_second_update(self): with self.assertRaises(ValueError): self.manager.start("update_second_0123456789", self.device, True) + def test_git_checkout_revision_wins_over_a_stale_installer_record(self): + env = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_SYSTEM": os.devnull} + def git(*args): + return subprocess.run(["git", "-C", str(self.plugin), *args], check=True, capture_output=True, text=True, env=env).stdout.strip() + git("init", "-q") + git("add", ".") + git("-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-q", "-m", "fixture") + head = git("rev-parse", "HEAD") + (self.root / "plugins" / ".install-metadata.json").write_text(json.dumps({"loopdy": {"pinned": True, "revision": "d" * 40, "source": "https://github.com/promptclickrun/loopdy-plugin"}})) + self.assertEqual(api._metadata_revision(self.plugin), head) + shutil.rmtree(self.plugin / ".git") + # Archive-style installs have no checkout and keep using the installer record. + self.assertEqual(api._metadata_revision(self.plugin), "d" * 40) + + def test_timeout_superseded_by_a_newer_runtime_on_other_bytes_releases_the_host(self): + target, other = "a" * 40, "c" * 40 + with patch.object(api, "LOADED_REVISION", "b" * 40), patch.object(api, "RUNTIME_ID", "runtime_started"): + self.manager.record_runtime_loaded() + self.begin() + self.manager._worker_transition(self.operation_id, "timed_out", "Waiting", target_revision=target, restart_requested_at=1) + with patch.object(api, "_metadata_revision", return_value=other): + # Same lifecycle that started the operation: still ambiguous, still held. + self.assertEqual(self.manager.status(self.operation_id, self.device)["phase"], "timed_out") + with patch.object(api, "LOADED_REVISION", other), patch.object(api, "RUNTIME_ID", "runtime_later"): + self.manager.record_runtime_loaded() + status = self.manager.status(self.operation_id, self.device) + self.assertEqual(status["phase"], "failed") + self.assertIn("Superseded", status["message"]) + self.assertEqual(self.manager.start("update_second_0123456789", self.device, True)["phase"], "accepted") + + def test_timeout_is_held_while_the_target_is_still_installed(self): + target = "a" * 40 + self.begin() + self.manager._worker_transition(self.operation_id, "timed_out", "Waiting", target_revision=target, restart_requested_at=1) + with patch.object(api, "_metadata_revision", return_value=target), patch.object(api, "LOADED_REVISION", "c" * 40), patch.object(api, "RUNTIME_ID", "runtime_later"): + self.manager.record_runtime_loaded() + self.assertEqual(self.manager.status(self.operation_id, self.device)["phase"], "timed_out") + def test_completion_requires_fresh_revision_and_authenticated_owner_response(self): revision = "a" * 40 with patch.object(api, "LOADED_REVISION", revision), patch.object(api, "RUNTIME_ID", "runtime_old"):