The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): refuse to move an install back past the gateway runtime once a state.db depends on it
Teknium1427a3a38c45
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.jsonindex 622b208b056..30600a878ef 100644--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json@@ -2724,6 +2724,7 @@"deps_failed","detached_head","disk_full",+ "downgrade_refused","download_failed","exception","fetch_failed",diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex 3aa140cea62..f96b1f40368 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -495,6 +495,7 @@ UPDATE_STOP_CLASSES = frozenset({"commit_point_refused", # the commit point could not be armed durably; nothing moved"detached_head", # a detached checkout stayed put, or its commits could not be backed up"disk_full", # (see above)+ "downgrade_refused", # the target predates the gateway runtime a state.db already uses"download_failed", # the ZIP fallback download failed"fetch_failed", # git fetch failed"git_in_progress", # a merge/rebase/cherry-pick/... was already in progressdiff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex a8768a60ef9..68b2de01957 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -1263,6 +1263,11 @@ def _switch_branch_at_commit_point(git_cmd, branch, target_ref, *, pre, stash):def _refuse_before_commit_point(git_cmd, target_ref, _windows_gateway_resume) -> None:"""Preconditions that used to fail AFTER the swap: refuse with the install untouched."""reason = _commit.preflight_refusal(git_cmd, _m().PROJECT_ROOT, target_ref, _UPDATE_CRITICAL_FILES)+ if reason is None:+ from hermes_cli.update_downgrade_guard import downgrade_refusal+ reason = downgrade_refusal(git_cmd, _m().PROJECT_ROOT, target_ref)+ if reason is not None:+ _record_stop("downgrade_refused")if reason is None:returnprint(reason)diff --git a/hermes_cli/update_downgrade_guard.py b/hermes_cli/update_downgrade_guard.pynew file mode 100644index 00000000000..5e83eb6e62b--- /dev/null+++ b/hermes_cli/update_downgrade_guard.py@@ -0,0 +1,99 @@+"""Refuse an update whose target predates the gateway runtime while a state.db already depends on it.++Releases before the gateway cutover know nothing of the runtime ledgers (``session_admissions`` /+``worker_executions``, ``ON DELETE RESTRICT``) and stamp the same ``schema_version``, so moving the+code back under a store that holds ledger rows leaves every session with that history undeletable+there. Downgrading is unsupported: the update refuses before anything moves and names the recovery+point that predates the cutover. Read-only throughout; a store or target it cannot read is never a+reason to refuse, and a target that descends from the running commit is a forward update.+"""++from __future__ import annotations++import sqlite3+from contextlib import closing+from pathlib import Path++# 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"+_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"+++def target_predates_runtime(git_cmd, root: Path, target_ref: str) -> bool:+ """True when ``target_ref`` does not descend from HEAD and none of its ``hermes_state*.py`` files+ defines the runtime ledger. The pathspec keeps a blobless partial clone from fetching the whole+ tree. Any git failure proves nothing (False)."""+ import subprocess++ from hermes_cli.update_custody import run_git++ def git(*args: str) -> int:+ try:+ return run_git(git_cmd, list(args), cwd=str(root), capture_output=True, timeout=120).returncode+ except (OSError, subprocess.SubprocessError):+ return -1++ if git("merge-base", "--is-ancestor", "HEAD", target_ref) == 0:+ return False # forward update: whatever the target's schema, it was written knowing this one+ if git("cat-file", "-e", f"{target_ref}^{{commit}}") != 0:+ return False+ # 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+++def _has_ledger_rows(db_path: Path) -> bool:+ if not db_path.is_file():+ return False+ from hermes_state_holders import read_only_db_uri+ try:+ with closing(sqlite3.connect(read_only_db_uri(db_path), uri=True, timeout=5.0)) as conn:+ return bool(conn.execute(_LEDGER_PROBE).fetchone()[0])+ except sqlite3.Error:+ return False # no ledger tables yet, or unreadable: nothing an older release would trip on+++def _pre_runtime_snapshot(home: Path) -> str | None:+ """Newest quick snapshot of ``home`` holding a state.db from before the runtime ledger."""+ from hermes_cli.backup import _quick_snapshot_root+ from hermes_state_holders import read_only_db_uri+ root = _quick_snapshot_root(home)+ for snap in sorted(root.iterdir(), reverse=True) if root.is_dir() else ():+ db = snap / "state.db"+ if snap.name.startswith(".") or not db.is_file():+ continue+ try:+ with closing(sqlite3.connect(read_only_db_uri(db), uri=True)) as conn:+ if conn.execute("SELECT 1 FROM sqlite_master WHERE name='session_admissions'").fetchone() is None:+ return snap.name+ except sqlite3.Error:+ continue+ return None+++def downgrade_refusal(git_cmd, root: Path, target_ref: str, home: Path | None = None) -> str | None:+ """Why the update must not move to ``target_ref``, or ``None``: refuses only a pre-runtime target+ while this profile's or a sibling profile's state.db holds runtime ledger rows."""+ from hermes_cli.backup import _sibling_profile_homes+ from hermes_constants import get_hermes_home++ home = Path(home or get_hermes_home())+ profiles = [("", home), *_sibling_profile_homes(home)]+ ledgered = [(name, h) for name, h in profiles if _has_ledger_rows(h / "state.db")]+ if not ledgered or not target_predates_runtime(git_cmd, root, target_ref):+ return None+ lines = [f"✗ Refusing to move this install to {target_ref[:12]}: that release predates the gateway runtime "+ "these session stores now use. Downgrading is unsupported.",+ *(f" {h / 'state.db'} has gateway runtime history." for _name, h in ledgered),+ " The older release could not delete or prune those sessions.",+ " To go back anyway: run `hermes gateway stop`, check out the older release with git, then put back "+ "each store's copy from before the upgrade:"]+ for name, h in ledgered:+ snapshot = _pre_runtime_snapshot(h)+ hermes = f"hermes -p {name}" if name else "hermes"+ lines.append(f" {h}: run `{hermes}` and enter `/snapshot restore {snapshot}`." if snapshot else+ f" {h}: no pre-update snapshot predates the upgrade; restore a full backup taken before "+ f"it with `{hermes} import <backup.zip>`.")+ lines += [" Sessions created since the upgrade are not in that copy.", f" Guide: {_DOCS}"]+ return "\n".join(lines)diff --git a/tests/hermes_cli/test_update_downgrade_guard.py b/tests/hermes_cli/test_update_downgrade_guard.pynew file mode 100644index 00000000000..43d82338b39--- /dev/null+++ b/tests/hermes_cli/test_update_downgrade_guard.py@@ -0,0 +1,97 @@+"""`hermes update` refuses a target that predates the gateway runtime once a state.db holds ledger rows.++Downgrading is unsupported (#106742, jquesnelle item 6): the older release cannot delete or prune+the sessions with runtime history, so the move is refused before the tree changes and the message+names the pre-update snapshot that predates the cutover.+"""+import sqlite3+import subprocess+from contextlib import closing++import pytest++import hermes_state_runtime as rt+from hermes_cli import update_downgrade_guard as guard+from hermes_state import SessionDB+++def _git(root, *args):+ return subprocess.run(["git", *args], cwd=root, check=True, capture_output=True, text=True,+ encoding="utf-8").stdout.strip()+++def repo(tmp_path):+ root = tmp_path / "checkout"+ root.mkdir()+ _git(root, "init", "-b", "main")+ _git(root, "config", "user.email", "[email protected]")+ _git(root, "config", "user.name", "T")+ (root / "hermes_state_common.py").write_text("SCHEMA_SQL = 'CREATE TABLE IF NOT EXISTS sessions (id TEXT)'\n")+ _git(root, "add", ".")+ _git(root, "commit", "-m", "release before the cutover")+ _git(root, "tag", "old-release")+ (root / "hermes_state_common.py").write_text(+ "SCHEMA_SQL = '''CREATE TABLE IF NOT EXISTS session_admissions (seq INTEGER)'''\n")+ _git(root, "commit", "-am", "gateway runtime")+ return root+++def _ledgered_store(home):+ home.mkdir(parents=True, exist_ok=True)+ with closing(SessionDB(home / "state.db")) as db:+ epoch = rt.begin_runtime_epoch(db, instance_id="owner")+ db.create_session("s", source="cli")+ rt.admit_session_input(db, epoch=epoch, principal_id="p", session_id="s", request_id="r",+ payload={"text": "x"})+++def _pre_cutover_snapshot(home, snap_id):+ snap = home / "state-snapshots" / snap_id+ snap.mkdir(parents=True)+ with closing(sqlite3.connect(snap / "state.db")) as conn:+ conn.execute("CREATE TABLE sessions (id TEXT PRIMARY KEY)")+++def test_a_pre_runtime_target_is_refused_before_the_move_with_the_snapshot_that_predates_it(+ repo, tmp_path, monkeypatch, capsys):+ from hermes_cli import main as hermes_main+ from hermes_cli import update_cmd++ home = tmp_path / "home"+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr("hermes_cli.backup._sibling_profile_homes", lambda h: [])+ monkeypatch.setattr(update_cmd._commit, "preflight_refusal", lambda *a, **k: None)+ monkeypatch.setattr(hermes_main, "PROJECT_ROOT", repo)+ _ledgered_store(home)+ _pre_cutover_snapshot(home, "20261001-000000-pre-update")+ # A newer snapshot already holding the runtime ledger is not a way back.+ newer = home / "state-snapshots" / "20261008-000000-pre-update"+ newer.mkdir()+ with closing(sqlite3.connect(newer / "state.db")) as conn:+ conn.execute("CREATE TABLE session_admissions (seq INTEGER)")+ head = _git(repo, "rev-parse", "HEAD")++ with pytest.raises(SystemExit) as stopped:+ update_cmd._refuse_before_commit_point(["git"], _git(repo, "rev-parse", "old-release"), None)+ assert stopped.value.code == 1 and _git(repo, "rev-parse", "HEAD") == head+ out = capsys.readouterr().out+ assert "Downgrading is unsupported" in out and str(home / "state.db") in out+ assert "/snapshot restore 20261001-000000-pre-update" in out and "20261008" not in out+ assert "hermes gateway stop" in out and "No update was applied" in out+++def test_forward_updates_and_stores_without_ledger_rows_are_never_refused(repo, tmp_path, monkeypatch):+ monkeypatch.setattr("hermes_cli.backup._sibling_profile_homes", lambda h: [])+ old = _git(repo, "rev-parse", "old-release")+ plain = tmp_path / "plain"+ plain.mkdir()+ SessionDB(plain / "state.db").close() # runtime tables exist, but nothing was ever admitted+ assert guard.downgrade_refusal(["git"], repo, old, home=plain) is None++ ledgered = tmp_path / "ledgered"+ _ledgered_store(ledgered)+ head = _git(repo, "rev-parse", "HEAD")+ assert guard.downgrade_refusal(["git"], repo, head, home=ledgered) is None+ _git(repo, "checkout", "-q", "--detach", old) # running the old release: the newer target is forward+ assert guard.downgrade_refusal(["git"], repo, head, home=ledgered) is Nonediff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 44007537080..e013173fc55 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -506,7 +506,7 @@ they failed. Rows recorded before the change keep their old field set and still| Metric | Dimensions added | Question it answers ||---|---|---|| `hermes.extension.install.count` | failure class, registry | Why skill, plugin and MCP installs fail, and which skills-hub source fails. `failure_class` is `none` on success, else a closed name for the failure exit that stopped the install. Skills: `ambiguous`, `auth_rejected`, `fetch_failed`, `invalid_bundle`, `invalid_name`, `not_found`, `rate_limited`, `scan_blocked`, `stale_index`. Plugins: `already_installed`, `clone_failed`, `deps_declined`, `deps_failed`, `git_missing`, `incompatible`, `invalid_source`, `manifest_invalid`, `non_interactive`, `removed_from_catalog`, `scan_blocked`. MCP servers: `auth_required`, `bootstrap_failed`, `clone_failed`, `config_invalid`, `config_rejected`, `connect_failed`, `git_missing`, `missing_credentials`, `server_start_failed`. Every kind may also read `exception`, `filesystem_error`, `network`, `other`, `permission`. A raised error without a named class is classified by its Python type only (`PermissionError` reads `permission`, connection and timeout errors `network`, other `OSError`s `filesystem_error`, anything else `exception`, its type name dropped). `registry` is set on skill rows only: the skills-hub adapter that resolved or served the skill, one of `browse-sh`, `clawhub`, `github`, `hermes-index`, `lobehub`, `official`, `skills-sh`, `url`, `well-known` (the adapter ids `tools/skills_hub_search.py::create_source_router` builds), `unresolved` when no adapter answered, `none` for built-in restores and every plugin/MCP row, `other` otherwise. A row whose `failure_class` is outside its kind's set, is `none` on a failure or set on a success, or that names a registry on a plugin/MCP row is invalid. Never the identifier, URL, error text or path; `name` keeps its existing catalog-or-`custom` rule. |-| `hermes.update.run` | failure class | Why `hermes update` fails, next to where (`failed_stage`). `none` unless the outcome is `failed`, `refused` or `partial`. Derived from the final update receipt only: `build_failed`, `deps_failed`, `exception`, `fleet_stale`, `fleet_unverified`, `git_failed`, `interrupted`, `lock_held`, `managed_install`, `os_error`, `disk_full`, `permission_denied`, `restart_failed`, `subprocess_failed`, else `other`; Desktop packaged self-updates report `unknown` (their RPC carries a stage, never a reason). An exception that ended the run is read by its type name alone, never its message (a `PermissionError` reads `permission_denied`, an `OSError` whose errno is ENOSPC reads `disk_full`); a failed Windows gateway resume after the update reads `restart_failed`. Every exit that stops a run before its apply stage mark records one closed token at the exit itself, and the run reads it (a few of these, `syntax_rollback`, `stash_restore_rejected`, `unexpected_branch`, `head_moved`, fire after git moved the tree and put it back or left it for the next launch to restore): `fetch_failed`, `git_timeout` (a network git call hit the updater's time limit), `channel_unresolved`, `git_in_progress` (a merge/rebase/... was already running), `git_index_locked`, `merge_conflict` (local commits on a custom branch), `checkout_move_failed`, `branch_missing`, `parked_branch_blocked`, `detached_head`, `unexpected_branch`, `head_moved` (a ref moved mid-update), `target_unresolved`, `target_syntax_error` (refused before the move), `syntax_rollback` (moved, failed the syntax check, rolled back), `commit_point_refused` (the commit point could not be armed; nothing moved), `venv_foreign_owner`, `local_changes_blocked` (local changes git could not stash, or a dirty tree the ZIP fallback will not overwrite), `stash_restore_rejected`, `not_git_checkout`, `old_version_handoff` (an older updater's hand-off could not finish), `branch_unsupported`, `download_failed`, `zip_failed`, `disk_full`, `lock_held`, `managed_install`. `aborted_before_apply` is now only the fallback for such an exit with no recorded token. The update-lock refusal, the Git-operation refusal and the managed-install refusal fire before the run's receipt opens; they still write no receipt (the receipt store belongs to the update holding the lock) and record one row with that token, with `kind` `desktop` when the update marker names this run's Desktop hand-off (as its delegate or its hand-off partner), never merely because another update holds the marker. A git error that ended the checkout move reads `git_index_locked` only when git reports the index lock already exists; git refused permission to write it (or any file) reads `permission_denied`. A token is read only while the run has no apply mark, so a reason can never outlive the exit that recorded it. A run that committed and then was interrupted, or whose stashed local changes could not be re-applied, reads outcome `partial` (`interrupted` / `local_changes_parked`, `failed_stage` `apply` for the latter), never `failed`; owed follow-ups alone keep the run a `success` (contract C3). A run the pre-update interpreter finishes is parked with the token, the exit code, the stop reason's leading exception type (or one of Hermes' two fixed phrases) and the restart/user-action flags (never argv, paths or messages), so it classifies exactly as the same run finished in-process. A failed run whose every stage mark passed now reads `failed_stage` `verify` (the post-restart verification wrote `partial`) or `restart` (a skipped restart left the fleet owing one) instead of `other`; a `partial` run with a failed build or restart mark keeps that stage, and its verify stage row is failed only when the fleet has a stale or down row. |+| `hermes.update.run` | failure class | Why `hermes update` fails, next to where (`failed_stage`). `none` unless the outcome is `failed`, `refused` or `partial`. Derived from the final update receipt only: `build_failed`, `deps_failed`, `exception`, `fleet_stale`, `fleet_unverified`, `git_failed`, `interrupted`, `lock_held`, `managed_install`, `os_error`, `disk_full`, `permission_denied`, `restart_failed`, `subprocess_failed`, else `other`; Desktop packaged self-updates report `unknown` (their RPC carries a stage, never a reason). An exception that ended the run is read by its type name alone, never its message (a `PermissionError` reads `permission_denied`, an `OSError` whose errno is ENOSPC reads `disk_full`); a failed Windows gateway resume after the update reads `restart_failed`. Every exit that stops a run before its apply stage mark records one closed token at the exit itself, and the run reads it (a few of these, `syntax_rollback`, `stash_restore_rejected`, `unexpected_branch`, `head_moved`, fire after git moved the tree and put it back or left it for the next launch to restore): `fetch_failed`, `git_timeout` (a network git call hit the updater's time limit), `channel_unresolved`, `git_in_progress` (a merge/rebase/... was already running), `git_index_locked`, `merge_conflict` (local commits on a custom branch), `checkout_move_failed`, `branch_missing`, `parked_branch_blocked`, `detached_head`, `unexpected_branch`, `head_moved` (a ref moved mid-update), `target_unresolved`, `target_syntax_error` (refused before the move), `syntax_rollback` (moved, failed the syntax check, rolled back), `commit_point_refused` (the commit point could not be armed; nothing moved), `downgrade_refused` (the target predates the gateway runtime a profile's `state.db` already holds history for; nothing moved), `venv_foreign_owner`, `local_changes_blocked` (local changes git could not stash, or a dirty tree the ZIP fallback will not overwrite), `stash_restore_rejected`, `not_git_checkout`, `old_version_handoff` (an older updater's hand-off could not finish), `branch_unsupported`, `download_failed`, `zip_failed`, `disk_full`, `lock_held`, `managed_install`. `aborted_before_apply` is now only the fallback for such an exit with no recorded token. The update-lock refusal, the Git-operation refusal and the managed-install refusal fire before the run's receipt opens; they still write no receipt (the receipt store belongs to the update holding the lock) and record one row with that token, with `kind` `desktop` when the update marker names this run's Desktop hand-off (as its delegate or its hand-off partner), never merely because another update holds the marker. A git error that ended the checkout move reads `git_index_locked` only when git reports the index lock already exists; git refused permission to write it (or any file) reads `permission_denied`. A token is read only while the run has no apply mark, so a reason can never outlive the exit that recorded it. A run that committed and then was interrupted, or whose stashed local changes could not be re-applied, reads outcome `partial` (`interrupted` / `local_changes_parked`, `failed_stage` `apply` for the latter), never `failed`; owed follow-ups alone keep the run a `success` (contract C3). A run the pre-update interpreter finishes is parked with the token, the exit code, the stop reason's leading exception type (or one of Hermes' two fixed phrases) and the restart/user-action flags (never argv, paths or messages), so it classifies exactly as the same run finished in-process. A failed run whose every stage mark passed now reads `failed_stage` `verify` (the post-restart verification wrote `partial`) or `restart` (a skipped restart left the fleet owing one) instead of `other`; a `partial` run with a failed build or restart mark keeps that stage, and its verify stage row is failed only when the fleet has a stale or down row. |<!-- ---- end iuf c1 ---- --><!-- ---- iuf c2 ---- -->#### Fresh installs