subagent_worktree.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. """Opt-in git worktree isolation for delegated subagents (``delegation.worktree_isolation``).
  2. Git-only (outside a repo children share the parent's cwd); local terminal backend only (on
  3. docker/ssh/modal the host worktree is invisible in the sandbox, so isolation is skipped). One
  4. worktree per child under ``<repo>/.worktrees/subagent-<id>``, branch ``hermes-subagent/<id>``.
  5. On finish: zero commits AND clean (both probes ok) -> removed; work left behind -> archived to
  6. ``refs/hermes/archive/<tree>`` then removed (``worktrees.archive_dirty``, branch kept so the parent
  7. can merge it); a failed probe or archive -> kept + flagged.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import os
  12. import subprocess
  13. import uuid
  14. from pathlib import Path
  15. from typing import Any, Dict, Optional
  16. from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_env
  17. logger = logging.getLogger(__name__)
  18. _GIT_TIMEOUT = 30
  19. def _run_git(args, cwd: str, timeout: int = _GIT_TIMEOUT, env=None):
  20. """Run git capturing output; never raises on non-zero exit.
  21. :func:`noninteractive_git_env` (GHSA-7x36-8jrh-v4pw): this runs unattended against whatever
  22. repo the parent sits in and ``worktree add`` runs hooks, so a malicious ``.git/config`` must
  23. not execute.
  24. """
  25. return subprocess.run(["git", *harden_git_argv(args)], cwd=cwd, capture_output=True,
  26. text=True, encoding="utf-8", errors="replace", timeout=timeout,
  27. stdin=subprocess.DEVNULL, env=env or noninteractive_git_env(), check=False)
  28. def local_backend_active() -> bool:
  29. """True when the terminal backend is local (worktrees visible to tools)."""
  30. try:
  31. from hermes_cli.config import load_config_readonly
  32. backend = (load_config_readonly().get("terminal") or {}).get("backend") or "local"
  33. return str(backend).strip().lower() in ("", "local")
  34. except Exception:
  35. # Legacy entry points without the shared loader default to local.
  36. return True
  37. def resolve_repo_root(path: Optional[str]) -> Optional[str]:
  38. """Return the git toplevel for *path*, or None when not in a work tree."""
  39. candidate = os.path.abspath(os.path.expanduser(str(path))) if path else ""
  40. if not candidate or not os.path.isdir(candidate):
  41. return None
  42. try:
  43. result = _run_git(["rev-parse", "--show-toplevel"], cwd=candidate)
  44. except Exception as exc:
  45. logger.debug("subagent worktree: rev-parse failed: %s", exc)
  46. return None
  47. return (result.stdout.strip() or None) if result.returncode == 0 else None
  48. def _ensure_gitignore_entry(repo_root: str) -> None:
  49. """Best-effort: keep ``.worktrees/`` out of git status."""
  50. gitignore = Path(repo_root) / ".gitignore"
  51. try:
  52. existing = gitignore.read_text(encoding="utf-8-sig", errors="replace") if gitignore.exists() else ""
  53. if ".worktrees/" not in existing.splitlines():
  54. with open(gitignore, "a", encoding="utf-8") as f:
  55. sep = "\n" if existing and not existing.endswith("\n") else ""
  56. f.write(f"{sep}.worktrees/\n")
  57. except Exception as exc:
  58. logger.debug("subagent worktree: could not update .gitignore: %s", exc)
  59. def create_subagent_worktree(parent_cwd: Optional[str], subagent_id: Optional[str] = None) -> Optional[dict[str, str]]:
  60. """Create an isolated worktree for one child; None (silent downgrade) outside git/on failure."""
  61. repo_root = resolve_repo_root(parent_cwd)
  62. if not repo_root:
  63. return None
  64. wt_name = f"subagent-{(subagent_id or uuid.uuid4().hex[:8]).replace('/', '-')}"
  65. branch = f"hermes-subagent/{wt_name}"
  66. wt_path = Path(repo_root) / ".worktrees" / wt_name
  67. try:
  68. wt_path.parent.mkdir(parents=True, exist_ok=True)
  69. _ensure_gitignore_entry(repo_root)
  70. base = _run_git(["rev-parse", "HEAD"], cwd=repo_root)
  71. base_commit = base.stdout.strip() if base.returncode == 0 else ""
  72. # The checkout runs the repo-named smudge filter; skip isolation when it cannot be neutralized.
  73. from hermes_cli._subprocess_compat import noninteractive_repo_git_env
  74. add_env = noninteractive_repo_git_env(repo_root)
  75. if add_env is None:
  76. logger.warning("subagent worktree: filter discovery failed; not creating a worktree")
  77. return None
  78. result = _run_git(["worktree", "add", str(wt_path), "-b", branch, "HEAD"], cwd=repo_root, env=add_env)
  79. except Exception as exc:
  80. logger.warning("subagent worktree: creation failed: %s", exc)
  81. return None
  82. if result.returncode != 0:
  83. # Common on repos with zero commits (unborn HEAD) — degrade silently.
  84. logger.warning("subagent worktree: git worktree add failed: %s", result.stderr.strip())
  85. return None
  86. logger.info("subagent worktree created: %s (branch %s)", wt_path, branch)
  87. from hermes_cli.worktree_registry import record_worktree_repo
  88. record_worktree_repo(repo_root)
  89. return {"path": str(wt_path), "branch": branch, "repo_root": repo_root, "base_commit": base_commit}
  90. def _base_payload(info: dict[str, str]) -> dict[str, Any]:
  91. """Result-entry schema the parent expects (no creation-side internals)."""
  92. return {"path": info.get("path", ""), "branch": info.get("branch", ""),
  93. "commits": 0, "dirty": False, "pruned": False}
  94. def mark_worktree_payload_unproven(payload: dict[str, Any], reason: str, *,
  95. unmeasured: str = "commits/dirty") -> dict[str, Any]:
  96. """Flag a worktree result payload as un-inspected, in place.
  97. The parent only sees this dict, so the uncertainty must travel in it or "0 commits, clean"
  98. reads as "the child produced nothing". *unmeasured* names only the fields actually left
  99. unproven (one probe can succeed while the other fails).
  100. See #88113.
  101. """
  102. path, branch = payload.get("path", ""), payload.get("branch", "")
  103. payload["inspection_failed"] = True
  104. payload["note"] = (f"git inspection failed ({reason}): {unmeasured} UNKNOWN — not proven "
  105. f"zero/clean. The worktree and branch were preserved — inspect {path} "
  106. f"(branch {branch}) before assuming no work.")
  107. logger.warning("subagent worktree: git inspection failed (%s) — keeping %s (branch %s) "
  108. "for manual review", reason, path, branch)
  109. return payload
  110. def unproven_worktree_payload(info: dict[str, str], reason: str) -> dict[str, Any]:
  111. """Complete un-inspected payload for ``delegate_tool`` when finalize raises."""
  112. return mark_worktree_payload_unproven(_base_payload(info), reason)
  113. def finalize_subagent_worktree(info: dict[str, str], *, prune: bool = True) -> dict[str, Any]:
  114. """Inspect (and possibly prune) a child worktree after the child finishes.
  115. Prunes only when *prune*, commits==0, clean tree AND both git probes succeeded; otherwise
  116. keeps it with ``inspection_failed`` + ``note`` (``commits``/``dirty`` then are defaults).
  117. """
  118. path, branch = info.get("path", ""), info.get("branch", "")
  119. base_commit = info.get("base_commit", "")
  120. payload = _base_payload(info)
  121. if not path or not os.path.isdir(path):
  122. payload["pruned"] = True # nothing on disk to review
  123. return payload
  124. # Without a base commit the count is an unproven default, and the prune
  125. # condition reads payload["commits"] — so it must not prune either.
  126. # See #88113.
  127. if not base_commit:
  128. return mark_worktree_payload_unproven(
  129. payload, "no base_commit recorded — commit count unmeasurable", unmeasured="commits")
  130. # The status probe re-hashes files the child touched, which runs repo-named clean filters.
  131. from hermes_cli._subprocess_compat import noninteractive_repo_git_env
  132. probe_env = noninteractive_repo_git_env(path)
  133. if probe_env is None:
  134. return mark_worktree_payload_unproven(payload, "filter discovery failed", unmeasured="dirty")
  135. failed, unmeasured = [], []
  136. probes = (("commits", "rev-list", ["rev-list", "--count", f"{base_commit}..HEAD"],
  137. lambda s: int(s or 0)),
  138. ("dirty", "status", ["status", "--porcelain", "--untracked-files=normal"], bool))
  139. try:
  140. for field, label, args, parse in probes:
  141. res = _run_git(args, cwd=path, env=probe_env)
  142. if res.returncode == 0:
  143. payload[field] = parse(res.stdout.strip())
  144. else:
  145. failed.append(f"{label} exit {res.returncode}: {res.stderr.strip()[:200]}")
  146. unmeasured.append(field)
  147. except Exception as exc:
  148. # Timeout, OSError or non-numeric rev-list stdout: which probe raised is
  149. # unknowable, so neither value is trustworthy — keep the worktree.
  150. return mark_worktree_payload_unproven(payload, f"inspection raised: {exc}")
  151. if failed:
  152. # Destructive cleanup requires affirmative proof; defaults prove nothing.
  153. return mark_worktree_payload_unproven(payload, "; ".join(failed), unmeasured="/".join(unmeasured))
  154. if not payload["dirty"]:
  155. # status trusts skip-worktree / assume-unchanged: edits behind them are invisible to it.
  156. from hermes_cli.worktree_archive import ArchiveError
  157. from hermes_cli.worktree_retention import hidden_index_edits
  158. try:
  159. payload["dirty"] = bool(hidden_index_edits(path))
  160. except (ArchiveError, OSError, subprocess.SubprocessError) as exc:
  161. return mark_worktree_payload_unproven(payload, f"index flag probe failed: {exc}", unmeasured="dirty")
  162. if prune and (payload["commits"] or payload["dirty"]):
  163. return _archive_finished_worktree(info, payload)
  164. if prune and payload["commits"] == 0 and not payload["dirty"]:
  165. cwd = info.get("repo_root", "") or path
  166. try:
  167. from hermes_cli.worktree_ops import release_lsp_clients, removal_blocked
  168. blocked = removal_blocked(path) # an embedded repo / private ref dies with the tree
  169. if blocked:
  170. payload["note"] = f"Worktree kept at {path}: {blocked[1]}."
  171. return payload
  172. release_lsp_clients(path) # the child ran in-process: its language servers are ours
  173. removed = _run_git(["worktree", "remove", "--force", path], cwd=cwd)
  174. if removed.returncode == 0:
  175. _run_git(["branch", "-D", branch], cwd=cwd)
  176. payload["pruned"] = True
  177. logger.info("subagent worktree pruned (no work): %s", path)
  178. else:
  179. logger.debug("subagent worktree: prune failed: %s", removed.stderr.strip())
  180. except Exception as exc:
  181. logger.debug("subagent worktree: prune failed: %s", exc)
  182. return payload
  183. def _archive_finished_worktree(info: dict[str, str], payload: dict[str, Any]) -> dict[str, Any]:
  184. """A finished child left commits or edits: snapshot them, then remove the tree.
  185. The branch is kept (the parent reviews and merges it); the archive also covers uncommitted
  186. edits. ``worktrees.archive_dirty: false`` or a failed snapshot keeps the tree as before.
  187. """
  188. from hermes_cli.worktree_archive import ArchiveError
  189. from hermes_cli.worktree_sweep import archive_then_remove, live_process_pids, sweep_settings
  190. settings = sweep_settings()
  191. if not settings["archive_dirty"]:
  192. return payload
  193. path = info.get("path", "")
  194. # A server or watcher the child started may still run in the tree: leave it to the sweep.
  195. if live_process_pids([path], exclude=(os.getpid(),)).get(path):
  196. logger.info("subagent worktree: a live process works in %s; keeping it", path)
  197. return payload
  198. try:
  199. ref, _kept, removed, why = archive_then_remove(
  200. info.get("repo_root", "") or path, path, reason="subagent finished",
  201. max_untracked_mb=settings["archive_max_file_mb"], unlock=False, keep_branch=True,
  202. exclude_pids=(os.getpid(),))
  203. except (ArchiveError, OSError, subprocess.SubprocessError) as exc:
  204. logger.warning("subagent worktree: archive failed, keeping %s: %s", path, exc)
  205. return payload
  206. payload["archive"] = ref
  207. payload["pruned"] = removed
  208. if removed:
  209. payload["note"] = (f"Worktree archived to {ref} and removed; branch {info.get('branch')} kept. "
  210. f"Restore the full tree (including uncommitted edits) with "
  211. f"`hermes worktree restore {ref.rsplit('/', 1)[-1]}`.")
  212. else:
  213. payload["note"] = (f"Worktree archived to {ref} but kept at {path} ({why}); "
  214. f"branch {info.get('branch')} kept.")
  215. return payload
  216. def build_worktree_context_note(info: dict[str, str]) -> str:
  217. """Context block telling the child to work inside its isolated worktree."""
  218. return (
  219. "\n\n[WORKTREE ISOLATION] You are working in an isolated git worktree "
  220. f"at: {info.get('path')}\n"
  221. f"Your dedicated branch is: {info.get('branch')}\n"
  222. "All file edits and shell commands must happen inside this worktree directory (your "
  223. "terminal already starts there). Do NOT cd to the main repository checkout. Commit your "
  224. "changes to your branch when done; the parent agent will review and merge your branch. If "
  225. "you make no commits and leave the tree clean, the worktree is discarded automatically; "
  226. "otherwise it is archived (restorable) and removed when you finish."
  227. )