The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(worktree): pushed open-PR lanes reclaim their disk; cron tick prunes worktrees
Teknium3a351a966549
diff --git a/cli.py b/cli.pyindex 256e3b23e08..916d0c1e1a2 100644--- a/cli.py+++ b/cli.py@@ -2392,6 +2392,85 @@ def _worktree_branch_pr_merged(return False+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++ try:+ result = subprocess.run(+ ["git", "ls-remote", "--heads", "origin"],+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, cwd=repo_root,+ )+ if result.returncode != 0:+ return None+ heads: Dict[str, str] = {}+ for line in result.stdout.splitlines():+ parts = line.split("\t", 1)+ if len(parts) == 2 and parts[1].startswith("refs/heads/"):+ heads[parts[1][len("refs/heads/"):].strip()] = parts[0].strip()+ return heads+ except Exception:+ return None+++def _worktree_branch_pushed_exact(+ worktree_path: str,+ remote_heads: Optional[Dict[str, str]],+ timeout: int = 10,+) -> bool:+ """Return 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.+ """+ 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":+ 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,+ )+ if local.returncode != 0:+ return False+ return local.stdout.strip() == remote_sha+ except Exception:+ return False++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.@@ -2638,7 +2717,16 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:- unpushed commits — never removed, UNLESS every local-only commit ispatch-equivalent to a commit already on upstream (``git cherry``): thesquash-merged-PR case, which is the dominant ``.worktrees/`` leak since- those commits stay unreachable from ``refs/remotes/*`` forever.+ 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 withreason ``hermes pid=<pid>`` so a concurrent hermes process leaves an in-use@@ -2735,6 +2823,22 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None: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).+ _remote_heads_memo: dict = {}+ _remote_heads_lock = threading.Lock()++ def _get_remote_heads():+ with _remote_heads_lock:+ if "heads" not in _remote_heads_memo:+ _remote_heads_memo["heads"] = _fetch_remote_branch_heads(+ repo_root, timeout=10+ )+ return _remote_heads_memo["heads"]+def _classify(item):entry, mtime, force = item# Never delete real work, regardless of age or tier. Uncommitted@@ -2743,6 +2847,7 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:# actually cause .worktrees/ bloat) are ever reaped.if _worktree_is_dirty(str(entry), timeout=5):return (entry, mtime, force, "dirty", None)+ keep_branch = Falseif _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,@@ -2763,7 +2868,17 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:with cache_lock:merge_cache.update(snapshot)if not merged:- return (entry, mtime, force, "unpushed", None)+ # 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.+ 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@@ -2773,7 +2888,8 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None: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", lock_state)+ 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.@@ -2795,6 +2911,9 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:_save_worktree_merge_cache(merge_cache)# ── 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.+ kept_branches: set = set()for entry, mtime, force, verdict, lock_state in verdicts:if verdict == "dirty":if mtime <= stale_work_cutoff:@@ -2837,7 +2956,14 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:entry.name, remove_result.stderr.strip(),)continue- if branch:+ 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,@@ -2853,7 +2979,7 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:len(preserved_stale), ", ".join(sorted(preserved_stale)),)- _prune_orphaned_branches(repo_root)+ _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@@ -2875,12 +3001,17 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:pass-def _prune_orphaned_branches(repo_root: str) -> 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 reviewworkflows respectively. Once their worktree is gone they serve nopurpose 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."""import subprocess@@ -2924,6 +3055,7 @@ def _prune_orphaned_branches(repo_root: str) -> None:orphaned = [b for b in all_branchesif b not in active_branches+ and b not in (protect or ())and (b.startswith("hermes/hermes-") or b.startswith("pr-"))]diff --git a/cron/scheduler.py b/cron/scheduler.pyindex bf7985eb4ec..22595d0412e 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -7808,6 +7808,102 @@ def create_job_with_scheduler_registration(**kwargs) -> dict:_DEAD_OWNER_REAP_INTERVAL_SECONDS = 300.0_last_dead_owner_reap_at: Optional[float] = None+# Worktree maintenance throttle: the startup pruner historically ran only on+# `hermes -w` launches, so on gateway-driven boxes (where sessions arrive via+# Telegram/Discord and nobody launches the CLI for days) merged scratch trees+# accumulated into tens of GB. The cron tick is the one reliably periodic+# process on every install, so it owns a low-frequency sweep too. Tests may+# reset _last_worktree_maintenance_at to None to force a sweep next tick.+_WORKTREE_MAINTENANCE_INTERVAL_SECONDS = 6 * 3600.0+_last_worktree_maintenance_at: Optional[float] = None+_worktree_maintenance_lock = threading.Lock()+++def _worktree_maintenance_repos() -> List[str]:+ """Repos whose ``.worktrees/`` this scheduler should keep pruned.++ Candidates: the hermes install checkout itself (where ``hermes -w``+ sessions on dev boxes create trees) and every configured job workdir's+ repo root. Only repos that actually have a ``.worktrees/`` dir survive —+ everything else costs nothing.+ """+ repos: set = set()++ # The hermes source checkout (editable/git installs). Wheel installs have+ # no .git here and are skipped.+ try:+ install_root = Path(__file__).resolve().parent.parent+ if (install_root / ".git").exists():+ repos.add(str(install_root))+ except Exception:+ pass++ # Job workdirs may point inside other repos the agent works on.+ try:+ from cron.jobs import load_jobs++ for job in load_jobs():+ workdir = str(job.get("workdir") or "").strip()+ if not workdir or not Path(workdir).is_dir():+ continue+ try:+ probe = subprocess.run(+ ["git", "rev-parse", "--show-toplevel"],+ capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=5, cwd=workdir,+ )+ if probe.returncode == 0 and probe.stdout.strip():+ repos.add(probe.stdout.strip())+ except Exception:+ continue+ except Exception:+ pass++ return [r for r in sorted(repos) if (Path(r) / ".worktrees").is_dir()]+++def _maybe_run_worktree_maintenance() -> None:+ """Throttled, threaded worktree prune from the cron tick.++ Runs ``cli._prune_stale_worktrees`` (the same conservative pruner the+ ``hermes -w`` startup path uses — dirty/unpushed/live-locked trees are+ never touched) against every candidate repo, on a daemon thread so the+ tick itself never waits on git. Errors never propagate: worktree GC is+ hygiene, not scheduling.+ """+ global _last_worktree_maintenance_at+ now = time.monotonic()+ with _worktree_maintenance_lock:+ if (+ _last_worktree_maintenance_at is not None+ and now - _last_worktree_maintenance_at+ < _WORKTREE_MAINTENANCE_INTERVAL_SECONDS+ ):+ return+ _last_worktree_maintenance_at = now++ def _run() -> None:+ try:+ repos = _worktree_maintenance_repos()+ if not repos:+ return+ from cli import _prune_stale_worktrees++ for repo in repos:+ try:+ _prune_stale_worktrees(repo)+ except Exception:+ logger.debug(+ "Cron worktree maintenance failed for %s", repo,+ exc_info=True,+ )+ except Exception:+ logger.debug("Cron worktree maintenance skipped", exc_info=True)++ threading.Thread(+ target=_run, name="cron-worktree-prune", daemon=True+ ).start()+def tick(verbose: bool = True,@@ -7926,6 +8022,14 @@ def tick(except Exception as _reap_exc:logger.debug("Dead-owner execution reclaim failed: %s", _reap_exc)+ # Periodic worktree GC (throttled to every 6h, threaded): gateway-only+ # boxes never hit the `hermes -w` startup pruner, so this is the only+ # sweep they get. Same conservative pruner, same guards.+ try:+ _maybe_run_worktree_maintenance()+ except Exception as _wt_exc:+ logger.debug("Worktree maintenance dispatch failed: %s", _wt_exc)+due_jobs = get_due_jobs()# Bound the in-flight set BEFORE the dedup guard is consulted, so adiff --git a/hermes_cli/worktree_gc.py b/hermes_cli/worktree_gc.pyindex bfb863c8690..13fb195b9f0 100644--- a/hermes_cli/worktree_gc.py+++ b/hermes_cli/worktree_gc.py@@ -181,6 +181,10 @@ def audit_worktrees(repo_root: str, *, with_sizes: bool = True) -> List[TreeRecomerge_cache = _cli._load_worktree_merge_cache()cache_size_before = len(merge_cache)+ # One ls-remote resolves "is this branch pushed as-is?" for the whole+ # sweep. None (offline) degrades every pushed-tier verdict to keep.+ remote_heads = _cli._fetch_remote_branch_heads(repo_root)+now = time.time()records: List[TreeRecord] = []for entry in sorted(worktrees_dir.iterdir()):@@ -226,6 +230,24 @@ def audit_worktrees(repo_root: str, *, with_sizes: bool = True) -> List[TreeRecomax_ahead=_MAX_CHERRY_AHEAD,)if not merged:+ # Pushed-branch tier: single-branch fetch refspecs (the+ # managed-install default) leave pushed PR branches with no+ # refs/remotes/* entry, so `git log HEAD --not --remotes`+ # reads them as unpushed forever. A local head that EXACTLY+ # matches the remote branch has nothing origin lacks — the+ # checkout is redundant; only the branch ref stays.+ if _cli._worktree_branch_pushed_exact(+ str(entry), remote_heads, timeout=10+ ):+ if untracked:+ rec("reap-keep-branch",+ f"pushed to origin (open-PR lane); branch kept; "+ f"{len(untracked)} untracked file(s) will be archived",+ untracked)+ else:+ rec("reap-keep-branch",+ "pushed to origin (open-PR lane); branch kept")+ continuerec("keep", "unpushed commits not found upstream")continue@@ -256,15 +278,16 @@ def reclaim_worktrees(if records is None:records = audit_worktrees(repo_root, with_sizes=False)actions: List[str] = []+ _REAP_VERDICTS = {"reap", "reap-archive", "reap-keep-branch"}for record in records:- if record.verdict not in {"reap", "reap-archive"}:+ if record.verdict not in _REAP_VERDICTS:continueif dry_run:actions.append(f"would remove {record.name} ({record.reason})")continueentry = Path(record.path)- if record.verdict == "reap-archive" and record.untracked:+ if record.untracked:archive = _archive_untracked(entry, record.untracked)if archive is None:actions.append(f"kept {record.name} (archive of untracked files failed)")@@ -287,6 +310,11 @@ def reclaim_worktrees(f"failed to remove {record.name}: {remove_result.stderr.strip()}")continue+ if record.verdict == "reap-keep-branch":+ actions.append(+ f"removed {record.name} (branch {record.branch} kept — pushed open-PR lane)"+ )+ continueif record.branch and record.branch not in _PROTECTED_BRANCHES:_git(["branch", "-D", record.branch], cwd=repo_root, timeout=10)actions.append(f"removed {record.name}")diff --git a/tests/cli/test_worktree_pushed_tier.py b/tests/cli/test_worktree_pushed_tier.pynew file mode 100644index 00000000000..b7d4cc13d4d--- /dev/null+++ b/tests/cli/test_worktree_pushed_tier.py@@ -0,0 +1,294 @@+"""Pushed-branch tier of the worktree pruners (#A, Aug 2026).++Behavior contract: a clean worktree whose branch head EXACTLY matches what+origin holds (open-PR lane on a single-branch-refspec install) gets its TREE+reaped while its BRANCH ref survives — including surviving the+orphaned-branch pass. Anything not provably on origin stays preserved.++Uses a real local bare repo as `origin` so `git ls-remote`/push are genuine,+no network and no mocks.+"""++import os+import subprocess+import time++import pytest+++def _run(args, cwd):+ return subprocess.run(+ args, cwd=cwd, capture_output=True, text=True, encoding="utf-8"+ )+++def repo_with_bare_origin(tmp_path):+ """A working clone whose origin is a real local bare repo.++ Mirrors the managed-install fetch config: single-branch refspec for main+ only, so pushed side branches never gain refs/remotes/origin/<branch>+ entries — the exact condition that made the old pruner misread pushed PR+ lanes as 'unpushed'.+ """+ bare = tmp_path / "origin.git"+ bare.mkdir()+ _run(["git", "init", "--bare", "--initial-branch=main"], bare)++ repo = tmp_path / "clone"+ repo.mkdir()+ _run(["git", "init", "--initial-branch=main"], repo)+ _run(["git", "config", "user.email", "[email protected]"], repo)+ _run(["git", "config", "user.name", "Test"], repo)+ (repo / "README.md").write_text("# repo\n")+ _run(["git", "add", "."], repo)+ _run(["git", "commit", "-m", "init"], repo)+ _run(["git", "remote", "add", "origin", str(bare)], repo)+ # Managed-install shape: fetch refspec covers main ONLY.+ _run(+ ["git", "config", "remote.origin.fetch",+ "+refs/heads/main:refs/remotes/origin/main"],+ repo,+ )+ _run(["git", "push", "-u", "origin", "main"], repo)+ _run(["git", "fetch", "origin"], repo)+ return repo+++def _age(path, hours=100):+ t = time.time() - hours * 3600+ os.utime(path, (t, t))+++def _mk_worktree(repo, name, branch, commit=True, push=False, extra_commit_after_push=False):+ """Create .worktrees/<name> on <branch> with an optional pushed commit."""+ (repo / ".worktrees").mkdir(exist_ok=True)+ p = repo / ".worktrees" / name+ _run(["git", "worktree", "add", str(p), "-b", branch, "HEAD"], repo)+ if commit:+ (p / f"{name}.txt").write_text("payload\n")+ _run(["git", "add", f"{name}.txt"], p)+ _run(["git", "commit", "-m", f"work on {name}"], p)+ if push:+ # Plain push — deliberately NO refs/remotes/* tracking ref appears,+ # because the fetch refspec only covers main.+ result = _run(["git", "push", "origin", branch], p)+ assert result.returncode == 0, result.stderr+ if extra_commit_after_push:+ (p / "later.txt").write_text("post-push work\n")+ _run(["git", "add", "later.txt"], p)+ _run(["git", "commit", "-m", "post-push commit"], p)+ _age(p)+ return p+++def _branch_exists(repo, branch):+ return _run(+ ["git", "rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], repo+ ).returncode == 0+++class TestFetchRemoteBranchHeads:+ def test_lists_pushed_branches(self, repo_with_bare_origin):+ import cli+ repo = repo_with_bare_origin+ _mk_worktree(repo, "hermes-a", "hermes/hermes-a", push=True)+ heads = cli._fetch_remote_branch_heads(str(repo))+ assert heads is not None+ assert "main" in heads+ assert "hermes/hermes-a" in heads++ def test_unreachable_remote_returns_none(self, tmp_path):+ import cli+ repo = tmp_path / "r"+ repo.mkdir()+ _run(["git", "init"], repo)+ _run(["git", "remote", "add", "origin", str(tmp_path / "missing.git")], repo)+ assert cli._fetch_remote_branch_heads(str(repo)) is None+++class TestBranchPushedExact:+ def test_exact_match_true(self, repo_with_bare_origin):+ import cli+ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "hermes-x", "hermes/hermes-x", push=True)+ heads = cli._fetch_remote_branch_heads(str(repo))+ assert cli._worktree_branch_pushed_exact(str(wt), heads) is True++ def test_local_ahead_of_push_false(self, repo_with_bare_origin):+ import cli+ repo = repo_with_bare_origin+ wt = _mk_worktree(+ repo, "hermes-y", "hermes/hermes-y",+ push=True, extra_commit_after_push=True,+ )+ heads = cli._fetch_remote_branch_heads(str(repo))+ assert cli._worktree_branch_pushed_exact(str(wt), heads) is False++ def test_never_pushed_false(self, repo_with_bare_origin):+ import cli+ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "hermes-z", "hermes/hermes-z", push=False)+ heads = cli._fetch_remote_branch_heads(str(repo))+ assert cli._worktree_branch_pushed_exact(str(wt), heads) is False++ def test_none_heads_false(self, repo_with_bare_origin):+ import cli+ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "hermes-n", "hermes/hermes-n", push=True)+ assert cli._worktree_branch_pushed_exact(str(wt), None) is False+ assert cli._worktree_branch_pushed_exact(str(wt), {}) is False+++class TestStartupPrunerPushedTier:+ """cli._prune_stale_worktrees against the real repo fixture."""++ def test_pushed_lane_tree_reaped_branch_kept(self, repo_with_bare_origin):+ import cli+ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "hermes-pushed", "hermes/hermes-pushed", push=True)++ cli._prune_stale_worktrees(str(repo))++ assert not wt.exists(), (+ "pushed-as-is open-PR lane must be reaped (checkout is redundant)"+ )+ assert _branch_exists(repo, "hermes/hermes-pushed"), (+ "branch ref must survive the reap AND the orphaned-branch pass"+ )++ def test_unpushed_lane_still_preserved(self, repo_with_bare_origin):+ import cli+ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "hermes-unpushed", "hermes/hermes-unp", push=False)++ cli._prune_stale_worktrees(str(repo))++ assert wt.exists(), "never-pushed unique work must survive, any age"++ def test_ahead_of_pushed_lane_preserved(self, repo_with_bare_origin):+ import cli+ repo = repo_with_bare_origin+ wt = _mk_worktree(+ repo, "hermes-ahead", "hermes/hermes-ahead",+ push=True, extra_commit_after_push=True,+ )++ cli._prune_stale_worktrees(str(repo))++ assert wt.exists(), (+ "local commits beyond the pushed head are unpushed work — preserve"+ )++ def test_pushed_but_dirty_preserved(self, repo_with_bare_origin):+ import cli+ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "hermes-pdirty", "hermes/hermes-pdirty", push=True)+ (wt / "uncommitted.txt").write_text("in-flight\n")+ _age(wt)++ cli._prune_stale_worktrees(str(repo))++ assert wt.exists(), "dirty guard outranks the pushed tier"++ def test_offline_remote_preserves(self, repo_with_bare_origin, tmp_path):+ import cli+ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "hermes-off", "hermes/hermes-off", push=True)+ # Sever the remote AFTER pushing: ls-remote now fails -> None ->+ # pushed tier must degrade to preserve.+ _run(["git", "remote", "set-url", "origin", str(tmp_path / "gone.git")], repo)++ cli._prune_stale_worktrees(str(repo))++ assert wt.exists(), "unverifiable push state must fail toward preserve"+++class TestAttendedGcPushedTier:+ """worktree_gc audit/reclaim behavior for the pushed tier."""++ def test_audit_verdict_and_reclaim_keeps_branch(self, repo_with_bare_origin):+ import cli # noqa: F401 (worktree_gc lazily imports cli)+ from hermes_cli import worktree_gc++ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "salv-lane", "salv/pushed-lane", push=True)++ records = worktree_gc.audit_worktrees(str(repo), with_sizes=False)+ by_name = {r.name: r for r in records}+ assert by_name["salv-lane"].verdict == "reap-keep-branch"+ assert "pushed to origin" in by_name["salv-lane"].reason++ actions = worktree_gc.reclaim_worktrees(str(repo), records=records)+ assert any("salv-lane" in a and "kept" in a for a in actions)+ assert not wt.exists()+ assert _branch_exists(repo, "salv/pushed-lane")++ def test_audit_never_pushed_keeps(self, repo_with_bare_origin):+ import cli # noqa: F401+ from hermes_cli import worktree_gc++ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "salv-keep", "salv/never-pushed", push=False)++ records = worktree_gc.audit_worktrees(str(repo), with_sizes=False)+ by_name = {r.name: r for r in records}+ assert by_name["salv-keep"].verdict == "keep"+ worktree_gc.reclaim_worktrees(str(repo), records=records)+ assert wt.exists()+++class TestCronWorktreeMaintenance:+ def test_throttle_dispatches_once_per_interval(self, monkeypatch):+ import cron.scheduler as sched++ calls = []+ monkeypatch.setattr(sched, "_last_worktree_maintenance_at", None)+ monkeypatch.setattr(+ sched.threading, "Thread",+ lambda *a, **k: type("T", (), {"start": lambda self: calls.append(k.get("name"))})(),+ )++ sched._maybe_run_worktree_maintenance()+ sched._maybe_run_worktree_maintenance() # inside interval — no-op++ assert len(calls) == 1++ def test_repo_discovery_requires_worktrees_dir(self, monkeypatch, tmp_path):+ import cron.scheduler as sched++ # A job workdir inside a git repo WITHOUT .worktrees/ is filtered out.+ repo = tmp_path / "jobrepo"+ repo.mkdir()+ _run(["git", "init"], repo)+ monkeypatch.setattr(+ "cron.jobs.load_jobs",+ lambda: [{"workdir": str(repo)}],+ )+ repos = sched._worktree_maintenance_repos()+ assert str(repo) not in repos++ # Adding .worktrees/ makes it eligible.+ (repo / ".worktrees").mkdir()+ repos = sched._worktree_maintenance_repos()+ assert str(repo) in repos++ def test_maintenance_prunes_via_real_pruner(self, repo_with_bare_origin, monkeypatch):+ import cron.scheduler as sched++ repo = repo_with_bare_origin+ wt = _mk_worktree(repo, "hermes-cronreap", "hermes/hermes-cronreap", push=True)++ monkeypatch.setattr(sched, "_last_worktree_maintenance_at", None)+ monkeypatch.setattr(+ sched, "_worktree_maintenance_repos", lambda: [str(repo)]+ )++ sched._maybe_run_worktree_maintenance()+ # The sweep runs on a daemon thread — wait for it (bounded).+ deadline = time.time() + 30+ while wt.exists() and time.time() < deadline:+ time.sleep(0.2)++ assert not wt.exists(), "cron-tick maintenance must run the real pruner"+ assert _branch_exists(repo, "hermes/hermes-cronreap")diff --git a/website/docs/user-guide/cli.md b/website/docs/user-guide/cli.mdindex 36a6cedf3f8..756038b8bae 100644--- a/website/docs/user-guide/cli.md+++ b/website/docs/user-guide/cli.md@@ -84,6 +84,12 @@ Safety guarantees (all modes, any age):rebase/squash-merged upstream are detected via `git cherry`patch-equivalence and count as merged, which is what lets the dominant"merged PR, tree preserved forever" leak finally reclaim.+- **Pushed open-PR lanes free their disk without losing anything**: when a+ clean tree's branch head exactly matches what `origin` holds (checked with+ one `git ls-remote` per sweep), the checkout is redundant — the tree is+ removed but its **branch ref is kept**, so the lane is one+ `git worktree add .worktrees/<name> <branch>` away from restored. If the+ remote can't be reached, the tree is preserved.- Trees **in use by a running hermes session** are never touched.- **Untracked-only scratch** (PR body drafts, notes) is archived to`~/.hermes/archive/worktree-prune/` before its tree is removed — never@@ -92,6 +98,11 @@ Safety guarantees (all modes, any age):commits are all on upstream is safe to delete; branches with unique work,checked-out branches, and `main`/`master`/`develop` are always kept.+The same conservative pruner also runs from the cron scheduler (at most once+every 6 hours, in the background), so gateway-only machines — where nobody+launches `hermes -w` for days — no longer accumulate merged scratch trees+between CLI sessions.+When `.worktrees/` grows past 10 trees or 5 GB, startup prints a one-linenotice pointing at these commands.