The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): make standalone rollback recoverable
KoNit-K043286ae68ff
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.pyindex fa0b8318933..989387ef1ef 100644--- a/hermes_cli/gateway_migrate.py+++ b/hermes_cli/gateway_migrate.py@@ -461,6 +461,30 @@ def _plan_tail(plan: MigrationPlan) -> list[str]:return lines+def format_rollback_plan(default_home: Path, manifest: dict, *, dry_run: bool) -> list[str]:+ head = "Rollback plan (dry run — nothing changed)" if dry_run else "Rollback plan"+ lines = [head, f" default home: {default_home}", "", " Steps:"]+ lines.append(" - default: restore gateway.multiplex_profiles to its pre-migration value")+ for rec in manifest.get("secondaries", []):+ if not isinstance(rec, dict):+ continue+ name = str(rec.get("profile") or "<unknown>")+ service = rec.get("service")+ if isinstance(service, dict) and service.get("kind"):+ action = f"reinstall and start its {service['kind']} service"+ elif rec.get("pid"):+ action = "start its standalone gateway (detached)"+ else:+ action = "restore its recorded standalone gateway"+ lines.append(f" - {name}: {action}")+ lines += [+ " - default: clear multiplex-owned runtime status",+ f" - remove rollback manifest {default_home / MANIFEST_NAME}",+ " - default: restart the standalone gateway last",+ ]+ return lines++def format_update_warning(plan: MigrationPlan) -> list[str]:return ["⚠ Your profiles each run their own gateway. A single multiplexed gateway is the recommended",@@ -490,7 +514,29 @@ def _read_manifest(default_home: Path) -> Optional[dict]:def _write_manifest(default_home: Path, data: dict) -> None:- _manifest_path(default_home).write_text(json.dumps(data, indent=2), encoding="utf-8")+ from utils import atomic_json_write++ atomic_json_write(_manifest_path(default_home), data)+++def _reconcile_standalone_runtime(default_home: Path, secondary_names: set[str]) -> None:+ """Remove only status owned by multiplexing, without re-stamping gateway identity."""+ from gateway.status import read_runtime_status+ from utils import atomic_json_write++ path = default_home / "gateway_state.json"+ runtime = read_runtime_status(path)+ if runtime is None:+ return+ runtime["served_profiles"] = []+ platforms = runtime.get("platforms")+ if isinstance(platforms, dict):+ prefixes = tuple(f"{name}:" for name in secondary_names)+ runtime["platforms"] = {+ key: value for key, value in platforms.items()+ if not (isinstance(key, str) and prefixes and key.startswith(prefixes))+ }+ atomic_json_write(path, runtime, indent=None, separators=(",", ":"))def _wait_for_served(default_home: Path, expected: set[str], timeout: float) -> Optional[list[str]]:@@ -579,21 +625,33 @@ def rollback_migration(default_home: Optional[Path] = None) -> bool:print(f"✗ No migration manifest at {_manifest_path(default_home)}; nothing to roll back.")print(" To leave multiplex mode by hand: hermes config set gateway.multiplex_profiles false && hermes gateway restart")return False- _write_multiplex_flag(default_home, bool(manifest.get("flag_was", False)))- print(" ✓ default: gateway.multiplex_profiles restored")+ try:+ _write_multiplex_flag(default_home, bool(manifest.get("flag_was", False)))+ print(" ✓ default: gateway.multiplex_profiles restored")+ except Exception as exc:+ print(f" ✗ default: could not restore gateway.multiplex_profiles ({exc})")+ print(f"⚠ Rollback incomplete; manifest kept at {_manifest_path(default_home)}.")+ return False+default_rec = manifest.get("default") or {}default_service = default_rec.get("service")default_gw = ProfileGateway("default", default_home, pid=_live_gateway_pid(default_home),service=(default_service["kind"], bool(default_service.get("system"))) if default_service else _installed_service(default_home),)- if default_gw.has_gateway:- print(f" ✓ {_restart_default(default_gw, None, default_home)}")ok = True+ secondary_names: set[str] = set()for rec in manifest.get("secondaries", []):- home = Path(rec["home"])- name = rec["profile"]+ if not isinstance(rec, dict):+ ok = False+ print(" ✗ invalid secondary record in migration manifest")+ continue+ name = str(rec.get("profile") or "")try:+ home = Path(rec["home"])+ if not name:+ raise ValueError("missing profile name")+ secondary_names.add(name)service = rec.get("service")if service:kind, system = service["kind"], bool(service.get("system"))@@ -608,13 +666,33 @@ def rollback_migration(default_home: Optional[Path] = None) -> bool:print(f" ✗ {name}: could not start its standalone gateway")except Exception as exc:ok = False- print(f" ✗ {name}: {exc}")- if ok:+ print(f" ✗ {name or '<unknown>'}: {exc}")+ if not ok:+ print(f"⚠ Rollback incomplete; manifest kept at {_manifest_path(default_home)}.")+ return False++ try:+ _reconcile_standalone_runtime(default_home, secondary_names)+ print(" ✓ default: cleared multiplex-owned runtime status")_manifest_path(default_home).unlink(missing_ok=True)- print("✓ Rolled back to per-profile gateways.")- else:+ except Exception as exc:+ print(f" ✗ default: could not finish rollback cleanup ({exc})")print(f"⚠ Rollback incomplete; manifest kept at {_manifest_path(default_home)}.")- return ok+ return False++ if default_gw.has_gateway:+ try:+ print(f" ✓ {_restart_default(default_gw, None, default_home)}")+ except Exception as exc:+ try:+ _write_manifest(default_home, manifest)+ except Exception as manifest_exc:+ print(f" ✗ default: could not restore rollback manifest ({manifest_exc})")+ print(f" ✗ default: could not restart its standalone gateway ({exc})")+ print(f"⚠ Rollback incomplete; manifest kept at {_manifest_path(default_home)}.")+ return False+ print("✓ Rolled back to per-profile gateways.")+ return True# --------------------------------------------------------------------------- CLI + update hook@@ -633,6 +711,14 @@ def _host_supports_migration() -> Optional[str]:def cmd_migrate(args) -> None:"""``hermes gateway migrate [--multiplex|--standalone] [--dry-run] [--yes]``."""if getattr(args, "standalone", False):+ if getattr(args, "dry_run", False):+ default_home = _default_home()+ manifest = _read_manifest(default_home)+ if manifest is None:+ print(f"✗ No migration manifest at {_manifest_path(default_home)}; nothing to roll back.")+ return+ _print(format_rollback_plan(default_home, manifest, dry_run=True))+ returnsys.exit(0 if rollback_migration() else 1)reason = _host_supports_migration()if reason:diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.pyindex 34cdef338fa..b9de6edaa94 100644--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py@@ -52,12 +52,15 @@ def fleet(tmp_path, monkeypatch):elif verb == "install":state.services[name] = (kind, system)elif verb in ("start", "restart") and name == "default":- # What the real multiplexer does at startup: record the served set in the default home.(root / "gateway.pid").write_text(json.dumps({"pid": os.getpid(), "hermes_home": str(root)}))- (root / "gateway_state.json").write_text(json.dumps({- "pid": os.getpid(), "hermes_home": str(root), "gateway_state": "running",- "served_profiles": ["default", "coder", "ops"],- }))+ runtime_path = root / "gateway_state.json"+ runtime = json.loads(runtime_path.read_text()) if runtime_path.exists() else {}+ runtime.update({"pid": os.getpid(), "hermes_home": str(root), "gateway_state": "running"})+ # Multiplex startup records ownership; standalone startup historically preserved the+ # old key, which is the stale-state half of #109473's rollback failure.+ if _config_flag(root):+ runtime["served_profiles"] = ["default", "coder", "ops"]+ runtime_path.write_text(json.dumps(runtime))monkeypatch.setattr(gm, "_installed_service", lambda home: state.services.get(_name(home)))monkeypatch.setattr(gm, "_live_gateway_pid", lambda home: state.pids.get(_name(home)))@@ -110,15 +113,52 @@ def test_apply_records_manifest_flips_flag_and_rollback_restores(fleet, capsys):again = gm.build_migration_plan()assert again.already_multiplexed and gm.apply_migration(again) is True+ runtime_path = fleet.root / "gateway_state.json"+ runtime = json.loads(runtime_path.read_text(encoding="utf-8"))+ runtime["platforms"] = {+ "telegram": {"state": "connected"},+ "coder:telegram": {"state": "connected"},+ "ops:discord": {"state": "connected"},+ }+ runtime_path.write_text(json.dumps(runtime), encoding="utf-8")fleet.ops.clear()assert gm.rollback_migration(fleet.root) is Trueassert _config_flag(fleet.root) is Falseassert fleet.services == {"default": ("systemd", False), "coder": ("systemd", False), "ops": ("systemd", False)}assert [op for op in fleet.ops if op[0] != "default"] == [("coder", "install"), ("coder", "start"), ("ops", "install"), ("ops", "start")]+ assert fleet.ops[-1] == ("default", "restart")+ runtime = json.loads(runtime_path.read_text(encoding="utf-8"))+ assert runtime["served_profiles"] == []+ assert runtime["platforms"] == {"telegram": {"state": "connected"}}+ from hermes_cli.gateway import named_profile_served_by_running_multiplexer+ assert named_profile_served_by_running_multiplexer("coder") is Falseassert not (fleet.root / gm.MANIFEST_NAME).exists()+def test_standalone_dry_run_prints_rollback_plan_without_mutation(fleet, capsys):+ assert gm.apply_migration(gm.build_migration_plan(), served_wait=5.0) is True+ capsys.readouterr()+ fleet.ops.clear()+ before = {+ path: path.read_bytes()+ for path in (+ fleet.root / "config.yaml",+ fleet.root / gm.MANIFEST_NAME,+ fleet.root / "gateway_state.json",+ )+ }+ services_before = dict(fleet.services)+ pids_before = dict(fleet.pids)++ gm.cmd_migrate(SimpleNamespace(multiplex=False, standalone=True, dry_run=True, yes=True))++ out = capsys.readouterr().out+ assert "Rollback plan (dry run" in out and "coder" in out and "ops" in out+ assert all(path.read_bytes() == contents for path, contents in before.items())+ assert fleet.services == services_before and fleet.pids == pids_before and fleet.ops == []++def test_secondary_port_binder_is_notice_with_ingress_and_blocker_without(fleet, monkeypatch):"""The verdict follows the adapter's ``serves_profile_prefix`` declaration, not a hardcoded list."""(fleet.root / "profiles/ops/.env").write_text(