Skip to content

The agent that grows with you

refactor(cli): unify git subprocess wrapper and split worktree god functions into phase helpers

Teknium29a854a95062
diff --git a/cli.py b/cli.py
index 98e098e12da..57fc425871f 100644
--- a/cli.py
+++ b/cli.py
@@ -1524,36 +1524,39 @@ def _reset_terminal_input_modes_on_exit() -> None:
# =============================================================================
-# Git Worktree Isolation (#652)
+# Git Worktree Isolation
# =============================================================================
# Tracks the active worktree for cleanup on exit
_active_worktree: Optional[Dict[str, str]] = None
+def _git(args, cwd, timeout: float = 10, **kwargs):
+ """Run ``git *args`` in *cwd* capturing UTF-8 text; raises like ``subprocess.run``."""
+ import subprocess
+
+ return subprocess.run(
+ ["git", *args],
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=timeout, cwd=cwd, **kwargs,
+ )
+
+
+def _git_quiet(args, cwd, timeout: float = 10, log: str | None = None, **kwargs) -> None:
+ """Fail-soft ``_git``: swallow every error, optionally logging it at DEBUG with *log* as prefix."""
+ try:
+ _git(args, cwd, timeout=timeout, **kwargs)
+ except Exception as e:
+ if log:
+ logger.debug("%s: %s", log, e)
+
+
def _normalize_git_bash_path(p: Optional[str]) -> Optional[str]:
- """Translate a Git Bash-style path (``/c/Users/...``) to the native
- Windows form (``C:\\Users\\...``) that Python's ``subprocess.Popen``
- and ``pathlib.Path`` accept.
-
- No-op on non-Windows and for paths that already look native. Git on
- native Windows normally emits forward-slash Windows paths
- (``C:/Users/...``) which both bash and Python handle, but certain
- configurations (Git Bash shells, MSYS2, WSL-mounted repos) surface
- ``/c/...`` or ``/cygdrive/c/...`` variants.
- """
- if not p:
+ """Translate a Git Bash path (``/c/Users/...``, ``/cygdrive/c/...``, ``/mnt/c/...``)
+ to native Windows form (``C:\\Users\\...``). No-op on non-Windows and native paths."""
+ if not p or sys.platform != "win32":
return p
- if sys.platform != "win32":
- return p
- import re as _re
- # /c/Users/... or /C/Users/...
- m = _re.match(r"^/([a-zA-Z])/(.*)$", p)
- if m:
- drive, rest = m.group(1), m.group(2)
- return f"{drive.upper()}:\\{rest.replace('/', chr(92))}"
- # /cygdrive/c/... or /mnt/c/...
- m = _re.match(r"^/(?:cygdrive|mnt)/([a-zA-Z])/(.*)$", p)
+ m = re.match(r"^/(?:(?:cygdrive|mnt)/)?([a-zA-Z])/(.*)$", p)
if m:
drive, rest = m.group(1), m.group(2)
return f"{drive.upper()}:\\{rest.replace('/', chr(92))}"
@@ -1561,19 +1564,9 @@ def _normalize_git_bash_path(p: Optional[str]) -> Optional[str]:
def _git_repo_root() -> Optional[str]:
- """Return the git repo root for CWD, or None if not in a repo.
-
- Runs through :func:`_normalize_git_bash_path` so callers can pass
- the result directly to ``Path``/``subprocess.Popen(cwd=...)`` on
- Windows without hitting ``C:\\c\\Users\\...`` style resolution
- mistakes.
- """
- import subprocess
+ """Return the git repo root for CWD (Git-Bash-normalized), or None if not in a repo."""
try:
- result = subprocess.run(
- ["git", "rev-parse", "--show-toplevel"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5,
- )
+ result = _git(["rev-parse", "--show-toplevel"], None, timeout=5)
if result.returncode == 0:
return _normalize_git_bash_path(result.stdout.strip())
except Exception:
@@ -1591,38 +1584,22 @@ def _path_is_within_root(path: Path, root: Path) -> bool:
def _cleanup_failed_worktree_add(repo_root: str, wt_path: Path, branch_name: str) -> None:
- """Make a failed/timed-out ``git worktree add`` atomic after the fact.
-
- ``git worktree add`` is not transactional: killed mid-checkout (the 30s
- timeout) it leaves (a) the partially-materialized worktree directory,
- (b) an admin entry under ``.git/worktrees/<name>`` that is LOCKED with a
- reason naming the *current, live* pid — so the startup pruner's
- dead-pid unlock will never touch it — and (c) sometimes the new branch.
- Any retry of the same name then fails on the leftovers. Sweep all three,
- quietly; every step is fail-soft because this runs on an error path.
- """
- import shutil
- import subprocess
-
- def _git(*args: str) -> None:
- try:
- subprocess.run(
- ["git", *args],
- capture_output=True, text=True, timeout=15, cwd=repo_root, check=False,
- )
- except Exception:
- pass
+ """Sweep the leftovers of a failed/timed-out ``git worktree add``.
+ ``worktree add`` is not transactional: killed mid-checkout it leaves the partial
+ directory, a LOCKED admin entry under ``.git/worktrees/<name>`` naming the *live*
+ pid (so the startup pruner's dead-pid unlock never touches it), and sometimes the
+ branch. Any retry of the same name then fails. Every step is fail-soft.
+ """
try:
# Unlock first: `worktree remove --force` refuses a locked tree.
- _git("worktree", "unlock", str(wt_path))
- _git("worktree", "remove", "--force", str(wt_path))
+ _git_quiet(["worktree", "unlock", str(wt_path)], repo_root, timeout=15, check=False)
+ _git_quiet(["worktree", "remove", "--force", str(wt_path)], repo_root, timeout=15, check=False)
if wt_path.exists():
shutil.rmtree(wt_path, ignore_errors=True)
- # Drop the orphaned admin entry when the dir is already gone
- # (`remove` needs the dir; `prune` handles the dirless case).
- _git("worktree", "prune")
- _git("branch", "-D", branch_name)
+ # `remove` needs the dir; `prune` drops the admin entry when it is already gone.
+ _git_quiet(["worktree", "prune"], repo_root, timeout=15, check=False)
+ _git_quiet(["branch", "-D", branch_name], repo_root, timeout=15, check=False)
except Exception as e:
logger.debug("cleanup after failed worktree add: %s", e)
@@ -1631,17 +1608,11 @@ _PACK_SPRAWL_THRESHOLD = 15
def _maintain_pack_health(repo_root: str) -> None:
- """Repack the object store when pack files sprawl (background thread).
-
- On a multi-agent box every fetch/salvage session adds packs; git never
- consolidates them on its own aggressively enough (``gc --auto``'s
- threshold is 50 *and* it counts only non-kept packs). Past a few dozen
- packs every object lookup scans every pack index, and worktree creation
- can blow its 30s timeout under concurrent load (Aug 2026 incident: 39
- packs, 638MB → ``hermes -w`` timing out; a full repack halved the store
- and restored 0.5s creates). Threshold 15 keeps lookups fast without
- repacking on every startup; ``nice`` + background thread keeps it off
- the startup path. Fail-soft everywhere.
+ """Repack the object store when pack files sprawl (background thread, fail-soft).
+
+ ``gc --auto`` only triggers at 50 non-kept packs; past a few dozen packs every
+ object lookup scans every pack index and worktree creation can blow its timeout
+ under concurrent load. ``nice`` keeps the repack off the startup path.
"""
import subprocess
@@ -1660,12 +1631,8 @@ def _maintain_pack_health(repo_root: str) -> None:
cmd,
capture_output=True, text=True, timeout=1800, cwd=repo_root, check=False,
)
- # Repacking can strand now-duplicated admin files; a prune here keeps
- # the worktree bookkeeping tight on the same maintenance pass.
- subprocess.run(
- ["git", "worktree", "prune"],
- capture_output=True, text=True, timeout=60, cwd=repo_root, check=False,
- )
+ # Repacking can strand now-duplicated admin files; prune on the same pass.
+ _git(["worktree", "prune"], repo_root, timeout=60, check=False)
except Exception as e:
logger.debug("pack maintenance skipped: %s", e)
@@ -1677,62 +1644,34 @@ def _resolve_worktree_base(
) -> tuple:
"""Resolve the freshest base ref to branch a new worktree from.
- The standalone clone's ``HEAD`` can lag the remote by hundreds of commits
- (the ``~/.hermes/hermes-agent`` clone is updated only by ``hermes update``,
- not on every session). Branching a worktree from that stale ``HEAD`` roots
- every new branch on an old base — so the PR diff GitHub computes against
- current ``main`` balloons with unrelated changes, and the agent has to
- discover the staleness via the pre-push gate and rebase. Branching from the
- freshly-fetched remote tip instead means the worktree starts current.
-
- Strategy (each step falls back to the next on failure):
- 1. If the current branch tracks an upstream, refresh and use that
- upstream ref — so a deliberate feature-branch worktree tracks its own
- remote, not the default branch.
- 2. Else refresh the remote's default branch (``origin/HEAD`` → e.g.
- ``origin/main``) and use it.
- 3. Else fall back to ``HEAD`` (offline, no remote, or detached) — the
- old behavior, never worse than before.
-
- "Refresh" is deliberately cheap on the startup path (the fetch here used
- to stall ``hermes -w`` launches for 30-60s on flaky smart-HTTP
- connections):
-
- - The fetch is SKIPPED entirely when the repo's ``FETCH_HEAD`` is younger
- than *freshness_window* seconds — a base fetched moments ago cannot have
- meaningfully moved, so repeated launches don't re-pay a network round
- trip.
- - The fetch is capped at *fetch_timeout* seconds. On timeout or failure we
- fall back to the locally-known remote-tracking ref (labelled "cached")
- instead of cascading into a second fetch attempt. Genuine staleness is
- backstopped by the pre-push stale-base gate.
-
- Returns ``(base_ref, label)`` where *base_ref* is a git revision suitable
- for ``git worktree add ... <base_ref>`` and *label* is a short
- human-readable description for the session banner.
+ The standalone clone's ``HEAD`` can lag the remote by hundreds of commits, so
+ branching from it roots every new branch on a stale base. Strategy, each step
+ falling back to the next: (1) the current branch's upstream, refreshed;
+ (2) the remote default branch (``origin/HEAD``), refreshed; (3) local ``HEAD``.
+
+ Refresh is deliberately cheap on the startup path: the fetch is skipped when
+ ``FETCH_HEAD`` is younger than *freshness_window* seconds and capped at
+ *fetch_timeout*; on failure the cached remote-tracking ref is used (never a
+ second fetch). Genuine staleness is backstopped by the pre-push stale-base gate.
+
+ Returns ``(base_ref, label)`` — *label* is the human-readable banner description.
"""
import subprocess
from hermes_cli._subprocess_compat import noninteractive_git_env
- def _git(args, timeout: float = 20):
- return subprocess.run(
- ["git", *args],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=repo_root,
- stdin=subprocess.DEVNULL,
- env=noninteractive_git_env(),
- )
+ def _run(args, timeout: float = 20):
+ return _git(args, repo_root, timeout=timeout, stdin=subprocess.DEVNULL, env=noninteractive_git_env())
def _ref_exists(ref: str) -> bool:
try:
- return _git(["rev-parse", "--verify", "--quiet", ref + "^{commit}"]).returncode == 0
+ return _run(["rev-parse", "--verify", "--quiet", ref + "^{commit}"]).returncode == 0
except Exception:
return False
def _fetch_head_age() -> Optional[float]:
- """Seconds since the last fetch in this repo, or None if unknown."""
try:
- gd = _git(["rev-parse", "--git-dir"])
+ gd = _run(["rev-parse", "--git-dir"])
if gd.returncode != 0:
return None
git_dir = Path(gd.stdout.strip())
@@ -1746,16 +1685,12 @@ def _resolve_worktree_base(
return None
def _refresh(remote: str, branch: str, ref: str) -> tuple:
- """Return (ref, label) after a cheap best-effort refresh of *ref*.
-
- Never raises, never fetches twice, never blocks longer than
- *fetch_timeout*.
- """
+ """(ref, label) after a best-effort refresh; never raises, never fetches twice."""
age = _fetch_head_age()
if age is not None and age < freshness_window and _ref_exists(ref):
return ref, f"{ref} (fetched {int(age)}s ago)"
try:
- fetched = _git(["fetch", remote, branch], timeout=fetch_timeout)
+ fetched = _run(["fetch", remote, branch], timeout=fetch_timeout)
if fetched.returncode == 0:
return ref, f"{ref} (fetched)"
reason = "fetch failed"
@@ -1770,7 +1705,7 @@ def _resolve_worktree_base(
# 1. Current branch's upstream, if it tracks one.
try:
- up = _git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"])
+ up = _run(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"])
if up.returncode == 0:
upstream = up.stdout.strip() # e.g. "origin/main"
if upstream and "/" in upstream:
@@ -1781,21 +1716,18 @@ def _resolve_worktree_base(
# 2. Remote default branch (origin/HEAD).
try:
- # Resolve the remote's default branch symref.
- head_ref = _git(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"])
+ head_ref = _run(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"])
default_ref = ""
if head_ref.returncode == 0:
default_ref = head_ref.stdout.strip().replace("refs/remotes/", "", 1)
if not default_ref:
- # origin/HEAD not set locally; ask the remote (network — capped
- # like the fetch so a stalled connection can't hang startup).
- show = _git(["remote", "show", "origin"], timeout=max(fetch_timeout, 5))
+ # origin/HEAD not set locally; ask the remote (network — capped like the fetch).
+ show = _run(["remote", "show", "origin"], timeout=max(fetch_timeout, 5))
for line in show.stdout.splitlines():
line = line.strip()
if line.startswith("HEAD branch:"):
_branch = line.split(":", 1)[1].strip()
- # A remote with no default branch reports "(unknown)";
- # don't construct a bogus "origin/(unknown)" ref from it.
+ # A remote with no default branch reports "(unknown)".
if _branch and _branch != "(unknown)":
default_ref = "origin/" + _branch
break
@@ -1809,60 +1741,13 @@ def _resolve_worktree_base(
return "HEAD", "HEAD (local — could not reach remote)"
-def _setup_worktree(repo_root: str = None, sync_base: bool = True,
- name: Optional[str] = None) -> Optional[Dict[str, str]]:
- """Create an isolated git worktree for this CLI session.
-
- Returns a dict with worktree metadata on success, None on failure.
- The dict contains: path, branch, repo_root.
-
- When *sync_base* is True (default), the worktree branches from the
- freshly-fetched remote tip rather than the (possibly stale) local ``HEAD``
- — see ``_resolve_worktree_base``. Set ``worktree_sync: false`` in config to
- branch from local ``HEAD`` (the pre-#10760-followup behavior).
-
- When *name* is given (``/worktree new <name>``), the worktree directory
- and branch use the sanitized name instead of a random ``hermes-<id>``.
- Named trees intentionally skip the ``hermes-`` prefix so the startup
- pruner ages them on its slower named-tree schedule.
- """
- import subprocess
-
- from hermes_cli._subprocess_compat import (
- noninteractive_git_env as _noninteractive_git_env,
- )
-
- repo_root = repo_root or _git_repo_root()
- if not repo_root:
- _cprint("\033[31m✗ --worktree requires being inside a git repository.\033[0m")
- print(" cd into your project repo first, then run hermes -w")
- return None
-
- if name:
- safe = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-._")[:40]
- wt_name = safe or f"hermes-{uuid.uuid4().hex[:8]}"
- else:
- wt_name = f"hermes-{uuid.uuid4().hex[:8]}"
- branch_name = f"hermes/{wt_name}"
-
- worktrees_dir = Path(repo_root) / ".worktrees"
- worktrees_dir.mkdir(parents=True, exist_ok=True)
-
- wt_path = worktrees_dir / wt_name
- if name and wt_path.exists():
- _cprint(f"\033[31m✗ Worktree already exists: {wt_path}\033[0m")
- print(" Pick a different name, or remove it with: "
- f"git worktree remove {wt_path}")
- return None
-
- # Ensure .worktrees/ is in .gitignore
+def _ensure_worktrees_gitignored(repo_root: str) -> None:
+ """Append ``.worktrees/`` to the repo's .gitignore when missing (fail-soft)."""
gitignore = Path(repo_root) / ".gitignore"
_ignore_entry = ".worktrees/"
try:
- # utf-8-sig: git files are UTF-8 and Notepad prepends a BOM, which
- # would glue to the first line and defeat the membership check below
- # (duplicating the entry); the locale default also breaks non-ASCII
- # patterns on Windows. The append below already writes UTF-8.
+ # utf-8-sig: a Notepad BOM would glue to the first line and defeat the
+ # membership check (duplicating the entry); the append writes UTF-8.
existing = (
gitignore.read_text(encoding="utf-8-sig", errors="replace")
if gitignore.exists()
@@ -1876,197 +1761,196 @@ def _setup_worktree(repo_root: str = None, sync_base: bool = True,
except Exception as e:
logger.debug("Could not update .gitignore: %s", e)
- # Resolve the base ref. By default branch from the freshly-fetched remote
- # tip so the worktree starts current with the project, not from the
- # (possibly stale) local HEAD of the standalone clone (#10760 follow-up).
- if sync_base:
- base_ref, base_label = _resolve_worktree_base(repo_root)
- else:
- base_ref, base_label = "HEAD", "HEAD (local — worktree_sync disabled)"
- # Create the worktree. checkout.workers parallelizes the file
- # materialization (~6k files on this repo): 0.6s serial → ~0.2s with 8
- # workers. Harmless on git builds without parallel-checkout support —
- # unknown -c keys are ignored for checkout, and the fallback retry
- # below drops the flags entirely.
- _wt_add_cfg = [
- "-c", "checkout.workers=8",
- "-c", "checkout.thresholdForParallelism=100",
- ]
+def _copy_worktree_includes(repo_root: str, wt_path: Path) -> None:
+ """Copy/symlink the entries listed in ``.worktreeinclude`` (gitignored files the agent needs)."""
+ include_file = Path(repo_root) / ".worktreeinclude"
+ if not include_file.exists():
+ return
try:
- # 120s, not 30: on a multi-agent box the ~10k-file materialization
- # contends with sibling sessions' checkouts/fetches/Electron dev
- # builds for the same disk — measured 113s wall at near-zero CPU
- # under load vs 1.2s idle (Aug 2026). A too-tight timeout kills a
- # legitimately slow create and wastes the work already done.
- result = subprocess.run(
- ["git", *_wt_add_cfg, "worktree", "add", str(wt_path), "-b", branch_name, base_ref],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120, cwd=repo_root,
- stdin=subprocess.DEVNULL, env=_noninteractive_git_env(),
+ repo_root_resolved = Path(repo_root).resolve()
+ wt_path_resolved = wt_path.resolve()
+ # utf-8-sig, not the locale default: on a cp1251/GBK Windows machine a UTF-8
+ # include list would decode to mojibake paths or raise (swallowed below),
+ # copying nothing; a Notepad BOM would glue to the first entry.
+ for line in include_file.read_text(encoding="utf-8-sig", errors="replace").splitlines():
+ entry = line.strip()
+ if not entry or entry.startswith("#"):
+ continue
+ src = Path(repo_root) / entry
+ dst = wt_path / entry
+ # Path-traversal / symlink-escape guard: both resolved endpoints must stay
+ # inside their roots before any file or symlink operation happens.
+ try:
+ src_resolved = src.resolve(strict=False)
+ dst_resolved = dst.resolve(strict=False)
+ except (OSError, ValueError):
+ logger.debug("Skipping invalid .worktreeinclude entry: %s", entry)
+ continue
+ if not _path_is_within_root(src_resolved, repo_root_resolved):
+ logger.warning("Skipping .worktreeinclude entry outside repo root: %s", entry)
+ continue
+ if not _path_is_within_root(dst_resolved, wt_path_resolved):
+ logger.warning("Skipping .worktreeinclude entry that escapes worktree: %s", entry)
+ continue
+ if src.is_file():
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(str(src), str(dst))
+ elif src.is_dir() and not dst.exists():
+ # Symlink directories (fast, no disk). Windows needs Developer Mode or
+ # elevation for symlinks — fall back to a recursive copy there.
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ os.symlink(str(src_resolved), str(dst))
+ except (OSError, NotImplementedError) as _sym_err:
+ if sys.platform != "win32":
+ raise
+ logger.info(
+ ".worktreeinclude: symlink failed (%s) — "
+ "falling back to copytree on Windows.",
+ _sym_err,
+ )
+ try:
+ shutil.copytree(
+ str(src_resolved),
+ str(dst),
+ symlinks=True,
+ dirs_exist_ok=False,
+ )
+ except Exception as _copy_err:
+ logger.warning(
+ ".worktreeinclude: copy fallback "
+ "also failed for %s -> %s: %s",
+ src, dst, _copy_err,
+ )
+ except Exception as e:
+ logger.debug("Error copying .worktreeinclude entries: %s", e)
+
+
+def _worktree_add(repo_root: str, wt_path: Path, branch_name: str, base_ref: str, base_label: str):
+ """Run ``git worktree add`` with a local-HEAD retry; returns ``(base_ref, base_label)`` or None on failure.
+
+ Any failed/timed-out attempt is swept with ``_cleanup_failed_worktree_add``
+ (git leaves a partial dir plus a lock naming THIS live pid, poisoning retries).
+ """
+ import subprocess
+
+ from hermes_cli._subprocess_compat import noninteractive_git_env
+
+ def _add(cfg):
+ # 120s, not 30: on a multi-agent box the ~10k-file materialization contends
+ # with sibling checkouts for the disk (measured 113s wall under load vs 1.2s idle).
+ return _git(
+ [*cfg, "worktree", "add", str(wt_path), "-b", branch_name, base_ref],
+ repo_root, timeout=120, stdin=subprocess.DEVNULL, env=noninteractive_git_env(),
)
+
+ # checkout.workers parallelizes file materialization (0.6s serial -> ~0.2s);
+ # unknown -c keys are ignored by older git, and the retry drops them anyway.
+ try:
+ result = _add(["-c", "checkout.workers=8", "-c", "checkout.thresholdForParallelism=100"])
if result.returncode != 0:
- # If branching from the resolved remote ref failed for any reason
- # (e.g. a partial fetch left the ref unusable), retry from local
- # HEAD so worktree creation never hard-fails on a sync hiccup.
if base_ref != "HEAD":
+ # A partial fetch can leave the remote ref unusable — retry from local
+ # HEAD so creation never hard-fails on a sync hiccup.
logger.warning(
"worktree add from %s failed (%s); retrying from local HEAD",
base_ref, result.stderr.strip(),
)
_cleanup_failed_worktree_add(repo_root, wt_path, branch_name)
base_ref, base_label = "HEAD", "HEAD (fallback — remote base failed)"
- result = subprocess.run(
- ["git", "worktree", "add", str(wt_path), "-b", branch_name, base_ref],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120, cwd=repo_root,
- stdin=subprocess.DEVNULL, env=_noninteractive_git_env(),
- )
+ result = _add([])
if result.returncode != 0:
_cleanup_failed_worktree_add(repo_root, wt_path, branch_name)
_cprint(f"\033[31m✗ Failed to create worktree: {result.stderr.strip()}\033[0m")
return None
except Exception as e:
- # A timed-out/failed `worktree add` is NOT atomic: git leaves the
- # partially-materialized directory plus a LOCKED admin entry under
- # .git/worktrees/<name> whose lock pid is THIS live process — so the
- # startup pruner's dead-pid unlock never reaps it and every retry of
- # the same name fails. Clean up our own wreckage before surfacing
- # the error (Aug 2026 incident: 30s timeout during pack-sprawl left
- # exactly this poison).
_cleanup_failed_worktree_add(repo_root, wt_path, branch_name)
_cprint(f"\033[31m✗ Failed to create worktree: {e}\033[0m")
return None
+ return base_ref, base_label
- # Copy files listed in .worktreeinclude (gitignored files the agent needs)
- include_file = Path(repo_root) / ".worktreeinclude"
- if include_file.exists():
- try:
- repo_root_resolved = Path(repo_root).resolve()
- wt_path_resolved = wt_path.resolve()
- # utf-8-sig, not the locale default: on a cp1251/GBK Windows
- # machine a UTF-8 include list either decodes to mojibake paths
- # (entries silently not copied) or raises UnicodeDecodeError,
- # which the enclosing handler swallows at DEBUG — no include is
- # copied at all. A Notepad BOM likewise glued to the first entry.
- for line in include_file.read_text(
- encoding="utf-8-sig", errors="replace"
- ).splitlines():
- entry = line.strip()
- if not entry or entry.startswith("#"):
- continue
- src = Path(repo_root) / entry
- dst = wt_path / entry
- # Prevent path traversal and symlink escapes: both the resolved
- # source and the resolved destination must stay inside their
- # expected roots before any file or symlink operation happens.
- try:
- src_resolved = src.resolve(strict=False)
- dst_resolved = dst.resolve(strict=False)
- except (OSError, ValueError):
- logger.debug("Skipping invalid .worktreeinclude entry: %s", entry)
- continue
- if not _path_is_within_root(src_resolved, repo_root_resolved):
- logger.warning("Skipping .worktreeinclude entry outside repo root: %s", entry)
- continue
- if not _path_is_within_root(dst_resolved, wt_path_resolved):
- logger.warning("Skipping .worktreeinclude entry that escapes worktree: %s", entry)
- continue
- if src.is_file():
- dst.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(str(src), str(dst))
- elif src.is_dir():
- # Symlink directories (faster, saves disk). On Windows,
- # symlink creation requires Developer Mode or elevation,
- # and fails with OSError otherwise — fall back to a
- # recursive copy so the worktree is still usable. The
- # copy is slower and uses disk, but it doesn't require
- # admin and matches the Linux/macOS symlink outcome
- # functionally.
- if not dst.exists():
- dst.parent.mkdir(parents=True, exist_ok=True)
- try:
- os.symlink(str(src_resolved), str(dst))
- except (OSError, NotImplementedError) as _sym_err:
- if sys.platform == "win32":
- logger.info(
- ".worktreeinclude: symlink failed (%s) — "
- "falling back to copytree on Windows.",
- _sym_err,
- )
- try:
- shutil.copytree(
- str(src_resolved),
- str(dst),
- symlinks=True,
- dirs_exist_ok=False,
- )
- except Exception as _copy_err:
- logger.warning(
- ".worktreeinclude: copy fallback "
- "also failed for %s -> %s: %s",
- src, dst, _copy_err,
- )
- else:
- raise
- except Exception as e:
- logger.debug("Error copying .worktreeinclude entries: %s", e)
- # Lock the worktree so other processes (and `git worktree remove`) can see
- # it is actively in use. Fail-soft: a lock failure never blocks the session.
+def _setup_worktree(repo_root: str = None, sync_base: bool = True,
+ name: Optional[str] = None) -> Optional[Dict[str, str]]:
+ """Create an isolated git worktree for this CLI session.
+
+ Returns ``{path, branch, repo_root, base}`` on success, None on failure.
+ *sync_base* branches from the freshly-fetched remote tip (see
+ ``_resolve_worktree_base``); ``worktree_sync: false`` branches from local HEAD.
+ *name* (``/worktree new <name>``) replaces the random ``hermes-<id>``; named
+ trees skip the ``hermes-`` prefix so the pruner ages them on its slower schedule.
+ """
+ repo_root = repo_root or _git_repo_root()
+ if not repo_root:
+ _cprint("\033[31m✗ --worktree requires being inside a git repository.\033[0m")
+ print(" cd into your project repo first, then run hermes -w")
+ return None
+
+ wt_name = f"hermes-{uuid.uuid4().hex[:8]}"
+ if name:
+ wt_name = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-._")[:40] or wt_name
+ branch_name = f"hermes/{wt_name}"
+
+ worktrees_dir = Path(repo_root) / ".worktrees"
+ worktrees_dir.mkdir(parents=True, exist_ok=True)
+
+ wt_path = worktrees_dir / wt_name
+ if name and wt_path.exists():
+ _cprint(f"\033[31m✗ Worktree already exists: {wt_path}\033[0m")
+ print(" Pick a different name, or remove it with: "
+ f"git worktree remove {wt_path}")
+ return None
+
+ _ensure_worktrees_gitignored(repo_root)
+
+ if sync_base:
+ base_ref, base_label = _resolve_worktree_base(repo_root)
+ else:
+ base_ref, base_label = "HEAD", "HEAD (local — worktree_sync disabled)"
+
+ added = _worktree_add(repo_root, wt_path, branch_name, base_ref, base_label)
+ if added is None:
+ return None
+ base_ref, base_label = added
+
+ _copy_worktree_includes(repo_root, wt_path)
+
+ # Lock so other processes (and `git worktree remove`) see it is in use. Fail-soft.
try:
- subprocess.run(
- ["git", "worktree", "lock", "--reason", f"hermes pid={os.getpid()}", str(wt_path)],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, cwd=repo_root,
- )
+ _git(["worktree", "lock", "--reason", f"hermes pid={os.getpid()}", str(wt_path)], repo_root)
logger.debug("Worktree locked: %s (pid=%s)", wt_path, os.getpid())
except Exception as e:
logger.debug("git worktree lock failed (non-fatal): %s", e)
- info = {
+ _cprint(f"\033[32m✓ Worktree created:\033[0m {wt_path}")
+ print(f" Branch: {branch_name}")
+ print(f" Base: {base_label}")
+
+ return {
"path": str(wt_path),
"branch": branch_name,
"repo_root": repo_root,
"base": base_ref,
}
- _cprint(f"\033[32m✓ Worktree created:\033[0m {wt_path}")
- print(f" Branch: {branch_name}")
- print(f" Base: {base_label}")
-
- return info
-
def _worktree_has_unpushed_commits(worktree_path: str, timeout: int = 10) -> bool:
"""Return whether a worktree has commits not reachable from any remote branch.
- ``git log HEAD --not --remotes`` compares against remote-tracking refs under
- ``refs/remotes/*``. If a repo has no remote-tracking refs yet, there is no
- usable remote baseline to compare against, so treat it as having no
- "unpushed" commits.
-
- SHALLOW-CLONE CAVEAT: in a shallow clone (the installer default) the
- shallow boundary can disconnect an older worktree HEAD from origin/*,
- making already-public commits look unpushed. The verdict here stays
- conservative (True) on purpose — deleting on unverifiable history would
- risk real work. Callers that can afford it should deepen first via
- ``_deepen_shallow_repo`` (the startup pruner does) or check
- ``_repo_is_shallow`` before presenting this verdict as fact.
+ No remote-tracking refs at all means no usable baseline -> False. Fails SAFE
+ toward True. SHALLOW-CLONE CAVEAT: the shallow boundary can disconnect an older
+ HEAD from origin/*, making public commits look unpushed; callers that can afford
+ it should ``_deepen_shallow_repo`` first (the startup pruner does).
"""
- import subprocess
-
try:
- remote_refs = subprocess.run(
- ["git", "for-each-ref", "--format=%(refname)", "refs/remotes"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
+ remote_refs = _git(["for-each-ref", "--format=%(refname)", "refs/remotes"], worktree_path, timeout=timeout)
if remote_refs.returncode != 0:
return True
if not remote_refs.stdout.strip():
return False
- result = subprocess.run(
- ["git", "log", "--oneline", "HEAD", "--not", "--remotes"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
+ result = _git(["log", "--oneline", "HEAD", "--not", "--remotes"], worktree_path, timeout=timeout)
if result.returncode != 0:
return True
return bool(result.stdout.strip())
@@ -2075,19 +1959,9 @@ def _worktree_has_unpushed_commits(worktree_path: str, timeout: int = 10) -> boo
def _worktree_is_dirty(worktree_path: str, timeout: int = 10) -> bool:
- """Return whether a worktree has uncommitted changes (staged, unstaged, or
- untracked).
-
- Fails SAFE: on any error returns True so callers do not delete a worktree
- whose state they cannot determine.
- """
- import subprocess
-
+ """Whether a worktree has staged/unstaged/untracked changes. Fails SAFE toward True."""
try:
- result = subprocess.run(
- ["git", "status", "--porcelain"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
+ result = _git(["status", "--porcelain"], worktree_path, timeout=timeout)
if result.returncode != 0:
return True
return bool(result.stdout.strip())
@@ -2096,43 +1970,25 @@ def _worktree_is_dirty(worktree_path: str, timeout: int = 10) -> bool:
def _repo_is_shallow(repo_path: str, timeout: int = 5) -> bool:
- """Return whether *repo_path* belongs to a shallow clone.
-
- Shallowness poisons every history-connectivity verdict the worktree
- machinery relies on: an older worktree's HEAD (a past snapshot of main)
- is disconnected from current ``origin/main`` by the shallow boundary, so
- ``git log HEAD --not --remotes`` misreports thousands of already-public
- commits as "unpushed" and the worktree is preserved forever. The default
- installer clones with ``--depth 1``, so this is the normal state of a
- user install, not an edge case.
-
- Fails toward False: if git can't be queried we don't want callers to
- take shallow-specific branches on top of an unknown state.
- """
- import subprocess
+ """Whether *repo_path* is a shallow clone (the installer default, ``--depth 1``).
+ Shallowness poisons every history-connectivity verdict: an older worktree HEAD is
+ disconnected from ``origin/main`` so its commits misreport as unpushed forever.
+ Fails toward False so callers don't take shallow-specific branches on unknown state.
+ """
try:
- result = subprocess.run(
- ["git", "rev-parse", "--is-shallow-repository"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=repo_path,
- )
+ result = _git(["rev-parse", "--is-shallow-repository"], repo_path, timeout=timeout)
return result.returncode == 0 and result.stdout.strip() == "true"
except Exception:
return False
def _deepen_shallow_repo(repo_root: str, timeout: int = 600) -> bool:
- """One-time blobless unshallow so history-based verdicts become correct.
-
- Fetches the full commit/tree graph (``--unshallow --filter=blob:none``)
- without downloading historical file contents, which keeps the transfer a
- small fraction of a full clone. Runs only from background paths (the
- startup pruner thread), never on the interactive session-close path.
+ """One-time blobless unshallow (``--unshallow --filter=blob:none``) so history verdicts are correct.
- Falls back to a plain ``--unshallow`` if the server rejects partial-clone
- filters. Fail-soft: returns whether the repo is actually non-shallow
- afterwards; on failure (offline, no remote) callers keep today's
- preserve-everything behavior.
+ Fetches the commit/tree graph without historical blobs; falls back to a plain
+ ``--unshallow`` if the server rejects filters. Background paths only. Returns
+ whether the repo is non-shallow afterwards; on failure callers keep preserving.
"""
import subprocess
@@ -2140,10 +1996,7 @@ def _deepen_shallow_repo(repo_root: str, timeout: int = 600) -> bool:
return True
try:
- remotes = subprocess.run(
- ["git", "remote"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, cwd=repo_root,
- )
+ remotes = _git(["remote"], repo_root)
names = [r.strip() for r in remotes.stdout.splitlines() if r.strip()]
if remotes.returncode != 0 or not names:
return False
@@ -2151,10 +2004,7 @@ def _deepen_shallow_repo(repo_root: str, timeout: int = 600) -> bool:
for extra in (["--filter=blob:none"], []):
try:
- result = subprocess.run(
- ["git", "fetch", remote, "--unshallow", *extra],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=repo_root,
- )
+ result = _git(["fetch", remote, "--unshallow", *extra], repo_root, timeout=timeout)
except subprocess.TimeoutExpired:
return False
if result.returncode == 0:
@@ -2177,9 +2027,7 @@ def _deepen_shallow_repo(repo_root: str, timeout: int = 600) -> bool:
return deepened
-# Upper bound on retained `git cherry` verdict entries (see
-# _save_worktree_merge_cache). Each entry is ~90 bytes, so this caps the cache
-# near 90 KB even on a repo that churns thousands of worktree branches.
+# Upper bound on retained `git cherry` verdict entries (~90 bytes each -> ~90 KB cap).
_WORKTREE_MERGE_CACHE_MAX = 1000
@@ -2201,17 +2049,12 @@ def _load_worktree_merge_cache() -> Dict[str, bool]:
entries = raw.get("verdicts")
if not isinstance(entries, dict):
return {}
- # Only keep well-formed bool verdicts — a hand-edited or partially written
- # cache must never inject a non-bool into the prune decision.
+ # A hand-edited or partially written cache must never inject a non-bool verdict.
return {k: v for k, v in entries.items() if isinstance(v, bool)}
def _save_worktree_merge_cache(verdicts: Dict[str, bool]) -> None:
- """Persist the verdict cache atomically. Best-effort — never raises.
-
- Bounded to the most recent ``_WORKTREE_MERGE_CACHE_MAX`` entries so the
- file can't grow without limit across thousands of sessions.
- """
+ """Persist the verdict cache atomically, bounded to the newest ``_WORKTREE_MERGE_CACHE_MAX``. Never raises."""
path = _worktree_merge_cache_path()
tmp = None
try:
@@ -2240,38 +2083,20 @@ def _worktree_commits_all_merged_upstream(
max_ahead: int = 20,
cache: Optional[Dict[str, bool]] = None,
) -> bool:
- """Return whether every local-only commit is patch-equivalent to a commit
- already on the default upstream branch.
-
- The dominant ``.worktrees/`` leak: a branch is pushed, its PR is
- squash-merged (or cherry-picked), and the remote branch is deleted. The
- local commits are then unreachable from ``refs/remotes/*`` forever, so the
- unpushed-commits guard preserves the worktree indefinitely even though its
- content is fully merged. ``git cherry`` detects patch-equivalence, letting
- the pruner reap these.
-
- Bounded: skips (returns False) when the branch is more than ``max_ahead``
- commits ahead — a stale-base tree, too expensive to diff-hash and unlikely
- to be a merged scratch branch. Fails SAFE toward False (preserve).
-
- ``git cherry`` diff-hashes every commit in the range, which on a large repo
- costs ~0.2-1.0s per worktree — and a tree preserved for unpushed work is
- re-tested on *every* startup, forever, always reaching the same answer. When
- *cache* is provided, the verdict is memoized against
- ``(base_sha, head_sha, max_ahead)``: the exact inputs ``git cherry``
- consumes. A cache hit is therefore identical to recomputation by
- construction — if either ref moves the key changes and the real git call
- runs again.
- """
- import subprocess
+ """Whether every local-only commit is patch-equivalent (``git cherry``) to an upstream commit.
+
+ Catches the dominant ``.worktrees/`` leak: a squash-merged/cherry-picked PR whose
+ remote branch was deleted leaves local commits unreachable from ``refs/remotes/*``
+ forever. Returns False (preserve) when more than *max_ahead* commits ahead — a
+ stale-base tree, too expensive to diff-hash. Fails SAFE toward False.
+ *cache* memoizes the verdict on ``(base_sha, head_sha, max_ahead)`` — the exact
+ inputs ``git cherry`` consumes, so a hit is identical to recomputation.
+ """
base = None
for candidate in ("origin/HEAD", "origin/main", "origin/master"):
try:
- probe = subprocess.run(
- ["git", "rev-parse", "--verify", "--quiet", candidate],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
+ probe = _git(["rev-parse", "--verify", "--quiet", candidate], worktree_path, timeout=timeout)
if probe.returncode == 0 and probe.stdout.strip():
base = candidate
break
@@ -2281,15 +2106,9 @@ def _worktree_commits_all_merged_upstream(
return False
try:
- # Resolve both endpoints to shas up front. These are the complete
- # inputs to the range below, so they form an exact cache key. Cheap
- # (~1ms) relative to the diff-hashing `git cherry` they guard.
cache_key = None
if cache is not None:
- revs = subprocess.run(
- ["git", "rev-parse", f"{base}^{{commit}}", "HEAD^{commit}"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
+ revs = _git(["rev-parse", f"{base}^{{commit}}", "HEAD^{commit}"], worktree_path, timeout=timeout)
if revs.returncode == 0:
shas = revs.stdout.split()
if len(shas) == 2:
@@ -2302,10 +2121,7 @@ def _worktree_commits_all_merged_upstream(
cache[cache_key] = verdict
return verdict
- ahead = subprocess.run(
- ["git", "rev-list", "--count", f"{base}..HEAD"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
+ ahead = _git(["rev-list", "--count", f"{base}..HEAD"], worktree_path, timeout=timeout)
if ahead.returncode != 0:
return False
count = int(ahead.stdout.strip() or "0")
@@ -2314,10 +2130,7 @@ def _worktree_commits_all_merged_upstream(
if count > max_ahead:
return _memo(False)
- cherry = subprocess.run(
- ["git", "cherry", base, "HEAD"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
+ cherry = _git(["cherry", base, "HEAD"], worktree_path, timeout=timeout)
if cherry.returncode != 0:
return False
lines = [ln for ln in cherry.stdout.splitlines() if ln.strip()]
@@ -2327,53 +2140,45 @@ def _worktree_commits_all_merged_upstream(
return False
+def _worktree_current_branch(worktree_path: str, timeout: int) -> Optional[str]:
+ """Checked-out branch name, or None when detached or git fails. May raise on subprocess errors."""
+ head = _git(["rev-parse", "--abbrev-ref", "HEAD"], worktree_path, timeout=timeout)
+ if head.returncode != 0:
+ return None
+ branch = head.stdout.strip()
+ if not branch or branch == "HEAD": # detached
+ return None
+ return branch
+
+
def _worktree_branch_pr_merged(
worktree_path: str,
timeout: int = 15,
cache: Optional[Dict[str, bool]] = None,
) -> bool:
- """Return whether the worktree branch's PR is MERGED on GitHub.
-
- Escape hatch for the case ``git cherry`` cannot catch: a rebase-merge that
- altered the diff (conflict resolution against a moved base, follow-up
- commits added during salvage/CI-fix) changes the patch-id, so the local
- commits are no longer patch-equivalent to anything upstream even though
- the PR merged. Those trees survive the cherry check forever (Aug 2026:
- 12 of 22 "unpushed" trees on a loaded box had MERGED PRs).
-
- GitHub's PR state is the authoritative merge signal, so a clean tree
- whose branch has a MERGED PR is reaped. Verdicts are memoized keyed on
- ``(branch, head_sha)`` — MERGED is monotonic, so a True verdict is cached
- permanently; False is never cached (the PR may merge later without new
- local commits, which would leave the key unchanged).
-
- Fails SAFE toward False (preserve): no gh binary, offline, rate-limited,
- detached HEAD, or any parse failure keeps the tree.
- """
- import subprocess
+ """Whether the worktree branch's PR is MERGED on GitHub (``gh pr list``).
+ Escape hatch for what ``git cherry`` cannot catch: a rebase-merge that altered the
+ diff changes the patch-id, so merged trees survive the cherry check forever.
+ Verdicts are memoized on ``(branch, head_sha)``; MERGED is monotonic so only True
+ is cached (the PR may merge later without new local commits).
+ Fails SAFE toward False: no gh, offline, rate-limited, detached, parse failure.
+ """
try:
- head = subprocess.run(
- ["git", "rev-parse", "--abbrev-ref", "HEAD"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
- if head.returncode != 0:
- return False
- branch = head.stdout.strip()
- if not branch or branch == "HEAD": # detached — no PR to look up
+ branch = _worktree_current_branch(worktree_path, timeout)
+ if branch is None:
return False
cache_key = None
if cache is not None:
- sha = subprocess.run(
- ["git", "rev-parse", "HEAD"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
+ sha = _git(["rev-parse", "HEAD"], worktree_path, timeout=timeout)
if sha.returncode == 0 and sha.stdout.strip():
cache_key = f"pr-merged:{branch}:{sha.stdout.strip()}"
if cache.get(cache_key) is True:
return True
+ import subprocess
+
result = subprocess.run(
["gh", "pr", "list", "--head", branch, "--state", "merged",
"--json", "number", "--limit", "1"],
@@ -2391,27 +2196,15 @@ def _worktree_branch_pr_merged(
def _fetch_remote_branch_heads(repo_root: str, timeout: int = 20) -> Optional[Dict[str, str]]:
- """Return ``{branch_name: sha}`` for every branch on origin, or None.
-
- One ``git ls-remote --heads origin`` call answers "is this branch pushed?"
- for EVERY worktree in the sweep, so callers pay a single bounded network
- round-trip instead of per-tree probes. Needed because managed installs
- fetch with a single-branch refspec (``+refs/heads/main:...``), so
- ``refs/remotes/origin/<branch>`` never exists for pushed PR branches and
- ``git log HEAD --not --remotes`` misreports them as unpushed forever —
- the dominant reason open-PR worktrees accumulate (Aug 2026: 24 of 33
- preserved trees on a loaded box were pushed branches with open PRs).
-
- Fails SAFE toward None (offline, no remote, timeout): callers must treat
- None as "cannot verify — preserve".
- """
- import subprocess
+ """Return ``{branch_name: sha}`` for every branch on origin (one ``ls-remote``), or None.
+ Managed installs fetch a single-branch refspec, so ``refs/remotes/origin/<branch>``
+ never exists for pushed PR branches and they read as unpushed forever; one bounded
+ network round-trip answers "is this branch pushed?" for the whole sweep.
+ Fails SAFE toward None — callers must treat None as "cannot verify — preserve".
+ """
try:
- result = subprocess.run(
- ["git", "ls-remote", "--heads", "origin"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=repo_root,
- )
+ result = _git(["ls-remote", "--heads", "origin"], repo_root, timeout=timeout)
if result.returncode != 0:
return None
heads: Dict[str, str] = {}
@@ -2429,39 +2222,24 @@ def _worktree_branch_pushed_exact(
remote_heads: Optional[Dict[str, str]],
timeout: int = 10,
) -> bool:
- """Return whether the worktree's branch head is EXACTLY what origin holds.
+ """Whether the worktree's branch head is EXACTLY what origin holds.
- True means the working tree contains nothing origin doesn't already have:
- the checkout is redundant — the work lives on the remote (typically as an
- open PR) and in the local branch ref. Reaping the TREE while keeping the
- BRANCH loses nothing and is one ``git worktree add`` away from undone.
-
- Exact-match is deliberately the only True case: a local head that is
- ahead of (or diverged from) the pushed branch has commits origin lacks,
- and without remote-tracking refs we cannot cheaply prove ancestry — so
- anything but equality fails SAFE toward preserve.
+ True means the checkout is redundant — the work lives on the remote (typically an
+ open PR) and in the local branch ref, so reaping the TREE while keeping the BRANCH
+ loses nothing. Exact match is deliberately the only True case: a head ahead of or
+ diverged from origin has commits origin lacks, and without remote-tracking refs
+ ancestry can't be proven cheaply — anything but equality fails SAFE toward preserve.
"""
- import subprocess
-
if not remote_heads:
return False
try:
- head = subprocess.run(
- ["git", "rev-parse", "--abbrev-ref", "HEAD"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
- if head.returncode != 0:
- return False
- branch = head.stdout.strip()
- if not branch or branch == "HEAD":
+ branch = _worktree_current_branch(worktree_path, timeout)
+ if branch is None:
return False
remote_sha = remote_heads.get(branch)
if not remote_sha:
return False
- local = subprocess.run(
- ["git", "rev-parse", "HEAD"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=worktree_path,
- )
+ local = _git(["rev-parse", "HEAD"], worktree_path, timeout=timeout)
if local.returncode != 0:
return False
return local.stdout.strip() == remote_sha
@@ -2470,31 +2248,15 @@ def _worktree_branch_pushed_exact(
def _worktree_lock_is_live(repo_root: str, worktree_path: str, timeout: int = 10):
- """Classify a worktree's git lock as live, dead, or absent.
-
- ``hermes -w`` locks each worktree with reason ``hermes pid=<pid>`` so a
- concurrent hermes process' startup prune leaves an in-use worktree alone.
- But a *crashed* session leaves the lock behind forever, and
- ``git worktree remove --force`` (single ``-f``) refuses to remove a locked
- worktree — so dead-locked worktrees accumulate indefinitely. This lets the
- pruner tell the two apart:
-
- - ``"live"`` — locked and the owning pid is still running (skip it).
- - ``"dead"`` — locked but the owning pid is gone, or the reason isn't a
- parseable hermes lock (safe to unlock + reap).
- - ``None`` — not locked at all.
-
- Fails SAFE toward ``"live"``: if git can't be queried at all we cannot
- prove the worktree is safe to touch, so we report it as live.
- """
- import re
- import subprocess
+ """Classify a worktree's git lock: ``"live"`` (owning pid running — skip), ``"dead"``
+ (pid gone or a non-hermes lock reason — safe to unlock + reap), or None (unlocked).
+ ``hermes -w`` locks with reason ``hermes pid=<pid>``; a crashed session leaves the
+ lock forever and ``worktree remove --force`` refuses locked trees, so dead-locked
+ worktrees would accumulate indefinitely. Fails SAFE toward ``"live"``.
+ """
try:
- result = subprocess.run(
- ["git", "worktree", "list", "--porcelain"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=repo_root,
- )
+ result = _git(["worktree", "list", "--porcelain"], repo_root, timeout=timeout)
if result.returncode != 0:
return "live"
except Exception:
@@ -2514,9 +2276,7 @@ def _worktree_lock_is_live(repo_root: str, worktree_path: str, timeout: int = 10
reason = line[len("locked"):].strip()
m = re.search(r"hermes pid=(\d+)", reason)
if not m:
- # Locked by something we don't recognize as a hermes session
- # (or lock reason unavailable). Treat as dead — a foreign lock
- # on a hermes -w worktree is almost certainly a leftover, and
+ # A foreign lock on a hermes -w worktree is almost certainly a leftover;
# the age/dirty/unpushed gates already ran before we got here.
return "dead"
pid = int(m.group(1))
@@ -2526,7 +2286,6 @@ def _worktree_lock_is_live(repo_root: str, worktree_path: str, timeout: int = 10
from gateway.status import _pid_exists
return "live" if _pid_exists(pid) else "dead"
except Exception:
- # Can't determine liveness — fail safe toward keeping it.
return "live"
return None
@@ -2534,18 +2293,14 @@ def _worktree_lock_is_live(repo_root: str, worktree_path: str, timeout: int = 10
def _cleanup_worktree(info: Dict[str, str] = None) -> None:
"""Remove a worktree and its branch on exit.
- Preserves the worktree only if it has unpushed commits (real work
- that hasn't been pushed to any remote). Uncommitted changes alone
- (untracked files, test artifacts) are not enough to keep it — agent
- work lives in commits/PRs, not the working tree.
+ Preserved only when it has unpushed commits (real work). Uncommitted changes alone
+ are not enough — agent work lives in commits/PRs, not the working tree.
"""
global _active_worktree
info = info or _active_worktree
if not info:
return
- import subprocess
-
wt_path = info["path"]
branch = info["branch"]
repo_root = info["repo_root"]
@@ -2553,15 +2308,10 @@ def _cleanup_worktree(info: Dict[str, str] = None) -> None:
if not Path(wt_path).exists():
return
- has_unpushed = _worktree_has_unpushed_commits(wt_path, timeout=10)
-
- if has_unpushed:
+ if _worktree_has_unpushed_commits(wt_path, timeout=10):
if _repo_is_shallow(repo_root):
- # In a shallow clone the unpushed verdict is unreliable: the
- # shallow boundary disconnects this worktree's history from
- # origin/*, so already-public commits look "unpushed". Be honest
- # about why we're keeping it — the startup pruner deepens the
- # clone in the background and will reap it on a later startup.
+ # The shallow boundary makes the unpushed verdict unreliable; the startup
+ # pruner deepens the clone in the background and reaps it later.
_cprint(f"\n\033[33m⚠ Shallow clone — cannot verify push state, keeping: {wt_path}\033[0m")
print(" The next `hermes -w` session deepens the clone and prunes merged worktrees automatically.")
else:
@@ -2570,49 +2320,20 @@ def _cleanup_worktree(info: Dict[str, str] = None) -> None:
_active_worktree = None
return
- # Remove worktree (even if working tree is dirty — uncommitted
- # changes without unpushed commits are just artifacts)
- # Unlock first so `git worktree remove` isn't blocked by the lock we
- # placed at creation time. Fail-soft — never block cleanup.
- try:
- subprocess.run(
- ["git", "worktree", "unlock", wt_path],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, cwd=repo_root,
- )
- except Exception as e:
- logger.debug("git worktree unlock failed (non-fatal): %s", e)
-
- try:
- subprocess.run(
- ["git", "worktree", "remove", wt_path, "--force"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15, cwd=repo_root,
- )
- except Exception as e:
- logger.debug("Failed to remove worktree: %s", e)
-
- # Delete the branch
- try:
- subprocess.run(
- ["git", "branch", "-D", branch],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, cwd=repo_root,
- )
- except Exception as e:
- logger.debug("Failed to delete branch %s: %s", branch, e)
+ # Unlock first so `remove` isn't blocked by the lock placed at creation. Fail-soft.
+ _git_quiet(["worktree", "unlock", wt_path], repo_root, log="git worktree unlock failed (non-fatal)")
+ _git_quiet(["worktree", "remove", wt_path, "--force"], repo_root, timeout=15, log="Failed to remove worktree")
+ _git_quiet(["branch", "-D", branch], repo_root, log=f"Failed to delete branch {branch}")
_active_worktree = None
_cprint(f"\033[32m✓ Worktree cleaned up: {wt_path}\033[0m")
def _run_state_db_auto_maintenance(session_db) -> None:
- """Call ``SessionDB.maybe_auto_prune_and_vacuum`` using current config.
-
- Reads the ``sessions:`` section from config.yaml via
- :func:`hermes_cli.config.load_config` (the authoritative loader that
- deep-merges DEFAULT_CONFIG, so unmigrated configs still get default
- values). Honours ``auto_prune`` / ``retention_days`` /
- ``vacuum_after_prune`` / ``min_vacuum_interval_days`` /
- ``min_interval_hours``, and delegates to the DB. Never raises —
- maintenance must never block interactive startup.
+ """Run one-time repairs + ``SessionDB.maybe_auto_prune_and_vacuum`` per the ``sessions:`` config.
+
+ Uses :func:`hermes_cli.config.load_config` (deep-merges DEFAULT_CONFIG so unmigrated
+ configs still get defaults). Never raises — maintenance must never block startup.
"""
if session_db is None:
return
@@ -2633,7 +2354,7 @@ def _run_state_db_auto_maintenance(session_db) -> None:
except Exception as _prune_exc:
logger.debug("Ghost session prune skipped: %s", _prune_exc)
- # One-time finalize of orphaned compression continuations (#20001).
+ # One-time finalize of orphaned compression continuations.
try:
if not session_db.get_meta("orphaned_compression_finalize_v1"):
finalized = session_db.finalize_orphaned_compression_sessions()
@@ -2647,9 +2368,8 @@ def _run_state_db_auto_maintenance(session_db) -> None:
cfg = (_load_full_config().get("sessions") or {})
- # Auto-archive (soft-hide stale sessions) is independent of the
- # destructive auto_prune sweep — run it first, before prune's early
- # return, so enabling one doesn't require the other.
+ # Auto-archive is independent of the destructive auto_prune sweep — run it
+ # first, before prune's early return.
if cfg.get("auto_archive", False):
session_db.maybe_auto_archive(
idle_days=float(cfg.get("auto_archive_days", 3)),
@@ -2670,24 +2390,16 @@ def _run_state_db_auto_maintenance(session_db) -> None:
def _run_checkpoint_auto_maintenance() -> None:
- """Call ``checkpoint_manager.maybe_auto_prune_checkpoints`` using current config.
-
- Reads the ``checkpoints:`` section from config.yaml via
- :func:`hermes_cli.config.load_config`. Honours ``auto_prune`` /
- ``retention_days`` / ``delete_orphans`` / ``min_interval_hours``.
- Never raises — maintenance must never block interactive startup.
- """
+ """Call ``maybe_auto_prune_checkpoints`` per the ``checkpoints:`` config. Never raises."""
try:
from hermes_cli.config import load_config as _load_full_config
cfg = (_load_full_config().get("checkpoints") or {})
if not cfg.get("auto_prune", False):
return
from tools.checkpoint_manager import maybe_auto_prune_checkpoints
- # delete_orphans is intentionally never honoured here: a missing
- # workdir at startup is ambiguous (deleted project vs. an unmounted
- # external volume / network share / VPN not yet up) and this sweep
- # runs unattended. Orphan cleanup is only ever done via the explicit
- # `hermes checkpoints prune` command, which the user has to invoke.
+ # delete_orphans is never honoured here: a missing workdir at startup is
+ # ambiguous (deleted project vs. unmounted volume / VPN not yet up) and this
+ # sweep runs unattended. Orphans are only reclaimed by `hermes checkpoints prune`.
maybe_auto_prune_checkpoints(
retention_days=int(cfg.get("retention_days", 7)),
min_interval_hours=int(cfg.get("min_interval_hours", 24)),
@@ -2698,134 +2410,46 @@ def _run_checkpoint_auto_maintenance() -> None:
logger.debug("checkpoint auto-maintenance skipped: %s", exc)
-def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
- """Remove stale worktrees and orphaned branches on startup.
+def _prune_candidates(worktrees_dir: Path, max_age_hours: int, now: float) -> list:
+ """Phase 1 — stat-only age filter: ``[(entry, mtime, force)]`` for trees past their soft cutoff.
- Covers EVERY directory under ``.worktrees/`` except kanban task trees
- (``t_<hex>`` — owned by the kanban dispatcher's own gc). Scratch trees
- created by ``hermes -w`` (``hermes-*``) age out fast; named trees created
- manually for salvage/review lanes age out on a slower schedule:
-
- - ``hermes-*``: skip under 24h; reap 24h+ when clean and merged/pushed;
- 72h+ is the aggressive tier (still never deletes real work).
- - named trees: same logic at 3x the timeline (72h soft / 9d hard).
-
- Work-preservation guards (all tiers, any age):
- - uncommitted changes (dirty) — never removed;
- - unpushed commits — never removed, UNLESS every local-only commit is
- patch-equivalent to a commit already on upstream (``git cherry``): the
- squash-merged-PR case, which is the dominant ``.worktrees/`` leak since
- those commits stay unreachable from ``refs/remotes/*`` forever;
- - pushed-branch tier: when the tree's branch head EXACTLY matches what
- origin holds (one ``git ls-remote`` per sweep, lazily), the checkout is
- redundant — typically an open-PR lane. The TREE is reaped but its
- BRANCH ref is kept (and shielded from the orphaned-branch pass), so
- the lane is one ``git worktree add`` away from restored. Needed because
- managed installs fetch with a single-branch refspec, leaving pushed PR
- branches with no ``refs/remotes/*`` entry — they read as "unpushed"
- forever and were the dominant survivor class (Aug 2026: 24 of 33
- preserved trees, ~18GB).
-
- Lock handling (orthogonal to age): ``hermes -w`` locks each worktree with
- reason ``hermes pid=<pid>`` so a concurrent hermes process leaves an in-use
- worktree alone. A *live*-locked worktree is skipped at any age; a
- *dead*-locked one (owning pid gone — a crashed session) is unlocked first
- so ``git worktree remove --force`` can actually reap it, otherwise those
- leftovers accumulate forever (``remove --force`` refuses a locked tree).
-
- Branch deletion is gated on ``git worktree remove`` succeeding, so a failed
- removal never orphans the branch (which would drop easy reachability of any
- commits still in the worktree).
-
- Preserved-work visibility: trees skipped for unpushed/dirty reasons that
- are older than 7 days are listed in a single WARNING so real in-flight
- work can't rot silently.
-
- Also prunes orphaned ``hermes/*`` and ``pr-*`` local branches that
- have no corresponding worktree.
-
- Performance: this runs on the startup path of every ``hermes -w`` session,
- and each candidate tree costs several git subprocesses (the ``git cherry``
- patch-equivalence probe dominates at ~0.2-1.0s on a large repo). With
- dozens of accumulated worktrees the serial version added ~11-18s of latency
- before the banner. Two changes keep the decisions byte-identical while
- removing nearly all of that:
-
- 1. The read-only classification of each tree (dirty / unpushed / merged /
- lock state) is independent per tree, so it runs on a thread pool. Only
- the mutating phase (unlock, remove, branch -D) stays serial and ordered.
- 2. ``git cherry`` verdicts are memoized on disk keyed by the exact
- ``(base_sha, head_sha)`` range they were computed from, so a tree
- preserved for unpushed work is not re-diff-hashed on every subsequent
- startup.
+ Kanban task trees (``t_<hex>``) are owned by the kanban dispatcher's gc and skipped.
+ Scratch trees (``hermes-*``) age on *max_age_hours*; named trees (salvage/review
+ lanes created deliberately) get 3x. *force* marks the hard (3x) tier.
"""
- import re
- import subprocess
- import time
-
- worktrees_dir = Path(repo_root) / ".worktrees"
- if not worktrees_dir.exists():
- _prune_orphaned_branches(repo_root)
- return
-
- # A shallow clone (the installer's default `--depth 1`) disconnects old
- # worktree HEADs from current origin/main, so the unpushed-commits guard
- # misclassifies every aged worktree as unpushed work and preserves it
- # forever. Deepen once — bloblessly, in this background thread — so all
- # history verdicts below (and the session-exit cleanup) become correct.
- # Fail-soft: offline, we just keep today's preserve-everything behavior.
- if _repo_is_shallow(repo_root):
- _deepen_shallow_repo(repo_root)
-
- now = time.time()
- stale_work_cutoff = now - (7 * 24 * 3600)
- preserved_stale: list = []
- # Kanban task worktrees (<repo>/.worktrees/t_<hex>) have their own
- # dispatcher-driven lifecycle (hermes kanban gc) — never touch them here.
kanban_re = re.compile(r"^t_[0-9a-f]+$")
-
- # ── Phase 1: age filter (no subprocesses) ───────────────────────────────
- # Cheap stat-only pass so the thread pool below is sized to the trees that
- # actually need git work, not to everything on disk.
candidates: list = []
for entry in sorted(worktrees_dir.iterdir()):
if not entry.is_dir() or kanban_re.match(entry.name):
continue
-
- # Scratch trees (hermes-*) age out on the default schedule; named
- # trees (salvage/review lanes someone created deliberately) get 3x.
- scratch = entry.name.startswith("hermes-")
- tier_hours = max_age_hours if scratch else max_age_hours * 3
+ tier_hours = max_age_hours if entry.name.startswith("hermes-") else max_age_hours * 3
soft_cutoff = now - (tier_hours * 3600)
hard_cutoff = now - (tier_hours * 3 * 3600)
-
try:
mtime = entry.stat().st_mtime
if mtime > soft_cutoff:
continue # Too recent — skip
except Exception:
continue
-
candidates.append((entry, mtime, mtime <= hard_cutoff))
+ return candidates
- if not candidates:
- _prune_orphaned_branches(repo_root)
- return
- # ── Phase 2: classify in parallel (read-only git queries) ───────────────
- # Every check here is a read-only git query against a distinct worktree, so
- # they are safe to run concurrently (git takes no repo-wide lock for these,
- # and each has its own index). Verdicts are collected and applied serially
- # below so removal order and log output stay deterministic.
+def _classify_prune_candidates(repo_root: str, candidates: list) -> list:
+ """Phase 2 — read-only git classification of every candidate, in parallel.
+
+ Returns ``[(entry, mtime, force, verdict, lock_state)]`` with verdict in
+ ``dirty`` / ``unpushed`` / ``locked-live`` / ``reap`` / ``reap-keep-branch``.
+ Each check is a read-only query against a distinct worktree (no repo-wide lock),
+ so a bounded thread pool is safe; the mutating phase stays serial. ``git cherry``
+ verdicts are memoized on disk (see ``_worktree_commits_all_merged_upstream``).
+ """
merge_cache = _load_worktree_merge_cache()
cache_size_before = len(merge_cache)
cache_lock = threading.Lock()
- # Lazy, once-per-sweep ls-remote: answers "is this branch pushed as-is?"
- # for every tree. Only paid when some tree actually reaches the
- # pushed-tier check (the TUI path runs this pruner synchronously, so an
- # unconditional network call would tax every launch; offline it costs
- # one bounded timeout at most, and None degrades verdicts to preserve).
+ # Lazy, once-per-sweep ls-remote — only paid when some tree reaches the pushed-tier
+ # check (the TUI runs this pruner synchronously; offline costs one bounded timeout).
_remote_heads_memo: dict = {}
_remote_heads_lock = threading.Lock()
@@ -2839,58 +2463,40 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
def _classify(item):
entry, mtime, force = item
- # Never delete real work, regardless of age or tier. Uncommitted
- # changes and unpushed commits may be a crashed session's in-flight
- # work; only clean, fully-merged/pushed trees (the scratch trees that
- # actually cause .worktrees/ bloat) are ever reaped.
+ # Never delete real work regardless of age: only clean, fully merged/pushed trees are reaped.
if _worktree_is_dirty(str(entry), timeout=5):
return (entry, mtime, force, "dirty", None)
keep_branch = False
if _worktree_has_unpushed_commits(str(entry), timeout=5):
- # Squash-merge escape hatch: commits unreachable from any remote
- # ref but patch-equivalent to upstream commits are merged work,
- # not unpushed work.
+ # Squash-merge escape hatch: patch-equivalent commits are merged, not unpushed.
with cache_lock:
snapshot = dict(merge_cache)
merged = _worktree_commits_all_merged_upstream(
str(entry), timeout=30, cache=snapshot
)
if not merged:
- # Rebase-merge escape hatch: conflict resolution or follow-up
- # commits change the patch-id, so cherry misses them — but
- # GitHub knows the PR merged. Authoritative and cheap (~0.3s,
- # memoized on (branch, head_sha) so it's paid once per tree).
+ # Rebase-merge escape hatch: cherry misses changed patch-ids, GitHub knows.
merged = _worktree_branch_pr_merged(
str(entry), timeout=15, cache=snapshot
)
with cache_lock:
merge_cache.update(snapshot)
if not merged:
- # Pushed-branch tier: single-branch fetch refspecs (the
- # managed-install default) leave pushed PR branches with no
- # refs/remotes/* entry, so they read as "unpushed" forever
- # even though every byte is on origin. When the local head
- # EXACTLY matches the remote branch, the checkout is
- # redundant: reap the tree, keep the branch ref so the lane
- # is one `git worktree add` from restored.
+ # Pushed-branch tier: head EXACTLY matches origin -> the checkout is
+ # redundant; reap the tree, keep the branch ref (open-PR lane anchor).
if _worktree_branch_pushed_exact(str(entry), _get_remote_heads(), timeout=10):
keep_branch = True
else:
return (entry, mtime, force, "unpushed", None)
- # Respect git-native session locks. A lock owned by a still-running
- # hermes process means the worktree is actively in use — never touch
- # it. A lock whose owning pid is gone is a crashed session's leftover:
- # unlock it so `git worktree remove --force` (single -f) can reap it,
- # otherwise dead-locked worktrees pile up indefinitely.
+ # A live-locked tree is in use by a running hermes; a dead lock is unlocked in phase 3.
lock_state = _worktree_lock_is_live(repo_root, str(entry), timeout=5)
if lock_state == "live":
return (entry, mtime, force, "locked-live", None)
return (entry, mtime, force,
"reap-keep-branch" if keep_branch else "reap", lock_state)
- # Bounded pool: enough to hide git's per-process startup latency without
- # spawning dozens of concurrent git processes on a small machine.
+ # Enough workers to hide git's per-process startup latency without dozens of gits.
workers = max(1, min(8, (os.cpu_count() or 4), len(candidates)))
try:
if workers > 1:
@@ -2901,16 +2507,23 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
else:
verdicts = [_classify(c) for c in candidates]
except Exception as e:
- # Never let a pool failure block startup — fall back to serial.
logger.debug("Parallel worktree classification failed (%s); serial", e)
verdicts = [_classify(c) for c in candidates]
if len(merge_cache) != cache_size_before:
_save_worktree_merge_cache(merge_cache)
+ return verdicts
+
- # ── Phase 3: mutate serially (unlock / remove / branch -D) ──────────────
- # Branch refs deliberately preserved by the pushed tier — must survive
- # the orphaned-branch pass even though their worktree is now gone.
+def _reap_prune_verdicts(repo_root: str, verdicts: list, stale_work_cutoff: float) -> tuple[list, set]:
+ """Phase 3 — serial unlock / remove / branch -D.
+
+ Returns ``(preserved_stale, kept_branches)``: trees preserved for dirty/unpushed work
+ older than the cutoff (reported once), and branch refs the pushed tier kept on
+ purpose (must survive the orphaned-branch pass). Branch deletion is gated on
+ ``worktree remove`` succeeding so a failed removal never orphans reachable commits.
+ """
+ preserved_stale: list = []
kept_branches: set = set()
for entry, mtime, force, verdict, lock_state in verdicts:
if verdict == "dirty":
@@ -2926,49 +2539,62 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
continue
if lock_state == "dead":
- try:
- subprocess.run(
- ["git", "worktree", "unlock", str(entry)],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, cwd=repo_root,
- )
- except Exception as e:
- logger.debug("Failed to unlock dead worktree %s: %s", entry.name, e)
+ _git_quiet(["worktree", "unlock", str(entry)], repo_root,
+ log=f"Failed to unlock dead worktree {entry.name}")
- # Safe to remove
try:
- branch_result = subprocess.run(
- ["git", "branch", "--show-current"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, cwd=str(entry),
- )
- branch = branch_result.stdout.strip()
-
- remove_result = subprocess.run(
- ["git", "worktree", "remove", str(entry), "--force"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15, cwd=repo_root,
- )
+ branch = _git(["branch", "--show-current"], str(entry), timeout=5).stdout.strip()
+ remove_result = _git(["worktree", "remove", str(entry), "--force"], repo_root, timeout=15)
if remove_result.returncode != 0:
- # Removal failed — keep the branch so any commits stay
- # reachable rather than orphaning it.
logger.debug(
"Failed to remove worktree %s: %s",
entry.name, remove_result.stderr.strip(),
)
continue
if branch and verdict == "reap-keep-branch":
- # Pushed-tier trees keep their branch ref: the branch IS the
- # work (an open PR's local anchor) — only the checkout was
- # redundant. Also shield it from the orphaned-branch pass
- # below, which would otherwise delete hermes/*- and pr-*
- # named refs the moment their worktree is gone.
kept_branches.add(branch)
elif branch:
- subprocess.run(
- ["git", "branch", "-D", branch],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, cwd=repo_root,
- )
+ _git(["branch", "-D", branch], repo_root)
logger.debug("Pruned stale worktree: %s (force=%s)", entry.name, force)
except Exception as e:
logger.debug("Failed to prune worktree %s: %s", entry.name, e)
+ return preserved_stale, kept_branches
+
+
+def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
+ """Remove stale worktrees and orphaned branches on startup.
+
+ Covers every directory under ``.worktrees/`` except kanban task trees. Tiers:
+ ``hermes-*`` skip under 24h, reap 24h+ when clean and merged/pushed, 72h+ is the
+ aggressive tier (still never deletes real work); named trees run at 3x.
+
+ Work-preservation guards (all tiers, any age): dirty trees are never removed;
+ unpushed commits are never removed UNLESS patch-equivalent to upstream (squash-merge
+ case), the PR is MERGED on GitHub, or the branch head EXACTLY matches origin (pushed
+ tier — tree reaped, branch ref kept and shielded from the orphaned-branch pass).
+ Live-locked trees are skipped at any age; dead-locked ones are unlocked first.
+ Trees preserved for >7 days are listed in one WARNING so in-flight work can't rot
+ silently. Phases: ``_prune_candidates`` -> ``_classify_prune_candidates`` (parallel,
+ read-only) -> ``_reap_prune_verdicts`` (serial) -> ``_prune_orphaned_branches``.
+ """
+ worktrees_dir = Path(repo_root) / ".worktrees"
+ if not worktrees_dir.exists():
+ _prune_orphaned_branches(repo_root)
+ return
+
+ # A shallow clone disconnects old worktree HEADs from origin/main, so every aged
+ # tree would read as unpushed forever. Deepen once (blobless, fail-soft).
+ if _repo_is_shallow(repo_root):
+ _deepen_shallow_repo(repo_root)
+
+ now = time.time()
+ candidates = _prune_candidates(worktrees_dir, max_age_hours, now)
+ if not candidates:
+ _prune_orphaned_branches(repo_root)
+ return
+
+ verdicts = _classify_prune_candidates(repo_root, candidates)
+ preserved_stale, kept_branches = _reap_prune_verdicts(repo_root, verdicts, now - (7 * 24 * 3600))
if preserved_stale:
logger.warning(
@@ -2979,11 +2605,8 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
_prune_orphaned_branches(repo_root, protect=kept_branches)
- # Escalation notice: the startup pass is deliberately conservative, so
- # installs accumulate preserved trees it can never reclaim. Once the
- # footprint is clearly a problem (many trees or multi-GB), say so once
- # per launch and name the attended reclaim command — silence here is how
- # boxes reach 15GB+ of .worktrees/ without anyone noticing.
+ # Escalation notice: the startup pass is conservative, so installs accumulate
+ # preserved trees it can never reclaim — say so once per launch past a threshold.
try:
from hermes_cli.worktree_gc import worktrees_summary
@@ -3002,35 +2625,21 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
def _prune_orphaned_branches(repo_root: str, protect: Optional[set] = None) -> None:
"""Delete local ``hermes/hermes-*`` and ``pr-*`` branches with no worktree.
- These are auto-generated by ``hermes -w`` sessions and PR review
- workflows respectively. Once their worktree is gone they serve no
- purpose and just accumulate.
-
- ``protect``: branch names to never delete this pass — the pushed-tier
- reap above removes a tree while deliberately keeping its branch (an open
- PR's local anchor), and some of those carry ``hermes/hermes-*`` names
- this sweep would otherwise collect immediately.
+ *protect*: branch names never deleted this pass — the pushed-tier reap removes a
+ tree while deliberately keeping its branch (an open PR's local anchor).
"""
- import subprocess
-
try:
- result = subprocess.run(
- ["git", "branch", "--format=%(refname:short)"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, cwd=repo_root,
- )
+ result = _git(["branch", "--format=%(refname:short)"], repo_root)
if result.returncode != 0:
return
all_branches = [b.strip() for b in result.stdout.strip().split("\n") if b.strip()]
except Exception:
return
- # Collect branches that are actively checked out in a worktree
+ # Branches actively checked out in a worktree
active_branches: set = set()
try:
- wt_result = subprocess.run(
- ["git", "worktree", "list", "--porcelain"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, cwd=repo_root,
- )
+ wt_result = _git(["worktree", "list", "--porcelain"], repo_root)
for line in wt_result.stdout.split("\n"):
if line.startswith("branch refs/heads/"):
active_branches.add(line.split("branch refs/heads/", 1)[-1].strip())
@@ -3039,11 +2648,7 @@ def _prune_orphaned_branches(repo_root: str, protect: Optional[set] = None) -> N
# Also protect the currently checked-out branch and main
try:
- head_result = subprocess.run(
- ["git", "branch", "--show-current"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, cwd=repo_root,
- )
- current = head_result.stdout.strip()
+ current = _git(["branch", "--show-current"], repo_root, timeout=5).stdout.strip()
if current:
active_branches.add(current)
except Exception:
@@ -3060,16 +2665,9 @@ def _prune_orphaned_branches(repo_root: str, protect: Optional[set] = None) -> N
if not orphaned:
return
- # Delete in batches
for i in range(0, len(orphaned), 50):
- batch = orphaned[i:i + 50]
- try:
- subprocess.run(
- ["git", "branch", "-D"] + batch,
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30, cwd=repo_root,
- )
- except Exception as e:
- logger.debug("Failed to prune orphaned branches: %s", e)
+ _git_quiet(["branch", "-D"] + orphaned[i:i + 50], repo_root, timeout=30,
+ log="Failed to prune orphaned branches")
logger.debug("Pruned %d orphaned branches", len(orphaned))