The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(worktree): judge no-remote repos against the local trunk instead of reaping everything
teknium10a3e792942b7
diff --git a/hermes_cli/worktree_gc.py b/hermes_cli/worktree_gc.pyindex 232f2bf2a54..e8c3c0cf627 100644--- a/hermes_cli/worktree_gc.py+++ b/hermes_cli/worktree_gc.py@@ -329,10 +329,11 @@ def audit_branches(repo_root: str) -> List[BranchRecord]:def _lines(result) -> List[str]:return [b.strip() for b in result.stdout.splitlines() if b.strip()]- upstream = next(- (c for c in ("origin/HEAD", "origin/main", "origin/master")- if _git(["rev-parse", "--verify", "--quiet", c], cwd=repo_root, timeout=5).returncode == 0),- None)+ # No remote at all -> the local trunk; no trunk either -> nothing can be judged, report nothing.+ try:+ upstream = _ops._worktree_merge_base_ref(repo_root)+ except Exception:+ upstream = Noneif upstream is None:return []diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.pyindex 26d1d6d0b47..096a49b8be3 100644--- a/hermes_cli/worktree_ops.py+++ b/hermes_cli/worktree_ops.py@@ -367,19 +367,60 @@ def _setup_worktree(repo_root: str = None, sync_base: bool = True,return {"path": str(wt_path), "branch": branch_name, "repo_root": repo_root, "base": base_ref}+_REMOTE_TRUNK_CANDIDATES = ("origin/HEAD", "origin/main", "origin/master")+_LOCAL_TRUNK_CANDIDATES = ("main", "master")+++def _worktree_local_trunk(path: str, timeout: float = 5) -> Optional[str]:+ """Local trunk of a repo with NO remote-tracking refs: ``main``/``master``, else the branch+ checked out in the main worktree. None = no baseline at all; callers must preserve.++ Nothing in such a repo was ever pushed, so "merged into the local trunk" is the only fact+ that can tell redundant scratch work from unique commits. May raise like ``_git``.+ """+ for name in _LOCAL_TRUNK_CANDIDATES:+ if _git_out(["rev-parse", "--verify", "--quiet", f"refs/heads/{name}"], path, timeout=timeout):+ return name+ porcelain = _git_out(["worktree", "list", "--porcelain"], path, timeout=timeout) or ""+ for line in porcelain.split("\n\n", 1)[0].splitlines(): # first block = the main worktree+ if line.startswith("branch refs/heads/"):+ return line[len("branch refs/heads/"):].strip() or None+ return None+++def _worktree_merge_base_ref(path: str, timeout: float = 5) -> Optional[str]:+ """Ref merged work is judged against: ``origin/HEAD``/``origin/main``/``origin/master``, or the+ local trunk when the repo has no remote-tracking refs at all. None = nothing to compare+ against -> every consumer must preserve. May raise like ``_git``.+ """+ for cand in _REMOTE_TRUNK_CANDIDATES:+ if _git_out(["rev-parse", "--verify", "--quiet", cand], path, timeout=timeout):+ return cand+ if _git_out(["for-each-ref", "--format=%(refname)", "refs/remotes"], path, timeout=timeout) == "":+ return _worktree_local_trunk(path, timeout=timeout)+ return None++def _worktree_has_unpushed_commits(worktree_path: str, timeout: int = 10) -> bool:"""Whether a worktree has commits unreachable from any remote branch. Fails SAFE toward True.- No remote-tracking refs = no baseline -> True: without a reachable upstream, cleanup cannot- prove that local commits are redundant. A shallow boundary can disconnect an older HEAD from- origin/* so public commits look unpushed; ``_deepen_shallow_repo`` first if affordable.+ No remote-tracking refs = nothing was ever pushed, so the tree is compared against the local+ trunk instead (``_worktree_local_trunk``); no trunk either -> True. A shallow boundary can+ disconnect an older HEAD from origin/* so public commits look unpushed;+ ``_deepen_shallow_repo`` first if affordable."""try:remote_refs = _git_out(["for-each-ref", "--format=%(refname)", "refs/remotes"], worktree_path,timeout=timeout)+ if remote_refs is None:+ return True+ baseline = ["--remotes"]if not remote_refs:- return True # no remote-tracking refs: no baseline can prove local work was pushed- unpushed = _git_out(["log", "--oneline", "HEAD", "--not", "--remotes"], worktree_path,+ trunk = _worktree_local_trunk(worktree_path, timeout=timeout)+ if trunk is None:+ return True+ baseline = [trunk]+ unpushed = _git_out(["log", "--oneline", "HEAD", "--not", *baseline], worktree_path,timeout=timeout)return unpushed is None or bool(unpushed)except Exception:@@ -473,13 +514,12 @@ def _worktree_commits_all_merged_upstream("""Whether every local-only commit is patch-equivalent (``git cherry``) to upstream. Fails SAFE -> False.Catches squash-merged/cherry-picked PRs whose remote branch was deleted (commits unreachable- from ``refs/remotes/*`` forever). More than *max_ahead* ahead = stale-base tree -> False.+ from ``refs/remotes/*`` forever). Upstream is ``_worktree_merge_base_ref`` (the local trunk in+ a repo without remotes). More than *max_ahead* ahead = stale-base tree -> False.*cache* memoizes on ``(base_sha, head_sha, max_ahead)``, exactly what ``git cherry`` consumes."""try:- base = next((c for c in ("origin/HEAD", "origin/main", "origin/master")- if _git_out(["rev-parse", "--verify", "--quiet", c], worktree_path, timeout=timeout)),- None)+ base = _worktree_merge_base_ref(worktree_path, timeout=timeout)if base is None:return Falsediff --git a/tests/hermes_cli/test_worktree.py b/tests/hermes_cli/test_worktree.pyindex d7bb2a148dc..b1ba38e380d 100644--- a/tests/hermes_cli/test_worktree.py+++ b/tests/hermes_cli/test_worktree.py@@ -1015,7 +1015,8 @@ class TestWidenedPruner:def test_merged_predicate_fails_safe_without_upstream(self, git_repo_no_remote):- import cli+ """No remote: the local trunk is the baseline (a tree at trunk IS merged). No trunk at+ all — detached main checkout, no main/master — leaves nothing to compare against -> False."""repo = git_repo_no_remotep = repo / ".worktrees" / "hermes-noremote"(repo / ".worktrees").mkdir(exist_ok=True)@@ -1023,7 +1024,15 @@ class TestWidenedPruner:["git", "worktree", "add", str(p), "-b", "wt/noremote", "HEAD"],cwd=repo, capture_output=True,)+ assert worktree_ops._worktree_commits_all_merged_upstream(str(p)) is True++ trunk = subprocess.run(["git", "branch", "--show-current"], cwd=repo, capture_output=True,+ text=True).stdout.strip()+ subprocess.run(["git", "checkout", "-q", "--detach"], cwd=repo, capture_output=True)+ subprocess.run(["git", "branch", "-m", trunk, "scratch/not-a-trunk"], cwd=repo, capture_output=True)+ assert worktree_ops._worktree_merge_base_ref(str(p)) is Noneassert worktree_ops._worktree_commits_all_merged_upstream(str(p)) is False+ assert worktree_ops._worktree_has_unpushed_commits(str(p)) is True# -- preserved-work warning ----------------------------------------------diff --git a/tests/hermes_cli/test_worktree_gc.py b/tests/hermes_cli/test_worktree_gc.pyindex 1844fbfd72f..7ec95b84643 100644--- a/tests/hermes_cli/test_worktree_gc.py+++ b/tests/hermes_cli/test_worktree_gc.py@@ -61,6 +61,20 @@ def repo(tmp_path, monkeypatch):return clone+def local_repo(tmp_path, monkeypatch):+ """``git init`` repo with NO remote at all (the #111895 shape), HOME redirected."""+ monkeypatch.setenv("HOME", str(tmp_path / "home"))+ (tmp_path / "home").mkdir()+ repo = tmp_path / "local-repo"+ _git(["init", "-b", "main", str(repo)], tmp_path)+ (repo / "README.md").write_text("hello\n")+ _git(["add", "."], repo)+ _git(["commit", "-m", "init"], repo)+ (repo / ".worktrees").mkdir()+ return repo++def _add_worktree(repo_path, name, branch=None):tree = repo_path / ".worktrees" / namebranch = branch or f"hermes/{name}"@@ -106,17 +120,8 @@ class TestAuditVerdicts:assert record.verdict == "keep"assert "unpushed" in record.reason- def test_unique_commits_without_a_remote_keep_tree_and_branch(self, tmp_path, monkeypatch):- """No remote means there is no baseline that can prove local work is merged."""- monkeypatch.setenv("HOME", str(tmp_path / "home"))- (tmp_path / "home").mkdir()- local_repo = tmp_path / "local-repo"- _git(["init", "-b", "main", str(local_repo)], tmp_path)- (local_repo / "README.md").write_text("hello\n")- _git(["add", "."], local_repo)- _git(["commit", "-m", "init"], local_repo)- (local_repo / ".worktrees").mkdir()-+ def test_unique_commits_without_a_remote_keep_tree_and_branch(self, local_repo):+ """No remote: unique commits are judged against the local trunk, never "merged/pushed"."""tree, branch = _add_worktree(local_repo, "hermes-local-work")(tree / "new.py").write_text("x = 1\n")_git(["add", "."], tree)@@ -130,6 +135,36 @@ class TestAuditVerdicts:assert tree.exists()assert _git(["rev-parse", "--verify", branch], local_repo)+ def test_without_a_remote_local_trunk_is_the_baseline(self, local_repo):+ """Control for the no-remote guard: work merged into the local ``main`` still reclaims+ (tree and squash-merged branch), while a branch holding unique commits — with or without+ a worktree — is reported and kept by the branch audit instead of vanishing."""+ clean_tree, _ = _add_worktree(local_repo, "hermes-clean")+ squashed_tree, _ = _add_worktree(local_repo, "hermes-squashed")+ (squashed_tree / "k.py").write_text("k = 1\n")+ _git(["add", "."], squashed_tree)+ _git(["commit", "-m", "squash me"], squashed_tree)+ _git(["merge", "--squash", "hermes/hermes-squashed"], local_repo)+ _git(["commit", "-m", "squash merge"], local_repo)+ _git(["branch", "orphan-unique", "main"], local_repo)+ _git(["checkout", "-q", "orphan-unique"], local_repo)+ (local_repo / "o.py").write_text("o = 1\n")+ _git(["add", "."], local_repo)+ _git(["commit", "-m", "unique, no worktree"], local_repo)+ _git(["checkout", "-q", "main"], local_repo)++ records = worktree_gc.audit_worktrees(str(local_repo), with_sizes=False)+ assert _verdict(records, "hermes-clean").verdict == "reap"+ assert _verdict(records, "hermes-squashed").verdict == "reap"+ worktree_gc.reclaim_worktrees(str(local_repo), records=records)+ assert not clean_tree.exists() and not squashed_tree.exists()++ by_name = {b.name: b for b in worktree_gc.audit_branches(str(local_repo))}+ assert by_name["orphan-unique"].verdict == "keep"+ assert "unique" in by_name["orphan-unique"].reason+ assert by_name["main"].verdict == "keep"+ assert "hermes/hermes-squashed" not in by_name # branch -D ran only on merged work+def test_patch_equivalent_commits_reap(self, repo):"""The squash/rebase-merge leak: local commit unreachable from anyremote ref but patch-equivalent to an upstream commit → merged work."""diff --git a/website/docs/user-guide/cli.md b/website/docs/user-guide/cli.mdindex 03aa91025be..957635189d0 100644--- a/website/docs/user-guide/cli.md+++ b/website/docs/user-guide/cli.md@@ -93,6 +93,11 @@ 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.+- **Repositories without a remote** are judged against the local trunk+ (`main`/`master`, else the branch checked out in the main worktree): only+ trees and branches whose commits are reachable from — or patch-equivalent+ to — that trunk are reclaimed. With no trunk to compare against, every tree+ and branch is preserved.- **Pushed open-PR lanes free their disk without losing anything**: when aclean tree's branch head exactly matches what `origin` holds (checked withone `git ls-remote` per sweep), the checkout is redundant — the tree is