worktree_registry.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Per-profile registry of every repository Hermes has created a worktree in.
  2. The 6-hourly cron sweep (``cron.scheduler._worktree_maintenance_repos``) only knew the Hermes
  3. checkout and cron job workdirs, so trees made by ``hermes -w`` / ``/worktree new`` / subagent
  4. isolation / the Desktop git pane in any other repo were never swept. Each creation path records
  5. its repo here; the sweep unions this list with its other sources.
  6. The file lives under the ACTIVE profile's home (``get_hermes_home()``), so one profile's sweep
  7. never visits another profile's repos. Writes are atomic under a cross-process lock; entries whose
  8. repo no longer exists are dropped on every read-modify-write and filtered on read.
  9. """
  10. from __future__ import annotations
  11. import logging
  12. import os
  13. import threading
  14. from pathlib import Path
  15. logger = logging.getLogger(__name__)
  16. _REGISTRY_NAME = "worktree_repos.json"
  17. _holder = threading.local()
  18. def registry_path() -> Path:
  19. from hermes_constants import get_hermes_home
  20. return get_hermes_home() / _REGISTRY_NAME
  21. def _repo_exists(repo: str) -> bool:
  22. return (Path(repo) / ".git").exists()
  23. def _read(path: Path) -> list[str]:
  24. from utils import read_json_or_empty
  25. repos = read_json_or_empty(path).get("repos")
  26. return [r for r in repos if isinstance(r, str) and r] if isinstance(repos, list) else []
  27. def registered_repos() -> list[str]:
  28. """Registered repo roots that still exist (read-only; never creates the file)."""
  29. try:
  30. return [r for r in _read(registry_path()) if _repo_exists(r)]
  31. except Exception:
  32. logger.debug("worktree registry read failed", exc_info=True)
  33. return []
  34. def record_worktree_repo(repo_root) -> None:
  35. """Remember *repo_root* as a repo with Hermes-made worktrees. Never raises."""
  36. if not repo_root:
  37. return
  38. try:
  39. from hermes_cli.auth import _file_lock
  40. from utils import atomic_json_write
  41. repo = os.path.realpath(str(repo_root))
  42. path = registry_path()
  43. with _file_lock(path.with_name(path.name + ".lock"), _holder, 5.0,
  44. "Timed out waiting for the worktree registry lock"):
  45. current = _read(path)
  46. kept = [r for r in dict.fromkeys(current) if _repo_exists(r)]
  47. if repo in kept and kept == current:
  48. return
  49. if repo not in kept:
  50. kept.append(repo)
  51. atomic_json_write(path, {"version": 1, "repos": kept})
  52. except Exception:
  53. logger.debug("worktree registry update failed for %s", repo_root, exc_info=True)