Skip to content

The agent that grows with you

revert: stale worktree reaping revalidation (#132260)

kshitijk4poor05d8d0a26635
diff --git a/hermes_cli/worktree_gc.py b/hermes_cli/worktree_gc.py
index df31b873efe..5119aa1ece2 100644
--- a/hermes_cli/worktree_gc.py
+++ b/hermes_cli/worktree_gc.py
@@ -285,17 +285,8 @@ def reclaim_worktrees(
) -> List[str]:
"""Remove every reap-verdict tree from a frozen audit list — never re-globs inside the
destructive loop, so trees created by concurrent sessions after the audit are out of scope."""
- from hermes_cli import worktree_ops as _ops
- from hermes_cli._subprocess_compat import FILTER_DISCOVERY_FAILED, noninteractive_repo_git_env
-
if records is None:
records = audit_worktrees(repo_root, with_sizes=False)
- # The cache only memoizes revalidation's `git cherry`; dry runs never revalidate.
- merge_cache = {} if dry_run else _ops._load_worktree_merge_cache()
- cache_size_before = len(merge_cache)
- remote_heads = (
- _ops._fetch_remote_branch_heads(repo_root)
- if not dry_run and any(r.verdict == "reap-keep-branch" for r in records) else None)
actions: List[str] = []
for record in records:
if record.verdict not in _REAP_VERDICTS:
@@ -305,22 +296,6 @@ def reclaim_worktrees(
continue
entry = Path(record.path)
- # The frozen list bounds membership, not authority to discard later work.
- # Another session may have changed a tree while earlier records were archived.
- try:
- verdict, reason, untracked = _classify_tree(
- _ops, repo_root, entry, merge_cache, remote_heads)
- branch = _git(["branch", "--show-current"], cwd=record.path, timeout=5)
- changed = ("verdict" if verdict != record.verdict
- else "untracked files" if untracked != record.untracked
- else "branch" if branch.returncode != 0 or branch.stdout.strip() != record.branch
- else "")
- if changed:
- actions.append(f"kept {record.name} (state changed since audit: {changed}; now {reason})")
- continue
- except Exception as exc:
- actions.append(f"kept {record.name} (could not revalidate: {exc})")
- continue
if record.untracked:
archive = _archive_untracked(entry, record.untracked)
if archive is None:
@@ -328,23 +303,11 @@ def reclaim_worktrees(
continue
actions.append(f"archived {len(record.untracked)} untracked file(s) → {archive}")
- # Dead-pid locks must be unlocked or `worktree remove` refuses.
+ # Dead-pid locks must be unlocked or `remove --force` refuses.
with contextlib.suppress(Exception):
_git(["worktree", "unlock", record.path], cwd=repo_root, timeout=10)
try:
- # Plain remove reads the TREE's index: its filters (config.worktree) need the tree's env.
- env = noninteractive_repo_git_env(record.path)
- if env is None:
- actions.append(f"kept {record.name} ({FILTER_DISCOVERY_FAILED})")
- continue
- remove_args = ["git", "worktree", "remove", record.path]
- if record.untracked:
- remove_args.append("--force") # only after the audited scratch was archived
- remove_result = _run(remove_args, 30, repo_root, env=env)
- # Plain remove always refuses trees with submodules; --force only after a fresh clean check.
- if (remove_result.returncode != 0 and not record.untracked
- and "submodules" in remove_result.stderr and _dirty_split(record.path) == (False, [])):
- remove_result = _run([*remove_args, "--force"], 30, repo_root, env=env)
+ remove_result = _git(["worktree", "remove", record.path, "--force"], cwd=repo_root, timeout=30)
if remove_result.returncode != 0:
actions.append(f"failed to remove {record.name}: {remove_result.stderr.strip()}")
continue
@@ -360,8 +323,6 @@ def reclaim_worktrees(
if not dry_run:
with contextlib.suppress(Exception):
_git(["worktree", "prune"], cwd=repo_root, timeout=15)
- if len(merge_cache) != cache_size_before:
- _ops._save_worktree_merge_cache(merge_cache)
return actions
diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.py
index d2d5a67125e..ce77b82df55 100644
--- a/hermes_cli/worktree_ops.py
+++ b/hermes_cli/worktree_ops.py
@@ -849,34 +849,26 @@ def _prune_candidates(worktrees_dir: Path, max_age_hours: int, now: float) -> li
return candidates
-def _remote_heads_getter(repo_root: str):
- """Lazy once-per-sweep ls-remote: only paid when a tree reaches the pushed tier (TUI runs this sync)."""
- memo: dict = {}
- lock = threading.Lock()
-
- def get():
- with lock:
- if "heads" not in memo:
- memo["heads"] = _fetch_remote_branch_heads(repo_root, timeout=10)
- return memo["heads"]
- return get
-
-
-def _classify_prune_candidates(repo_root: str, candidates: list, *, merge_cache=None,
- get_remote_heads=None) -> list:
+def _classify_prune_candidates(repo_root: str, candidates: list) -> list:
"""Phase 2, parallel read-only classification -> ``[(entry, mtime, force, verdict, lock_state)]``.
verdict in ``dirty`` / ``unpushed`` / ``locked-live`` / ``reap`` / ``reap-keep-branch``. Each
check is a read-only query on a distinct worktree (no repo-wide lock), so a bounded pool is
- safe; mutation stays serial. ``git cherry`` verdicts are memoized on disk; a caller-supplied
- *merge_cache* / *get_remote_heads* is shared across calls and the caller saves the cache.
+ safe; mutation stays serial. ``git cherry`` verdicts are memoized on disk.
"""
- owns_cache = merge_cache is None
- if owns_cache:
- merge_cache = _load_worktree_merge_cache()
+ merge_cache = _load_worktree_merge_cache()
cache_size_before = len(merge_cache)
cache_lock = threading.Lock()
- _get_remote_heads = get_remote_heads or _remote_heads_getter(repo_root)
+
+ # Lazy once-per-sweep ls-remote: only paid when a tree reaches the pushed tier (TUI runs this sync).
+ _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
@@ -920,7 +912,7 @@ def _classify_prune_candidates(repo_root: str, candidates: list, *, merge_cache=
logger.debug("Parallel worktree classification failed (%s); serial", e)
verdicts = [_classify(c) for c in candidates]
- if owns_cache and len(merge_cache) != cache_size_before:
+ if len(merge_cache) != cache_size_before:
_save_worktree_merge_cache(merge_cache)
return verdicts
@@ -929,27 +921,15 @@ def _classify_prune_candidates(repo_root: str, candidates: list, *, merge_cache=
_PRESERVE_REASONS = {"dirty": "uncommitted changes", "unpushed": "unpushed commits"}
-def _reap_prune_verdicts(repo_root: str, verdicts: list, stale_work_cutoff: float, *,
- merge_cache=None, get_remote_heads=None) -> tuple[list, set]:
+def _reap_prune_verdicts(repo_root: str, verdicts: list, stale_work_cutoff: float) -> tuple[list, set]:
"""Phase 3, serial unlock / remove / branch -D -> ``(preserved_stale, kept_branches)``.
*kept_branches* must survive the orphaned-branch pass. Branch deletion is gated on
``worktree remove`` succeeding so a failed removal never orphans reachable commits.
"""
- from hermes_cli._subprocess_compat import noninteractive_repo_git_env
preserved_stale: list = []
kept_branches: set = set()
for entry, mtime, force, verdict, lock_state in verdicts:
- # Keep the original candidate set, but refresh its destructive safety gates:
- # classification can precede removal by a long parallel sweep.
- if verdict in {"reap", "reap-keep-branch"}:
- try:
- (_, _, _, verdict, lock_state), = _classify_prune_candidates(
- repo_root, [(entry, mtime, force)], merge_cache=merge_cache,
- get_remote_heads=get_remote_heads)
- except Exception as exc:
- logger.debug("Could not revalidate worktree %s: %s", entry.name, exc)
- continue
reason = _PRESERVE_REASONS.get(verdict)
if reason:
if mtime <= stale_work_cutoff:
@@ -965,21 +945,7 @@ def _reap_prune_verdicts(repo_root: str, verdicts: list, stale_work_cutoff: floa
try:
branch = _git(["branch", "--show-current"], str(entry), timeout=5).stdout.strip()
- # Our own .worktreeinclude symlinks are the only untracked state a reap verdict
- # allows; drop them so the plain (non --force) remove still succeeds.
- for rel in _include_symlink_paths(str(entry), repo_root):
- (entry / rel).unlink()
- # Without --force, remove reads the tree's index, which runs core.fsmonitor.
- remove_env = noninteractive_repo_git_env(str(entry))
- if remove_env is None:
- continue
- remove_result = _git(["worktree", "remove", str(entry)], repo_root, timeout=15,
- stdin=subprocess.DEVNULL, env=remove_env)
- # Plain remove always refuses trees with submodules; --force only after a fresh clean check.
- if (remove_result.returncode != 0 and "submodules" in remove_result.stderr
- and not _worktree_is_dirty(str(entry), repo_root)):
- remove_result = _git(["worktree", "remove", "--force", str(entry)], repo_root,
- timeout=15, stdin=subprocess.DEVNULL, env=remove_env)
+ remove_result = _git(["worktree", "remove", str(entry), "--force"], repo_root, timeout=15)
if remove_result.returncode != 0:
logger.debug("Failed to remove worktree %s: %s", entry.name, remove_result.stderr.strip())
continue
@@ -1020,17 +986,8 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
_prune_orphaned_branches(repo_root)
return
- # One disk cache + one ls-remote shared by classification and the per-tree revalidation.
- merge_cache = _load_worktree_merge_cache()
- cache_size_before = len(merge_cache)
- get_remote_heads = _remote_heads_getter(repo_root)
- verdicts = _classify_prune_candidates(repo_root, candidates, merge_cache=merge_cache,
- get_remote_heads=get_remote_heads)
- preserved_stale, kept_branches = _reap_prune_verdicts(
- repo_root, verdicts, now - (7 * 24 * 3600), merge_cache=merge_cache,
- get_remote_heads=get_remote_heads)
- if len(merge_cache) != cache_size_before:
- _save_worktree_merge_cache(merge_cache)
+ 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("Preserving %d worktree(s) older than 7 days with unmerged work "
diff --git a/tests/hermes_cli/test_worktree_reclaim_revalidation.py b/tests/hermes_cli/test_worktree_reclaim_revalidation.py
deleted file mode 100644
index 8271ddd5da8..00000000000
--- a/tests/hermes_cli/test_worktree_reclaim_revalidation.py
+++ /dev/null
@@ -1,86 +0,0 @@
-"""An old cleanup verdict must not delete work added since the audit."""
-
-import os
-import subprocess
-import time
-
-import pytest
-
-
-def repository(tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
- monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull)
- monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
- root = tmp_path / "repo"
- _git(tmp_path, "init", "-b", "main", str(root))
- _git(root, "config", "user.name", "Hermes test")
- _git(root, "config", "user.email", "[email protected]")
- (root / "README.md").write_text("initial\n", encoding="utf-8")
- _git(root, "add", "README.md")
- _git(root, "-c", "commit.gpgsign=false", "commit", "-m", "initial")
- tree = root / ".worktrees" / "scratch"
- _git(root, "worktree", "add", "-b", "scratch", str(tree))
- return root, tree
-
-
-def _git(cwd, *args):
- result = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=True)
- return result.stdout.strip()
-
-
-def _add_work(tree, kind):
- (tree / "README.md").write_text("new work after audit\n", encoding="utf-8")
- if kind == "commit":
- _git(tree, "add", "README.md")
- _git(tree, "-c", "commit.gpgsign=false", "commit", "-m", "new unique work")
-
-
[email protected]("kind", ["edit", "commit"])
-def test_attended_reclaim_preserves_work_added_after_audit(repository, kind):
- from hermes_cli.worktree_gc import audit_worktrees, reclaim_worktrees
-
- root, tree = repository
- records = audit_worktrees(str(root), with_sizes=False)
- assert next(record for record in records if record.path == str(tree)).verdict == "reap"
- _add_work(tree, kind)
-
- assert reclaim_worktrees(str(root), records=records) == [
- "kept scratch (state changed since audit: verdict; now uncommitted tracked changes (real work))"
- if kind == "edit" else "kept scratch (state changed since audit: verdict; now unpushed commits not found upstream)"]
-
- assert tree.is_dir()
- assert (tree / "README.md").read_text(encoding="utf-8") == "new work after audit\n"
- assert _git(root, "rev-parse", "--verify", "scratch")
-
-
[email protected]("kind", ["edit", "commit", "include-symlink", "submodule"])
-def test_startup_reclaim_preserves_work_added_after_classification(repository, kind):
- from hermes_cli.worktree_ops import _classify_prune_candidates, _reap_prune_verdicts
-
- root, tree = repository
- if kind == "include-symlink": # our own scaffolding only: still reclaimed, target untouched
- (root / "node_modules").mkdir()
- (root / ".worktreeinclude").write_text("node_modules\n", encoding="utf-8")
- (root / ".gitignore").write_text("node_modules/\n.worktrees/\n", encoding="utf-8")
- os.symlink(root / "node_modules", tree / "node_modules")
- if kind == "submodule": # plain `worktree remove` always refuses these; clean + merged still reclaims
- _git(root.parent, "init", "-b", "main", "sub")
- _git(root.parent / "sub", "-c", "user.name=t", "-c", "user.email=t@x", "commit", "--allow-empty", "-m", "s")
- _git(tree, "-c", "protocol.file.allow=always", "submodule", "add", str(root.parent / "sub"), "sub")
- _git(tree, "-c", "commit.gpgsign=false", "commit", "-m", "add submodule")
- _git(root, "merge", "--ff-only", "scratch")
- verdicts = _classify_prune_candidates(str(root), [(tree, time.time() - 86400, False)])
- assert verdicts[0][3] == "reap"
- added_work = kind in {"edit", "commit"}
- if added_work:
- _add_work(tree, kind)
-
- _reap_prune_verdicts(str(root), verdicts, stale_work_cutoff=0)
-
- assert tree.is_dir() is added_work
- if added_work:
- assert (tree / "README.md").read_text(encoding="utf-8") == "new work after audit\n"
- assert _git(root, "rev-parse", "--verify", "scratch")
- elif kind == "include-symlink":
- assert (root / "node_modules").is_dir()
diff --git a/tests/security/test_gitspawn_config_injection.py b/tests/security/test_gitspawn_config_injection.py
index cde9636a6b2..63dac267d67 100644
--- a/tests/security/test_gitspawn_config_injection.py
+++ b/tests/security/test_gitspawn_config_injection.py
@@ -124,7 +124,7 @@ def _make_malicious_repo(tmp: Path) -> tuple[Path, Path]:
def _fired(marker: Path) -> list[str]:
out = []
- for sink in ("fsmonitor", "hook", "extdiff", "textconv", "ssh", "clean"):
+ for sink in ("fsmonitor", "hook", "extdiff", "textconv", "ssh"):
p = Path(f"{marker}.{sink}")
if p.exists():
out.append(sink)
@@ -216,28 +216,13 @@ def test_index_reading_probes_and_kanban_gc_git_are_safe(malicious_repo, tmp_pat
subprocess.run(["git", "-C", str(repo), "-c", "core.hooksPath=/dev/null", "branch", "pr-1"], check=True,
env=_CLEAN_GIT_ENV)
kw._ensure_git_worktree(repo, tmp_path / "wt3", "safe3")
- # A clean filter defined only in the tree's config.worktree: the plain remove re-hashes a stat-dirty README.
- subprocess.run(["git", "-C", str(repo), "config", "extensions.worktreeConfig", "true"], check=True,
- env=_CLEAN_GIT_ENV)
- (repo / ".git" / "info" / "attributes").write_text("README filter=evil\n")
-
- def _tree_filter(tree: Path) -> None:
- subprocess.run(["git", "-C", str(tree), "config", "--worktree", "filter.evil.clean",
- f"touch '{marker.as_posix()}.clean'; cat"], check=True, env=_CLEAN_GIT_ENV)
- os.utime(tree / "README", (time.time() + 60, time.time() + 60))
- _tree_filter(tmp_path / "wt2")
worktree_ops._reap_prune_verdicts(str(repo), [(tmp_path / "wt2", 0.0, False, "reap", None)], 0.0)
worktree_ops._prune_orphaned_branches(str(repo))
worktree_ops._cleanup_failed_worktree_add(str(repo), tmp_path / "wt3", "safe3")
assert _fired(marker) == []
- kw._ensure_git_worktree(repo, tmp_path / "wt4", "safe4")
- _tree_filter(tmp_path / "wt4")
- record = worktree_gc.TreeRecord("wt4", str(tmp_path / "wt4"), "safe4", 9.0, None, "reap", "")
- assert worktree_gc.reclaim_worktrees(str(repo), records=[record]) == ["removed wt4"] # attended reclaim
- assert _fired(marker) == []
branches = subprocess.run(["git", "-C", str(repo), "branch", "--format=%(refname:short)"],
capture_output=True, text=True, env=_CLEAN_GIT_ENV).stdout.split()
- assert not {"safe2", "pr-1", "safe3", "safe4"} & set(branches) # the deletions ran
+ assert not {"safe2", "pr-1", "safe3"} & set(branches) # the deletions ran
for key, value in {"remote.origin.url": "ssh://[email protected]/x.git",
"core.sshCommand": f"touch '{marker.as_posix()}.ssh'; false"}.items():