profiles_honcho.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """Honcho host-block migration for ``hermes profile rename``.
  2. Split out of ``hermes_cli.profiles``; the profiles root is late-imported from there so its
  3. ``_get_default_hermes_home`` seam holds.
  4. """
  5. import json
  6. from pathlib import Path
  7. def _atomic_write_json(path: Path, data: dict) -> bool:
  8. """Atomic rewrite of a third-party JSON config; False on OSError (nothing partially written)."""
  9. from utils import atomic_json_write
  10. try:
  11. atomic_json_write(path, data)
  12. return True
  13. except OSError:
  14. return False
  15. def migrate_honcho_profile_host(old_name: str, new_name: str, new_dir: Path) -> None:
  16. """Rename Honcho host blocks for a renamed profile without changing peers."""
  17. from hermes_cli.profiles import _get_default_hermes_home
  18. old_host = f"hermes_{old_name}"
  19. legacy_old_host = f"hermes.{old_name}"
  20. new_host = f"hermes_{new_name}"
  21. candidates = [
  22. new_dir / "honcho.json", _get_default_hermes_home() / "honcho.json", Path.home() / ".honcho" / "config.json"
  23. ]
  24. seen: set[Path] = set()
  25. for path in candidates:
  26. try:
  27. resolved = path.resolve()
  28. except OSError:
  29. resolved = path
  30. if resolved in seen or not path.is_file():
  31. continue
  32. seen.add(resolved)
  33. try:
  34. raw = json.loads(path.read_text(encoding="utf-8-sig"))
  35. except (OSError, json.JSONDecodeError):
  36. continue
  37. hosts = raw.get("hosts")
  38. if not isinstance(hosts, dict):
  39. continue
  40. source_host = old_host if old_host in hosts else legacy_old_host
  41. if source_host not in hosts:
  42. continue
  43. if new_host in hosts:
  44. print(f"⚠ Honcho host block not migrated: {new_host} already exists in {path}")
  45. continue
  46. block = hosts[source_host]
  47. if isinstance(block, dict) and "aiPeer" not in block:
  48. block["aiPeer"] = old_name # source_host is ``hermes_<old>`` or legacy ``hermes.<old>``
  49. hosts[new_host] = hosts.pop(source_host)
  50. if _atomic_write_json(path, raw):
  51. print(f"✓ Honcho host updated: {source_host} → {new_host}")