The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(update): keep one metadata preflight
ethernet1ad0e9f00a21
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex db5ea70034a..cff51b8d69a 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2197,17 +2197,6 @@ def _update_preflight_handled(args) -> bool:managed_error("update Hermes Agent")return True- # Informational flags never enter the updater: --install-id prints the- # identifier and --set-channel atomically persists a valid channel- # record; both exit here, before the update lock, git, network,- # backups, or process pause. Implementation lives in the channel topic- # module, not this file.- if getattr(args, "install_id", False) or getattr(args, "set_channel", None):- from hermes_cli.update_channel import handle_channel_flags-- handle_channel_flags(args)- return True-# --plan is read-only and deployment-kind aware, so it runs BEFORE the# docker/nix/apt refusal gates: on an image/package-managed install the# plan itself reports "not updatable in place" plus the right mechanism.diff --git a/hermes_cli/update_channel.py b/hermes_cli/update_channel.pyindex 948a1ff8d6e..febfa3d2118 100644--- a/hermes_cli/update_channel.py+++ b/hermes_cli/update_channel.py@@ -36,7 +36,6 @@ from hermes_cli.runtime_paths import install_key, installs_rootimport loggingimport osimport re-import sysfrom pathlib import Pathfrom typing import Any, Optional@@ -264,89 +263,6 @@ def _write_channel_record(sha16: str, path: str, channel: str) -> None:atomic_roundtrip_yaml_update(config_path, f"update.installs.{sha16}", new_record)-def _stable_wait_target(canary_version: str) -> str:- """The stable release a canary install waits for: the canary's own base- version (canary is current-stable patch+1; ``v0.28.0`` from- ``v0.28.0-canary.20260818171926``)."""- base = re.sub(r"-canary\.\d+$", "", canary_version.strip())- return base if base.startswith("v") else f"v{base}"---def _stamp_channel_hint(stamp: dict) -> Optional[str]:- """The channel the RUNNING artifact implies, for stamps without a clean- ``tag`` (desktop About-page stamps carry ``displayVersion`` like- ``0.28.0-canary.20260818`` — the ``v`` prefix ``is_canary_tag`` requires- is restored before the shape check, so validation stays with the single- canary authority). Switch text only; resolution stays with- :func:`resolve_update_channel`."""- if stamp.get("updateMechanism") not in ("electron-updater", "app-installer"):- return None- version = str(stamp.get("tag") or stamp.get("displayVersion") or "")- if not version:- return None- candidate = version if version.startswith("v") else f"v{version}"- return CHANNEL_CANARY if is_canary_tag(candidate) else None---def _set_channel_from_cli(channel: str) -> None:- """Persist ``--set-channel`` and print the switch text. Never updates.-- Runs before the update lock, git, network, backups, or process pause:- this is a configuration action, not an update. The reported previous- channel prefers the stored per-install record over what the running- artifact implies.- """- from hermes_cli.config import read_raw_config-- root = _default_root()- stamp = _read_stamp(root)- stored = channel_record(read_raw_config(), root).get("channel")- if isinstance(stored, str) and stored.strip().lower() in VALID_CHANNELS:- previous = stored.strip().lower()- else:- previous = _stamp_channel_hint(stamp) or resolve_update_channel(None, root)- try:- sha16 = set_install_channel(channel, root)- except ValueError as exc:- print(f"error: {exc}")- sys.exit(1)-- print(f"Channel set to '{channel}' (was '{previous}') for install {sha16}.")- version = str(stamp.get("tag") or stamp.get("displayVersion") or "")- if previous == CHANNEL_CANARY and channel == CHANNEL_STABLE:- print(f" You are on canary build {version}.")- print(- f" Stable updates begin at { _stable_wait_target(version) } —"- " canary outversions it until that release ships."- )- print(" Not patient? Switch back: hermes update --set-channel canary")- print(" Docs: https://hermes-agent.nousresearch.com")- elif channel == CHANNEL_CANARY:- print(- " Canary builds are forward-incompatible: a canary install"- " only updates to artifacts that ship after it. Downgrading"- " means reinstalling."- )- sys.exit(0)---def handle_channel_flags(args) -> None:- """Preflight for the informational update flags.-- ``--install-id`` prints this install's id and path; ``--set-channel``- atomically persists a valid channel record. Both terminate the command- here — the caller never reaches the update lock, git, network, backup,- or process-pause paths.- """- if getattr(args, "install_id", False):- root = _default_root()- print(f"{install_id(root)} {root}")- sys.exit(0)- channel = getattr(args, "set_channel", None)- if channel:- _set_channel_from_cli(channel)--def stale_channel_records(config: Optional[dict]) -> list[tuple[str, dict, str]]:"""Doctor's staleness triad over ``update.installs``.diff --git a/tests/hermes_cli/test_update_channel.py b/tests/hermes_cli/test_update_channel.pyindex 997145bd013..fc462a8d6ed 100644--- a/tests/hermes_cli/test_update_channel.py+++ b/tests/hermes_cli/test_update_channel.py@@ -16,7 +16,6 @@ from hermes_cli.update_channel import (CHANNEL_CANARY,CHANNEL_STABLE,default_channel,- handle_channel_flags,install_id,resolve_update_channel,set_install_channel,@@ -311,59 +310,70 @@ class TestSetChannelCLI:shutil.rmtree(home)- def test_stored_record_outranks_running_stamp_in_switch_text(+ def test_metadata_commands_precede_managed_refusal_and_write_once(self, tmp_path, monkeypatch, capsys):- """The reported previous channel comes from the stored per-install- record when one exists — not from what the running artifact implies."""- home = self._home(tmp_path, monkeypatch)- root = tmp_path # == HERMES_INSTALL_ROOT (see sentinel fixture)- (root / "install-stamp.json").write_text(json.dumps({- "schemaVersion": 2,- "updateMechanism": "electron-updater",- "displayVersion": "0.28.0-canary.20260818",- }))import yaml+ import utils+ from hermes_cli import config, main- (home / "config.yaml").write_text(- yaml.safe_dump(- {"update": {"installs": {- install_id(root): {"path": str(root), "channel": "stable"}- }}}- )- )- from types import SimpleNamespace+ home = self._home(tmp_path, monkeypatch)+ monkeypatch.setenv("HERMES_MANAGED", "nix")+ assert config.is_managed()+ root, other = tmp_path, tmp_path / "sibling"+ _stamp(root, "self")+ initial = {"model": {"provider": "fixture"}, **_config_for(other, "stable")}+ cfg = home / "config.yaml"+ cfg.write_text("# retain user comment\n" + yaml.safe_dump(initial), encoding="utf-8")+ before = cfg.read_bytes()- args = SimpleNamespace(- check=False, gateway=False, branch=None, channel=None,- set_channel="canary", install_id=False, plan=False,- )with pytest.raises(SystemExit) as exc:- handle_channel_flags(args)+ main.cmd_update(self._args(install_id=True))assert exc.value.code == 0- assert "Channel set to 'canary' (was 'stable')" in capsys.readouterr().out+ assert capsys.readouterr().out.strip() == install_id(root)+ assert cfg.read_bytes() == before- def test_hint_requires_a_valid_canary_shape(self, tmp_path, monkeypatch, capsys):- """A ``displayVersion`` only reads as canary when it validates as a- canary version shape — 'nightly' builds must not claim the canary- switch text."""- home = self._home(tmp_path, monkeypatch)- root = tmp_path # == HERMES_INSTALL_ROOT (see sentinel fixture)- (root / "install-stamp.json").write_text(json.dumps({- "schemaVersion": 2,- "updateMechanism": "electron-updater",- "displayVersion": "0.28.0-nightly.123",- }))- from types import SimpleNamespace+ writes = []+ original = utils.atomic_roundtrip_yaml_update- args = SimpleNamespace(- check=False, gateway=False, branch=None, channel=None,- set_channel="stable", install_id=False, plan=False,- )+ def write(path, key, value):+ writes.append((path, key))+ return original(path, key, value)++ monkeypatch.setattr(utils, "atomic_roundtrip_yaml_update", write)with pytest.raises(SystemExit) as exc:- handle_channel_flags(args)+ main.cmd_update(self._args(set_channel="canary"))assert exc.value.code == 0- assert "Channel set to 'stable' (was 'stable')" in capsys.readouterr().out+ assert writes == [(cfg, f"update.installs.{install_id(root)}")]+ expected = initial+ expected["update"]["installs"][install_id(root)] = {"path": str(root), "channel": "canary"}+ assert yaml.safe_load(cfg.read_text(encoding="utf-8")) == expected+ assert cfg.read_text(encoding="utf-8").startswith("# retain user comment\n")+ output = capsys.readouterr().out+ assert f"Update channel for {install_id(root)}: canary" in output+ assert "forward-incompatible" in output+ assert not (home / "logs" / "update_receipts").exists()++ def test_metadata_refusals_leave_config_unchanged(self, tmp_path, monkeypatch, capsys):+ from hermes_cli import main++ home = self._home(tmp_path, monkeypatch)+ monkeypatch.setenv("HERMES_MANAGED", "nix")+ cfg = home / "config.yaml"+ before = b"# retain user comment\nmodel:\n provider: fixture\n"+ cfg.write_bytes(before)+ for mechanism, channel, message in (+ ("self", "bogus", "unknown channel"),+ ("external", "stable", "owned by"),+ ("app-installer", "canary", "owned by"),+ ):+ _stamp(tmp_path, mechanism)+ with pytest.raises(SystemExit) as exc:+ main.cmd_update(self._args(set_channel=channel))+ assert exc.value.code == 2+ assert message in capsys.readouterr().out+ assert cfg.read_bytes() == before+ assert not (home / "logs" / "update_receipts").exists()def _args(self, **kw):from types import SimpleNamespace