worktree_cmd.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. """``hermes worktree`` — audit (``list [--json] [--older-than DAYS]``), reclaim
  2. (``prune [--dry-run] [--json] [--older-than DAYS] [--trees-only | --branches-only]``) and
  3. ``restore <name> [--path DIR]`` accumulated git worktrees/branches. ``--json`` output is the only
  4. thing written to stdout in that mode so scripts can consume it."""
  5. from __future__ import annotations
  6. import json
  7. from dataclasses import asdict
  8. from typing import Optional
  9. def _fmt_size(size_mb: Optional[int]) -> str:
  10. if size_mb is None:
  11. return "?"
  12. return f"{size_mb / 1024:.1f}G" if size_mb >= 1024 else f"{size_mb}M"
  13. def _list(worktree_gc, repo_root: str, args) -> int:
  14. older_than = getattr(args, "older_than", None)
  15. records = worktree_gc.audit_worktrees(repo_root, older_than_days=older_than)
  16. external = worktree_gc.audit_external_trees(repo_root)
  17. branch_records = worktree_gc.audit_branches(repo_root)
  18. from hermes_cli.worktree_archive import list_archives
  19. archives = list_archives(repo_root)
  20. if getattr(args, "json", False):
  21. print(json.dumps({
  22. "repo": repo_root,
  23. "trees": [asdict(r) for r in records],
  24. "external_trees": [asdict(r) for r in external],
  25. "branches": [asdict(b) for b in branch_records],
  26. "archives": [asdict(a) for a in archives],
  27. }, indent=2))
  28. return 0
  29. _print_archives(archives)
  30. if not records and not external:
  31. print("No worktrees under .worktrees/ — nothing to reclaim.")
  32. return 0
  33. if records:
  34. total_mb = sum(r.size_mb or 0 for r in records)
  35. reapable_mb = sum(r.size_mb or 0 for r in records if r.verdict.startswith("reap"))
  36. print(f"{'TREE':32} {'AGE':>6} {'SIZE':>6} {'VERDICT':13} REASON")
  37. for r in sorted(records, key=lambda x: -(x.size_mb or 0)):
  38. print(f"{r.name[:32]:32} {r.age_days:>5.1f}d {_fmt_size(r.size_mb):>6} {r.verdict:13} {r.reason}")
  39. print(
  40. f"\n{len(records)} tree(s), {_fmt_size(total_mb)} total — "
  41. f"{_fmt_size(reapable_mb)} reclaimable now via `hermes worktree prune`.")
  42. if external:
  43. print(f"\n{len(external)} externally-registered worktree(s) (never touched by prune):")
  44. for e in external:
  45. state = "MISSING" if e.missing else ("locked" if e.locked else "ok")
  46. print(f" {e.path} [{e.branch or '?'}] {state}")
  47. if any(e.missing and not e.locked for e in external):
  48. print(" Stale registrations (MISSING) are cleaned by `hermes worktree prune` (metadata only).")
  49. deletable = [b for b in branch_records if b.verdict == "delete"]
  50. if deletable:
  51. print(f"{len(deletable)} local branch(es) fully merged/patch-equivalent upstream would also be deleted.")
  52. return 0
  53. def _print_archives(archives) -> None:
  54. if not archives:
  55. return
  56. import time
  57. print(f"{len(archives)} archived worktree(s) (restore with `hermes worktree restore <name>`):")
  58. for a in archives:
  59. age = (time.time() - a.created) / 86400 if a.created else 0
  60. skipped = len(a.meta.get("skipped_untracked") or [])
  61. extra = f", {skipped} large untracked file(s) not captured" if skipped else ""
  62. print(f" {a.name:40} {age:5.1f}d {a.meta.get('branch') or 'detached'} "
  63. f"({a.meta.get('reason') or '?'}{extra})")
  64. print()
  65. def _sweep_lines(plan) -> list[str]:
  66. lines = [f"{'TREE':40} {'IDLE':>7} {'DECISION':20} REASON"]
  67. for d in sorted(plan, key=lambda x: (x.action, x.name)):
  68. lines.append(f"{d.name[:40]:40} {d.age_hours:>6.1f}h {d.action:20} {d.reason}")
  69. counts: dict = {}
  70. for d in plan:
  71. counts[d.action] = counts.get(d.action, 0) + 1
  72. lines.append("Sweep totals: " + (", ".join(f"{k}={v}" for k, v in sorted(counts.items())) or "nothing to do"))
  73. return lines
  74. def _sweep(repo_root: str, dry_run: bool, older_than: Optional[float] = None) -> tuple[list, list[str]]:
  75. """The automatic sweep's plan for this repo (applied unless *dry_run*) -> (plan, actions).
  76. *older_than* (days) bounds what the plan may archive or remove before anything runs."""
  77. from hermes_cli import worktree_sweep
  78. settings = worktree_sweep.sweep_settings()
  79. plan = worktree_sweep.plan_sweep(repo_root, settings=settings, older_than_days=older_than)
  80. if dry_run or worktree_sweep.classic_mode(settings):
  81. return plan, []
  82. _, _, archived = worktree_sweep.execute_plan(repo_root, plan, settings)
  83. from hermes_cli.worktree_archive import prune_expired_archives
  84. expired = prune_expired_archives(repo_root, settings["archive_retention_days"])
  85. from agent.i18n import t
  86. saved = [t("cli.worktree.sweep_archived_removed", ref=ref) if removed
  87. else t("cli.worktree.sweep_archived_kept", ref=ref, reason=why or "?")
  88. for ref, removed, why in archived]
  89. return plan, saved + [f"deleted expired archive {r}" for r in expired]
  90. def _attended_records(records, plan) -> list:
  91. """The attended reclaim's records minus trees the sweep already decided (archived, removed,
  92. kanban) and minus any tree a live process works in: those are never touched here either."""
  93. from hermes_cli.worktree_sweep import classic_mode, live_process_pids, sweep_settings
  94. if classic_mode(sweep_settings()):
  95. return records
  96. owned = {d.path for d in plan if d.action != "skip-young"}
  97. records = [r for r in records if r.path not in owned]
  98. live = live_process_pids([r.path for r in records])
  99. return [r for r in records if not live.get(r.path)]
  100. def _prune(worktree_gc, repo_root: str, args) -> int:
  101. dry_run = bool(getattr(args, "dry_run", False))
  102. as_json = bool(getattr(args, "json", False))
  103. older_than = getattr(args, "older_than", None)
  104. actions: list = []
  105. kept: list = []
  106. plan: list = []
  107. if not getattr(args, "branches_only", False):
  108. plan, actions = _sweep(repo_root, dry_run, older_than)
  109. if not as_json:
  110. print("\n".join(_sweep_lines(plan)) + "\n")
  111. actions += worktree_gc.prune_missing_registrations(repo_root, dry_run=dry_run)
  112. tree_records = _attended_records(
  113. worktree_gc.audit_worktrees(repo_root, with_sizes=False, older_than_days=older_than), plan)
  114. actions += worktree_gc.reclaim_worktrees(repo_root, dry_run=dry_run, records=tree_records)
  115. kept = [r for r in tree_records if r.verdict == "keep"
  116. and "kanban" not in r.reason and "in use" not in r.reason]
  117. if kept and not as_json:
  118. print(f"Preserved {len(kept)} tree(s) with real work:")
  119. for r in kept:
  120. print(f" {r.name}: {r.reason}")
  121. if not getattr(args, "trees_only", False):
  122. actions += worktree_gc.reclaim_branches(repo_root, dry_run=dry_run)
  123. if as_json:
  124. print(json.dumps({
  125. "repo": repo_root,
  126. "dry_run": dry_run,
  127. "actions": actions,
  128. "preserved": [asdict(r) for r in kept],
  129. "sweep": [d.as_dict() for d in plan],
  130. }, indent=2))
  131. return 0
  132. if actions:
  133. print("Attended reclaim (`hermes worktree prune` only; the automatic sweep is the table above):")
  134. for line in actions:
  135. print(f" {line}")
  136. print(f"{len(actions)} action(s) {'planned' if dry_run else 'done'}.")
  137. else:
  138. print("Nothing to reclaim — all trees/branches carry real work or are in use.")
  139. return 0
  140. def _restore(_worktree_gc, repo_root: str, args) -> int:
  141. from hermes_cli.worktree_archive import ArchiveError, restore_archive
  142. name = getattr(args, "name", None)
  143. if not name:
  144. print("Usage: hermes worktree restore <name> [--path DIR]")
  145. return 1
  146. try:
  147. result = restore_archive(repo_root, name, getattr(args, "path", None))
  148. except ArchiveError as exc:
  149. print(f"✗ {exc}")
  150. return 1
  151. print(f"✓ Restored {result['ref']} → {result['path']}")
  152. if result["detached"]:
  153. print(f" Detached at {result['head'][:12]} (branch {result['branch'] or '-'} moved or is checked out "
  154. "elsewhere); create a branch with `git switch -c <name>`.")
  155. else:
  156. print(f" Branch: {result['branch']}")
  157. for item in result["skipped_untracked"]:
  158. print(f" Not captured (over the size cap): {item['path']} ({item['bytes'] // (1024 * 1024)} MB)")
  159. return 0
  160. _ACTIONS = {"list": _list, "prune": _prune, "restore": _restore}
  161. def cmd_worktree(args) -> int:
  162. from hermes_cli import worktree_gc
  163. repo_root = getattr(args, "repo", None)
  164. if not repo_root:
  165. import cli as _cli
  166. repo_root = _cli._git_repo_root()
  167. if not repo_root:
  168. print("Not inside a git repository (or pass --repo <path>).")
  169. return 1
  170. older_than = getattr(args, "older_than", None)
  171. if older_than is not None and older_than < 0:
  172. print("--older-than must be a non-negative number of days.")
  173. return 1
  174. action = getattr(args, "worktree_action", None) or "list"
  175. handler = _ACTIONS.get(action)
  176. if handler is None:
  177. print(f"Unknown worktree action: {action}")
  178. return 1
  179. return handler(worktree_gc, repo_root, args)