worktree_sweep.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. """Snapshot-then-delete sweep for stale worktrees (``worktrees.archive_dirty``, default on).
  2. The classic pruner (``worktree_ops._prune_stale_worktree_trees``) never removes a dirty or
  3. unpushed tree at any age, so leftovers of finished lanes pile up forever. This sweep keeps its
  4. tiers and classifier, then removes an idle dirty/unpushed tree only after archiving its full
  5. working state to ``refs/hermes/archive/<tree>`` (``worktree_archive``); a failed archive keeps
  6. the tree. Never touched, at any age or budget: Kanban ``t_<hex>`` trees, trees whose ``hermes``
  7. lock owner still runs, trees any live process sits in (cwd or open file), and trees with file or
  8. ref activity younger than their tier, and trees holding anything an archive cannot carry
  9. (``worktree_retention.removal_blocker``: a submodule, an embedded repository, a per-worktree ref,
  10. an untracked file over the size cap). With
  11. ``archive_dirty: false`` and no size budget the classic pruner runs unchanged.
  12. ``plan_sweep`` is read-only (``hermes worktree prune --dry-run`` prints it); ``execute_plan``
  13. applies a frozen plan.
  14. """
  15. from __future__ import annotations
  16. import logging
  17. import os
  18. import subprocess
  19. import sys
  20. import time
  21. from dataclasses import asdict, dataclass
  22. from pathlib import Path
  23. from typing import Optional
  24. logger = logging.getLogger("cli")
  25. _DEFAULTS = {"archive_dirty": True, "archive_max_file_mb": 50, "archive_retention_days": 30, "max_total_gb": 0}
  26. _PROTECTED_BRANCHES = {"main", "master", "develop", "dev", "trunk"}
  27. _ARCHIVE_REASONS = {"dirty": "uncommitted changes", "unpushed": "unpushed commits"}
  28. @dataclass
  29. class Decision:
  30. name: str
  31. path: str
  32. action: str # remove | remove-keep-branch | archive-remove | skip-* | keep-*
  33. reason: str
  34. age_hours: float
  35. branch: Optional[str] = None
  36. mtime: float = 0.0
  37. force: bool = False
  38. verdict: str = ""
  39. lock_state: Optional[str] = None
  40. size_mb: Optional[int] = None
  41. tier_hours: float = 0.0
  42. planned_at: float = 0.0
  43. def as_dict(self) -> dict:
  44. return asdict(self)
  45. def sweep_settings() -> dict:
  46. """``worktrees.*`` from the active profile's config (defaults on any read failure)."""
  47. settings = dict(_DEFAULTS)
  48. try:
  49. from hermes_cli.config import load_config_readonly
  50. section = load_config_readonly().get("worktrees") or {}
  51. if isinstance(section, dict):
  52. settings.update({k: section[k] for k in _DEFAULTS if section.get(k) is not None})
  53. except Exception:
  54. logger.debug("worktrees config unreadable; using defaults", exc_info=True)
  55. settings["archive_dirty"] = bool(settings["archive_dirty"])
  56. for key in ("archive_max_file_mb", "archive_retention_days", "max_total_gb"):
  57. try:
  58. settings[key] = max(0.0, float(settings[key]))
  59. except (TypeError, ValueError):
  60. settings[key] = float(_DEFAULTS[key])
  61. return settings
  62. def classic_mode(settings: dict) -> bool:
  63. """True when the sweep must behave exactly like the pre-archive pruner."""
  64. return not settings["archive_dirty"] and not settings["max_total_gb"]
  65. # ---------------------------------------------------------------- live-work detection
  66. def _inside(target: str, roots: list[str]) -> Optional[str]:
  67. for root in roots:
  68. if target == root or target.startswith(root + os.sep):
  69. return root
  70. return None
  71. def _proc_links(pid_dir: Path):
  72. yield pid_dir / "cwd"
  73. try:
  74. yield from (pid_dir / "fd").iterdir()
  75. except OSError:
  76. return
  77. def _linux_live_pids(roots: list[str], exclude: frozenset) -> dict[str, list[int]]:
  78. hits: dict[str, list[int]] = {}
  79. for pid_dir in Path("/proc").iterdir():
  80. if not pid_dir.name.isdigit() or int(pid_dir.name) in exclude:
  81. continue
  82. for link in _proc_links(pid_dir):
  83. try:
  84. target = os.readlink(link)
  85. except OSError:
  86. continue
  87. root = _inside(target.removesuffix(" (deleted)"), roots)
  88. if root is not None:
  89. hits.setdefault(root, []).append(int(pid_dir.name))
  90. break
  91. return hits
  92. def _psutil_live_pids(roots: list[str], exclude: frozenset) -> dict[str, list[int]]:
  93. hits: dict[str, list[int]] = {}
  94. try:
  95. import psutil
  96. except ImportError:
  97. return hits
  98. for proc in psutil.process_iter(["pid"]):
  99. try:
  100. if proc.pid in exclude:
  101. continue
  102. root = _inside(os.path.realpath(proc.cwd()), roots)
  103. except (psutil.Error, OSError):
  104. continue
  105. if root is not None:
  106. hits.setdefault(root, []).append(proc.pid)
  107. return hits
  108. def live_process_pids(paths, exclude=()) -> dict[str, list[int]]:
  109. """``{path: [pid, ...]}`` for every *path* some live process works in: cwd or an open fd on
  110. Linux (``/proc``), cwd elsewhere (psutil, best-effort). Keys are the paths as given;
  111. *exclude* pids are ignored (an exiting session's own process)."""
  112. real = {os.path.realpath(str(p)): str(p) for p in paths}
  113. if not real:
  114. return {}
  115. roots = sorted(real, key=len, reverse=True)
  116. try:
  117. skip = frozenset(int(p) for p in exclude)
  118. hits = (_linux_live_pids(roots, skip) if sys.platform.startswith("linux")
  119. else _psutil_live_pids(roots, skip))
  120. except OSError:
  121. hits = {}
  122. return {real[root]: pids for root, pids in hits.items()}
  123. def _last_activity(path: str) -> float:
  124. """Newest mtime among the tree's HEAD/reflog, every changed or untracked file, and the
  125. directory holding each changed path.
  126. The tree dir's own mtime only moves when a top-level entry is created or removed, so a lane
  127. editing files deep inside for days still looks idle by it. A deleted file has no mtime; its
  128. nearest surviving parent directory was stamped by the unlink. The index is not a signal:
  129. the classifier's own ``git status`` may rewrite it. ``GIT_OPTIONAL_LOCKS=0`` keeps this probe from refreshing (and re-stamping) the index.
  130. """
  131. from hermes_cli._subprocess_compat import noninteractive_repo_git_env
  132. newest = 0.0
  133. wt = Path(path)
  134. env = noninteractive_repo_git_env(path)
  135. if env is None:
  136. return time.time() # unverifiable: treat as active
  137. env["GIT_OPTIONAL_LOCKS"] = "0"
  138. try:
  139. git_dir = subprocess.run(["git", "rev-parse", "--absolute-git-dir"], cwd=path, env=env, capture_output=True,
  140. text=True, encoding="utf-8", errors="surrogateescape", timeout=10, stdin=subprocess.DEVNULL, check=False).stdout.strip()
  141. status = subprocess.run(["git", "status", "--porcelain", "-z", "-uall", "--no-renames"], cwd=path, env=env,
  142. capture_output=True, text=True, encoding="utf-8", errors="surrogateescape",
  143. timeout=60, stdin=subprocess.DEVNULL, check=False)
  144. except (OSError, subprocess.SubprocessError):
  145. return time.time()
  146. if status.returncode != 0:
  147. return time.time()
  148. candidates = [Path(git_dir) / name for name in ("HEAD", "logs/HEAD")] if git_dir else []
  149. changed = [wt / entry[3:] for entry in status.stdout.split("\0") if len(entry) > 3]
  150. candidates += changed
  151. for item in changed:
  152. parent = item.parent
  153. while parent != wt and not parent.exists() and wt in parent.parents:
  154. parent = parent.parent # a whole deleted subtree: its surviving ancestor moved
  155. candidates.append(parent)
  156. for candidate in dict.fromkeys(candidates):
  157. try:
  158. newest = max(newest, candidate.lstat().st_mtime)
  159. except OSError:
  160. continue
  161. return newest
  162. # ---------------------------------------------------------------- planning
  163. def _tier_hours(name: str, max_age_hours: float) -> float:
  164. from hermes_cli.worktree_ops import prune_tier_hours
  165. return prune_tier_hours(name, max_age_hours)
  166. def _plan_survivor(repo_root: str, entry: Path, verdict: str, lock_state, settings: dict,
  167. tier_hours: float, now: float) -> tuple[str, str, Optional[str], Optional[float]]:
  168. """(action, reason, lock_state, last_activity) for a dirty/unpushed tree past its tier."""
  169. from hermes_cli import worktree_ops as ops
  170. from hermes_cli.worktree_archive import archive_preflight
  171. what = _ARCHIVE_REASONS[verdict]
  172. lock_state = ops._worktree_lock_is_live(repo_root, str(entry), timeout=5)
  173. if lock_state == "live":
  174. return "skip-live-lock", "lock owner still running", lock_state, None
  175. active = _last_activity(str(entry))
  176. if active > now - tier_hours * 3600:
  177. return "skip-young", f"{what}; last activity {(now - active) / 3600:.1f}h ago", lock_state, active
  178. if not settings["archive_dirty"]:
  179. return f"keep-{verdict}", what, lock_state, active # idle: only the size budget may evict it
  180. unsafe = archive_preflight(str(entry), settings["archive_max_file_mb"])
  181. if unsafe:
  182. return unsafe[0], unsafe[1], lock_state, active
  183. return "archive-remove", what, lock_state, active
  184. def _apply_budget(decisions: list[Decision], max_total_gb: float, max_file_mb: float = 50) -> None:
  185. """Evict the oldest idle kept trees (archive first) until they fit *max_total_gb*.
  186. Only idle past-tier trees count or move; live, young and kanban trees are invisible here.
  187. """
  188. from hermes_cli.worktree_archive import archive_preflight
  189. from hermes_cli.worktree_gc import _tree_size_mb
  190. eligible = [d for d in decisions if d.action in ("keep-dirty", "keep-unpushed")]
  191. for d in eligible:
  192. d.size_mb = _tree_size_mb(Path(d.path), timeout=120) or 0
  193. total = sum(d.size_mb or 0 for d in eligible)
  194. budget_mb = max_total_gb * 1024
  195. for d in sorted(eligible, key=lambda x: x.mtime):
  196. if total <= budget_mb:
  197. break
  198. unsafe = archive_preflight(d.path, max_file_mb)
  199. if unsafe:
  200. d.action, d.reason = unsafe
  201. continue
  202. d.action, d.reason = "archive-remove", f"{d.reason}; over worktrees.max_total_gb={max_total_gb:g}"
  203. total -= d.size_mb or 0
  204. _DESTRUCTIVE = ("remove", "remove-keep-branch", "archive-remove")
  205. def plan_sweep(repo_root: str, max_age_hours: int = 24, settings: Optional[dict] = None,
  206. now: Optional[float] = None, older_than_days: Optional[float] = None) -> list[Decision]:
  207. """Read-only decision for every tree under ``<repo>/.worktrees`` (kanban/young included).
  208. *older_than_days* (``hermes worktree prune --older-than``) only restricts: a tree idle for
  209. less than that is never archived or removed, whatever its tier.
  210. """
  211. import re
  212. from hermes_cli import worktree_ops as ops
  213. settings = settings or sweep_settings()
  214. now = now or time.time()
  215. worktrees_dir = Path(repo_root) / ".worktrees"
  216. if not worktrees_dir.is_dir():
  217. return []
  218. candidates = ops._prune_candidates(worktrees_dir, max_age_hours, now)
  219. doomed_names = {entry.name for entry, _m, _f in candidates}
  220. decisions: list[Decision] = []
  221. for entry in sorted(worktrees_dir.iterdir()):
  222. if not entry.is_dir() or entry.name in doomed_names:
  223. continue
  224. try:
  225. age = (now - entry.stat().st_mtime) / 3600
  226. except OSError:
  227. continue
  228. kanban = re.match(r"^t_[0-9a-f]+$", entry.name)
  229. decisions.append(Decision(entry.name, str(entry), "skip-kanban" if kanban else "skip-young",
  230. "owned by kanban gc" if kanban else "younger than its age tier", round(age, 1)))
  231. verdicts = ops._classify_prune_candidates(repo_root, candidates) if candidates else []
  232. # archive_dirty: false is the classic pruner verbatim (I6), which has no process check.
  233. live = {} if classic_mode(settings) else live_process_pids([str(v[0]) for v in verdicts])
  234. for entry, mtime, force, verdict, lock_state in verdicts:
  235. tier = _tier_hours(entry.name, max_age_hours)
  236. d = Decision(entry.name, str(entry), "", "", round((now - mtime) / 3600, 1), mtime=mtime, force=force,
  237. verdict=verdict, lock_state=lock_state, tier_hours=tier, planned_at=now)
  238. if live.get(str(entry)):
  239. d.action, d.reason = "skip-live-process", f"in use by pid {', '.join(map(str, live[str(entry)][:5]))}"
  240. elif verdict == "locked-live":
  241. d.action, d.reason = "skip-live-lock", "lock owner still running"
  242. elif verdict in _ARCHIVE_REASONS and classic_mode(settings):
  243. d.action, d.reason = f"keep-{verdict}", _ARCHIVE_REASONS[verdict]
  244. elif verdict in _ARCHIVE_REASONS:
  245. d.action, d.reason, d.lock_state, active = _plan_survivor(
  246. repo_root, entry, verdict, lock_state, settings, tier, now)
  247. if active:
  248. d.age_hours = min(d.age_hours, round((now - active) / 3600, 1))
  249. elif blocked := ops.removal_blocked(str(entry)):
  250. d.action, d.reason = blocked
  251. else:
  252. d.action = "remove-keep-branch" if verdict == "reap-keep-branch" else "remove"
  253. d.reason = "pushed to origin; branch kept" if verdict == "reap-keep-branch" else "clean and merged/pushed"
  254. decisions.append(d)
  255. if settings["max_total_gb"]:
  256. _apply_budget(decisions, settings["max_total_gb"], settings["archive_max_file_mb"])
  257. if older_than_days is not None:
  258. for d in decisions:
  259. if d.action in _DESTRUCTIVE and d.age_hours < older_than_days * 24:
  260. d.action, d.reason = "skip-young", f"idle {d.age_hours:.1f}h (--older-than {older_than_days:g})"
  261. return decisions
  262. # ---------------------------------------------------------------- execution
  263. def _branch_published(repo_root: str, branch: str, remote_heads: Optional[dict]) -> bool:
  264. """Whether *branch* exists on a remote. Unknown (``ls-remote`` failed) counts as published:
  265. deleting a branch is never needed for safety, so doubt keeps it."""
  266. from hermes_cli.worktree_ops import _git_out
  267. try:
  268. if _git_out(["remote"], repo_root) == "":
  269. return False # no remote at all: nothing could have been published
  270. if remote_heads is None or branch in remote_heads:
  271. return True
  272. refs = _git_out(["for-each-ref", "--format=%(refname)", f"refs/remotes/*/{branch}"], repo_root)
  273. except (OSError, subprocess.SubprocessError):
  274. return True # unknown: keep the branch
  275. return refs is None or bool(refs.strip())
  276. def _in_use_since(path: str, since: float, exclude=()) -> Optional[str]:
  277. """Why *path* must not be removed now: a live process works in it, or a file/ref in it
  278. changed at or after *since*. None = still idle."""
  279. pids = live_process_pids([path], exclude=exclude).get(path)
  280. if pids:
  281. return f"in use by pid {', '.join(map(str, pids[:5]))}"
  282. active = _last_activity(path)
  283. if active >= since:
  284. return f"changed {max(0.0, time.time() - active):.0f}s ago"
  285. return None
  286. def _index_moved(path: str, captured: str) -> Optional[str]:
  287. """Why the staged state of *path* no longer matches the archive (``git add``/``apply
  288. --cached`` after the capture: the index is not a file-mtime signal), or None. A stat-only
  289. refresh by ``git status`` does not count. Unreadable index = moved (keep the tree)."""
  290. from hermes_cli.worktree_archive import ArchiveError, staged_state
  291. try:
  292. if staged_state(path) == captured:
  293. return None
  294. except (ArchiveError, OSError, subprocess.SubprocessError):
  295. pass
  296. return "staged changes since the snapshot"
  297. def archive_then_remove(repo_root: str, path: str, *, reason: str, max_untracked_mb: float,
  298. unlock: bool, remote_heads_fn=None, keep_branch: bool = False,
  299. exclude_pids=(),
  300. ) -> tuple[str, Optional[str], bool, Optional[str]]:
  301. """Snapshot *path*, then remove it -> ``(archive_ref, kept_branch, removed, why_kept)``.
  302. Raises ``ArchiveError`` (tree untouched) when the snapshot fails. Right after the snapshot the
  303. tree is checked again: a process (other than *exclude_pids*) now working in it, any edit
  304. made while the snapshot ran, staged entries that differ from the captured index, or anything
  305. the archive does not hold (``worktree_retention.removal_blocker``: a file the snapshot skipped
  306. for size, an embedded repository, a per-worktree ref, a submodule) keep the tree (``removed`` False, *why_kept* says why; the archive stays). The branch
  307. survives when it is protected or published on a remote (an open PR may still need it);
  308. otherwise the archive ref anchors its commits and the local branch is deleted.
  309. """
  310. from hermes_cli.worktree_archive import snapshot_worktree
  311. from hermes_cli.worktree_ops import _git, _git_quiet, release_lsp_clients
  312. from hermes_cli.worktree_retention import removal_blocker
  313. from hermes_cli._subprocess_compat import noninteractive_git_env
  314. started = time.time()
  315. arc = snapshot_worktree(repo_root, path, reason=reason, max_untracked_mb=max_untracked_mb)
  316. blocked = removal_blocker(path, skipped=arc.meta.get("skipped_untracked"), gitlinks=True)
  317. busy = (_in_use_since(path, started, exclude=exclude_pids) or _index_moved(path, arc.staged)
  318. or (blocked and blocked[1]))
  319. if busy:
  320. logger.warning("Archived %s to %s but keeping it: %s", path, arc.ref, busy)
  321. return arc.ref, None, False, busy
  322. release_lsp_clients(path)
  323. if unlock:
  324. _git_quiet(["worktree", "unlock", path], repo_root, log=f"unlock {path}")
  325. removed = _git(["worktree", "remove", "--force", path], repo_root, timeout=60)
  326. if removed.returncode != 0:
  327. logger.warning("Archived %s to %s but could not remove it: %s", path, arc.ref, removed.stderr.strip())
  328. return arc.ref, None, False, removed.stderr.strip() or "git worktree remove failed"
  329. branch = arc.meta.get("branch")
  330. if not branch or keep_branch or branch in _PROTECTED_BRANCHES:
  331. return arc.ref, branch, True, None
  332. if remote_heads_fn is None:
  333. from hermes_cli.worktree_ops import _fetch_remote_branch_heads
  334. heads = _fetch_remote_branch_heads(repo_root, timeout=10)
  335. else:
  336. heads = remote_heads_fn()
  337. if _branch_published(repo_root, branch, heads):
  338. return arc.ref, branch, True, None
  339. _git(["branch", "-D", branch], repo_root, stdin=subprocess.DEVNULL, env=noninteractive_git_env())
  340. return arc.ref, None, True, None
  341. def _recheck(repo_root: str, d: Decision) -> tuple[Optional[str], Optional[str]]:
  342. """Fresh gate for ONE planned tree, run immediately before it is touched -> (why_keep,
  343. lock_state). Earlier trees in the batch can take minutes to archive; a user may have entered
  344. this one meanwhile."""
  345. from hermes_cli import worktree_ops as ops
  346. if not os.path.isdir(d.path):
  347. return "gone", None
  348. lock_state = ops._worktree_lock_is_live(repo_root, d.path, timeout=5)
  349. if lock_state == "live":
  350. return "lock owner still running", lock_state
  351. since = d.planned_at or time.time()
  352. if d.action == "archive-remove" and d.tier_hours:
  353. since = min(since, time.time() - d.tier_hours * 3600) # back inside its idle tier
  354. busy = _in_use_since(d.path, since)
  355. if busy:
  356. return busy, lock_state
  357. if d.action != "archive-remove" and ops._worktree_is_dirty(d.path, repo_root, timeout=10):
  358. return "new uncommitted changes", lock_state
  359. return None, lock_state
  360. def execute_plan(repo_root: str, plan: list[Decision], settings: dict
  361. ) -> tuple[list[str], set, list[tuple[str, bool, Optional[str]]]]:
  362. """Apply a frozen plan -> ``(preserved_stale, kept_branches, [(archive_ref, removed, why_kept)])``.
  363. Each tree is re-gated (lock, live process, fresh activity) right before it is archived or
  364. removed; ``removed`` is False when the archive was saved but the tree was kept (*why_kept*)."""
  365. from hermes_cli import worktree_ops as ops
  366. from hermes_cli.worktree_archive import ArchiveError
  367. memo: dict = {}
  368. def remote_heads():
  369. if "heads" not in memo:
  370. memo["heads"] = ops._fetch_remote_branch_heads(repo_root, timeout=10)
  371. return memo["heads"]
  372. kept_branches: set = set()
  373. archived: list[tuple[str, bool, Optional[str]]] = []
  374. preserved: list[str] = [f"{d.name} ({d.reason})" for d in plan if d.action.startswith("keep-")]
  375. for d in (d for d in plan if d.action in _DESTRUCTIVE):
  376. why_keep, lock_state = _recheck(repo_root, d)
  377. if why_keep:
  378. logger.info("Sweep: keeping %s (%s)", d.name, why_keep)
  379. continue
  380. if d.action != "archive-remove":
  381. _, kept = ops._reap_prune_verdicts(
  382. repo_root, [(Path(d.path), d.mtime, d.force, d.verdict, lock_state)], 0.0)
  383. kept_branches |= kept
  384. continue
  385. try:
  386. ref, kept, removed, why = archive_then_remove(
  387. repo_root, d.path, reason=f"sweep: {d.reason}", max_untracked_mb=settings["archive_max_file_mb"],
  388. unlock=lock_state == "dead", remote_heads_fn=remote_heads)
  389. except (ArchiveError, OSError, subprocess.SubprocessError) as exc:
  390. logger.warning("Keeping worktree %s: archive failed (%s)", d.name, exc)
  391. preserved.append(f"{d.name} (archive failed)")
  392. continue
  393. archived.append((ref, removed, why))
  394. if not removed:
  395. preserved.append(f"{d.name} (archived to {ref}, kept: {why})")
  396. if kept:
  397. kept_branches.add(kept)
  398. return preserved, kept_branches, archived
  399. def run_sweep(repo_root: str, max_age_hours: int, settings: dict) -> None:
  400. """Plan + execute + archive retention for one repo (the archive-mode pruner)."""
  401. from hermes_cli import worktree_ops as ops
  402. from hermes_cli.worktree_archive import prune_expired_archives
  403. plan = plan_sweep(repo_root, max_age_hours, settings)
  404. preserved, kept_branches, archived = execute_plan(repo_root, plan, settings)
  405. removed = [ref for ref, gone, _why in archived if gone]
  406. if removed:
  407. logger.warning("Archived and removed %d idle worktree(s) with unmerged work; restore any with "
  408. "`hermes worktree restore <name>` (`hermes worktree list` shows archives).", len(removed))
  409. if preserved:
  410. logger.warning("Preserving %d stale worktree(s) (run `hermes worktree prune --dry-run` for reasons): %s",
  411. len(preserved), ", ".join(sorted(preserved)[:20]))
  412. expired = prune_expired_archives(repo_root, settings["archive_retention_days"])
  413. if expired:
  414. logger.info("Deleted %d worktree archive(s) older than %g days", len(expired), settings["archive_retention_days"])
  415. ops._prune_orphaned_branches(repo_root, protect=kept_branches)