Skip to content

The agent that grows with you

fix(migrate): rollback refuses a malformed manifest before mutating; plan and run agree

kshitijk4poor422bc9bde9d2
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.py
index a40c5ba538a..77d5465fc8b 100644
--- a/hermes_cli/gateway_migrate.py
+++ b/hermes_cli/gateway_migrate.py
@@ -461,25 +461,48 @@ def _plan_tail(plan: MigrationPlan) -> list[str]:
return lines
+def _no_manifest_lines(default_home: Path) -> list[str]:
+ return [f"✗ No migration manifest at {_manifest_path(default_home)}; nothing to roll back.",
+ " To leave multiplex mode by hand: hermes config set gateway.multiplex_profiles false && hermes gateway restart"]
+
+
+def _manifest_secondaries(manifest: dict) -> Optional[list[dict]]:
+ """The manifest's secondary records, or None when the (hand-edited) manifest is malformed."""
+ recs = manifest.get("secondaries", [])
+ if not isinstance(recs, list) or not all(isinstance(r, dict) and r.get("profile") and r.get("home") for r in recs):
+ return None
+ return recs
+
+
+def _secondary_service(rec: dict) -> Optional[tuple[str, bool]]:
+ service = rec.get("service")
+ if isinstance(service, dict) and service.get("kind"):
+ return str(service["kind"]), bool(service.get("system"))
+ return None
+
+
+_NOTHING_RECORDED = "no gateway was recorded; nothing to restore"
+
+
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")
lines.append(" - default: clear multiplex-owned runtime status")
- 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"
+ secondaries = _manifest_secondaries(manifest)
+ if secondaries is None:
+ return lines + [f" ✗ malformed secondary records in {_manifest_path(default_home)}; fix or delete the manifest"]
+ for rec in secondaries:
+ service = _secondary_service(rec)
+ if service is not None:
+ action = f"reinstall and start its {service[0]} service"
elif rec.get("pid"):
action = "start its standalone gateway (detached)"
else:
- action = "restore its recorded standalone gateway"
- lines.append(f" - {name}: {action}")
+ action = _NOTHING_RECORDED
+ lines.append(f" - {rec['profile']}: {action}")
lines += [
- f" - remove rollback manifest {default_home / MANIFEST_NAME}",
+ f" - remove rollback manifest {_manifest_path(default_home)}",
" - default: restart the standalone gateway last",
]
return lines
@@ -531,10 +554,10 @@ def _reconcile_standalone_runtime(default_home: Path, secondary_names: set[str])
runtime["served_profiles"] = []
platforms = runtime.get("platforms")
if isinstance(platforms, dict):
- prefixes = tuple(f"{name}:" for name in secondary_names)
+ prefixes = tuple(f"{name}:" for name in secondary_names if name)
runtime["platforms"] = {
key: value for key, value in platforms.items()
- if not (isinstance(key, str) and prefixes and key.startswith(prefixes))
+ if not (isinstance(key, str) and key.startswith(prefixes))
}
atomic_json_write(path, runtime, indent=None, separators=(",", ":"))
@@ -622,59 +645,60 @@ def rollback_migration(default_home: Optional[Path] = None) -> bool:
default_home = default_home or _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.")
- print(" To leave multiplex mode by hand: hermes config set gateway.multiplex_profiles false && hermes gateway restart")
+ _print(_no_manifest_lines(default_home))
+ return False
+ incomplete = f"⚠ Rollback incomplete; manifest kept at {_manifest_path(default_home)}."
+ secondaries = _manifest_secondaries(manifest)
+ if secondaries is None:
+ # Refuse before touching anything: a hand-edited manifest is not a rollback authority.
+ print(f"✗ Malformed secondary records in {_manifest_path(default_home)}; fix or delete the manifest.")
return False
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)}.")
+ print(incomplete)
return False
- default_rec = manifest.get("default") or {}
- default_service = default_rec.get("service")
+ default_rec = manifest.get("default")
+ default_service = _secondary_service(default_rec) if isinstance(default_rec, dict) else None
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),
+ service=default_service or _installed_service(default_home),
)
- secondaries = [rec for rec in manifest.get("secondaries", []) if isinstance(rec, dict)]
- ok = len(secondaries) == len(manifest.get("secondaries", []))
- if not ok:
- print(" ✗ invalid secondary record in migration manifest")
# The live multiplexer's record still claims every secondary; a per-profile gateway started
# while it does is refused (exit 78, parked by RestartPreventExitStatus) — clear it FIRST.
try:
- _reconcile_standalone_runtime(default_home, {str(rec.get("profile") or "") for rec in secondaries})
+ _reconcile_standalone_runtime(default_home, {str(rec["profile"]) for rec in secondaries})
print(" ✓ default: cleared multiplex-owned runtime status")
except Exception as exc:
print(f" ✗ default: could not clear multiplex-owned runtime status ({exc})")
- print(f"⚠ Rollback incomplete; manifest kept at {_manifest_path(default_home)}.")
+ print(incomplete)
return False
+ ok = True
for rec in secondaries:
- name = str(rec.get("profile") or "")
+ name, home = str(rec["profile"]), Path(str(rec["home"]))
try:
- home = Path(rec["home"])
- if not name:
- raise ValueError("missing profile name")
- service = rec.get("service")
- if service:
- kind, system = service["kind"], bool(service.get("system"))
+ service = _secondary_service(rec)
+ if service is not None:
+ kind, system = service
_service_op(kind, system, "install", home)
_service_op(kind, system, "start", home)
print(f" ✓ {name}: reinstalled and started its {kind} service")
- elif rec.get("pid") and _live_gateway_pid(home) is not None:
- print(f" ✓ {name}: standalone gateway already running") # re-run after a partial rollback
elif rec.get("pid"):
- if _spawn_detached_gateway(home):
+ if _live_gateway_pid(home) is not None: # re-run after a partial rollback
+ print(f" ✓ {name}: standalone gateway already running")
+ elif _spawn_detached_gateway(home):
print(f" ✓ {name}: started its standalone gateway (detached)")
else:
ok = False
print(f" ✗ {name}: could not start its standalone gateway")
+ else:
+ print(f" ✓ {name}: {_NOTHING_RECORDED}")
except Exception as exc:
ok = False
- print(f" ✗ {name or '<unknown>'}: {exc}")
+ print(f" ✗ {name}: {exc}")
if ok:
_manifest_path(default_home).unlink(missing_ok=True)
# The flag is already off, so the default must come back standalone even when a secondary
@@ -691,10 +715,11 @@ def rollback_migration(default_home: Optional[Path] = None) -> bool:
print(f" ✗ default: could not restore rollback manifest ({manifest_exc})")
ok = False
print(f" ✗ default: could not restart its standalone gateway ({exc})")
+ print(" The default gateway is still multiplexing; stop it by hand (hermes gateway stop) and re-run.")
if ok:
print("✓ Rolled back to per-profile gateways.")
else:
- print(f"⚠ Rollback incomplete; manifest kept at {_manifest_path(default_home)}.")
+ print(incomplete)
return ok
@@ -718,8 +743,8 @@ def cmd_migrate(args) -> None:
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(_no_manifest_lines(default_home))
+ sys.exit(1)
_print(format_rollback_plan(default_home, manifest, dry_run=True))
return
sys.exit(0 if rollback_migration() else 1)
diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.py
index 090fbafcf2e..7d1c27a75f9 100644
--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py
+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py
@@ -176,6 +176,30 @@ def test_rollback_rerun_does_not_respawn_a_running_detached_secondary(fleet, mon
assert spawned == ["ops"]
+def test_malformed_manifest_is_refused_before_any_mutation(fleet, capsys):
+ (fleet.root / gm.MANIFEST_NAME).write_text(
+ json.dumps({"version": 1, "flag_was": False, "default": [], "secondaries": [{"home": "x"}]}), encoding="utf-8")
+ assert gm.rollback_migration(fleet.root) is False
+ assert _config_flag(fleet.root) is None and fleet.ops == []
+ assert "fix or delete the manifest" in capsys.readouterr().out
+ gm.cmd_migrate(SimpleNamespace(multiplex=False, standalone=True, dry_run=True, yes=True))
+ assert "fix or delete the manifest" in capsys.readouterr().out
+
+
+def test_rollback_plan_and_execution_agree_on_a_secondary_with_nothing_recorded(fleet, capsys):
+ gm._write_manifest(fleet.root, {"version": 1, "flag_was": False, "default": {"service": None}, "secondaries": [
+ {"profile": "coder", "home": str(fleet.root / "profiles/coder"), "pid": None, "service": None}]})
+ fleet.services.clear()
+ fleet.pids.clear()
+ plan = "\n".join(gm.format_rollback_plan(fleet.root, gm._read_manifest(fleet.root), dry_run=True))
+ assert gm.rollback_migration(fleet.root) is True
+ out = capsys.readouterr().out
+ # The plan must not promise an action the run never performs: both name the same outcome.
+ plan_line = next(line.split("coder: ", 1)[1] for line in plan.splitlines() if "coder: " in line)
+ assert plan_line in out and "restore" not in plan_line.split(";")[0]
+ assert fleet.ops == []
+
+
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()