tui_worktree_resume.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. """Bring back a ``hermes --tui -w`` worktree a resume needs (N8).
  2. Quitting a clean, idle ``--tui -w`` session removes its tree and branch, but the session's policy
  3. froze that cwd, and the owner refuses every turn in a missing directory (``workspace_unavailable``).
  4. So the launcher records each tree it creates in the profile's ``tui_worktrees.json``, and a resume
  5. whose session cwd is such a missing tree recreates it at the same path before attaching: from its
  6. branch when that still exists, else a new branch of the same name from the repo's current HEAD.
  7. Only a path this profile's launcher recorded, directly under its repo's ``.worktrees/``, is ever
  8. created; any other missing directory is left alone (the resume warns as before).
  9. """
  10. from __future__ import annotations
  11. import logging
  12. import os
  13. import subprocess
  14. import threading
  15. from pathlib import Path
  16. from typing import Optional
  17. logger = logging.getLogger(__name__)
  18. _RECORD_NAME = "tui_worktrees.json"
  19. _MAX_RECORDS = 500
  20. _holder = threading.local()
  21. def _record_path() -> Path:
  22. from hermes_constants import get_hermes_home
  23. return get_hermes_home() / _RECORD_NAME
  24. def _key(path) -> str:
  25. return os.path.normcase(os.path.realpath(str(path)))
  26. def _read() -> dict:
  27. from utils import read_json_or_empty
  28. trees = read_json_or_empty(_record_path()).get("trees")
  29. return trees if isinstance(trees, dict) else {}
  30. def record_tui_worktree(wt_info: dict) -> None:
  31. """Remember a tree the ``-w`` / ``--tui -w`` launcher created, or a classic ``/worktree new``
  32. moved its gateway session into. Never raises."""
  33. try:
  34. from hermes_cli.auth import _file_lock
  35. from utils import atomic_json_write
  36. path = _record_path()
  37. with _file_lock(path.with_name(path.name + ".lock"), _holder, 5.0,
  38. "Timed out waiting for the TUI worktree record lock"):
  39. trees = {k: v for k, v in _read().items()
  40. if isinstance(v, dict) and (Path(str(v.get("repo_root") or "")) / ".git").exists()}
  41. trees[_key(wt_info["path"])] = {"path": str(wt_info["path"]), "branch": wt_info["branch"],
  42. "repo_root": str(wt_info["repo_root"])}
  43. atomic_json_write(path, {"version": 1, "trees": dict(list(trees.items())[-_MAX_RECORDS:])})
  44. except Exception: # health: allow BLE001 -- a lost record only means no recreate on resume
  45. logger.debug("TUI worktree record failed for %s", wt_info.get("path"), exc_info=True)
  46. def _recorded_tree_for(cwd: str) -> Optional[dict]:
  47. """The launcher's record of the missing tree *cwd* is (or is inside), or None."""
  48. try:
  49. trees = _read()
  50. except Exception: # health: allow BLE001 -- unreadable record: create nothing
  51. return None
  52. probe = Path(cwd)
  53. for candidate in (probe, *probe.parents):
  54. entry = trees.get(_key(candidate))
  55. if not isinstance(entry, dict):
  56. continue
  57. repo = Path(str(entry.get("repo_root") or ""))
  58. tree = Path(str(entry.get("path") or ""))
  59. branch = str(entry.get("branch") or "")
  60. # Only a direct child of the repo's Hermes worktree dir, as _setup_worktree makes them.
  61. if (branch and (repo / ".git").exists()
  62. and _key(tree.parent) == _key(repo / ".worktrees") and _key(tree) == _key(candidate)):
  63. return {"path": str(tree), "branch": branch, "repo_root": str(repo)}
  64. return None
  65. return None
  66. def _branch_exists(repo_root: str, branch: str) -> bool:
  67. from hermes_cli.worktree_ops import _git
  68. result = _git(["rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], repo_root)
  69. return result.returncode == 0
  70. def recreate_tui_worktree(cwd: str, session_id: str) -> Optional[str]:
  71. """Recreate the launcher-made tree a resumed session's missing *cwd* names -> its path, or None.
  72. Reuses the branch when it survived (its commits come back), else makes it again from the repo's
  73. current HEAD. The tree is locked for the session so the stale-tree prune keeps it. Never raises.
  74. """
  75. if not cwd or os.path.isdir(cwd):
  76. return None
  77. entry = _recorded_tree_for(cwd)
  78. if entry is None:
  79. return None
  80. from hermes_cli._subprocess_compat import noninteractive_repo_git_env
  81. from hermes_cli.worktree_ops import (
  82. _copy_worktree_includes,
  83. _git,
  84. _git_quiet,
  85. _retain_worktree_for_session,
  86. )
  87. from hermes_constants import get_hermes_home
  88. repo_root, tree, branch = entry["repo_root"], Path(entry["path"]), entry["branch"]
  89. if tree.exists(): # a file, or a dir that appeared since: never overwrite it
  90. return None
  91. env = noninteractive_repo_git_env(repo_root)
  92. if env is None:
  93. return None
  94. try:
  95. # A tree deleted by hand leaves its admin entry; drop it so the path can be added again.
  96. _git_quiet(["worktree", "prune"], repo_root, timeout=15, stdin=subprocess.DEVNULL, env=env)
  97. tree.parent.mkdir(parents=True, exist_ok=True)
  98. args = ([str(tree), branch] if _branch_exists(repo_root, branch)
  99. else [str(tree), "-b", branch, "HEAD"])
  100. result = _git(["worktree", "add", *args], repo_root, timeout=120, stdin=subprocess.DEVNULL, env=env)
  101. if result.returncode != 0:
  102. logger.warning("could not recreate worktree %s: %s", tree, result.stderr.strip())
  103. return None
  104. _copy_worktree_includes(repo_root, tree)
  105. _retain_worktree_for_session(repo_root, str(tree), session_id, get_hermes_home() / "state.db")
  106. except (OSError, subprocess.SubprocessError) as exc:
  107. logger.warning("could not recreate worktree %s: %s", tree, exc)
  108. return None
  109. return str(tree)