The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(worktree): read lock state from the tree's admin dir, not `worktree list -z`
Tekniumda4ae170dde0
diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.pyindex fdf3863e15f..704f461ba8f 100644--- a/hermes_cli/worktree_ops.py+++ b/hermes_cli/worktree_ops.py@@ -791,8 +791,8 @@ def _worktree_branch_pushed_exact(# ``hermes pid=<pid>`` (classic launch), ``hermes pid=<pid> db=<state.db>`` (``--tui -w`` launch)-# and ``hermes session=<id> db=<state.db>`` (re-lock when the TUI exits). Read with-# ``list --porcelain -z``: without it git C-quotes a reason holding a backslash, a quote, a control or a+# and ``hermes session=<id> db=<state.db>`` (re-lock when the TUI exits). Read raw from the admin+# dir: plain ``list --porcelain`` C-quotes a reason holding a backslash, a quote, a control or a# non-ASCII byte (every Windows path), and the ``db=`` path would never parse._HERMES_LOCK_RE = re.compile(r"hermes (?:pid=(\d+)|session=\S+)(?: db=(.+))?", re.DOTALL)@@ -843,21 +843,26 @@ def _retained_tree_is_live(db_path: str, worktree_path: str) -> bool:def _worktree_lock_reason(repo_root: str, worktree_path: str, timeout: int):- """``(found, reason)`` from ``git worktree list --porcelain -z``; reason is ``None`` when- unlocked and ``""`` for a bare lock. Raises when git fails."""- listing = _git(["worktree", "list", "--porcelain", "-z"], repo_root, timeout=timeout)- if listing.returncode != 0:- raise RuntimeError(listing.stderr.strip())- target = Path(worktree_path).resolve()- for record in listing.stdout.split("\0\0"):- fields = record.strip("\0").split("\0")- if not fields[0].startswith("worktree ") or Path(fields[0][len("worktree "):]).resolve() != target:- continue- for field in fields[1:]:- if field == "locked" or field.startswith("locked "):- return True, field[len("locked "):]+ """``(found, reason)`` from the tree's admin dir (``gitdir:`` of its ``.git`` file, under+ ``<common-dir>/worktrees/``); reason is ``None`` when unlocked and ``""`` for a bare lock.+ Read raw and trimmed, as git does: ``list --porcelain -z`` needs git 2.36. Raises when git+ or the admin dir cannot be read."""+ common = _git_out(["rev-parse", "--git-common-dir"], repo_root, timeout=timeout)+ if not common:+ raise RuntimeError("not a git repository")+ tree = Path(worktree_path)+ if not (tree / ".git").is_file():+ return False, None # no tree there, or the main checkout+ link = (tree / ".git").read_text(encoding="utf-8-sig")+ if not link.startswith("gitdir:"):+ raise RuntimeError(f"unreadable .git file in {tree}")+ admin = (tree / link[len("gitdir:"):].strip()).resolve()+ if admin.parent != (Path(repo_root) / common / "worktrees").resolve():+ return False, None # a checkout of another repository+ try:+ return True, (admin / "locked").read_text(encoding="utf-8-sig", errors="replace").strip(" \t\n\v\f\r")+ except FileNotFoundError:return True, None- return False, Nonedef _worktree_lock_is_live(repo_root: str, worktree_path: str, timeout: int = 10):diff --git a/tests/hermes_cli/test_worktree_lock_old_git.py b/tests/hermes_cli/test_worktree_lock_old_git.pynew file mode 100644index 00000000000..d0d222dfeb5--- /dev/null+++ b/tests/hermes_cli/test_worktree_lock_old_git.py@@ -0,0 +1,45 @@+"""Worktree lock state without ``git worktree list --porcelain -z`` (git < 2.36, e.g. Ubuntu 22.04).++The pruner read every lock through ``list -z``; on an older git that fails and the fail-safe+``"live"`` answer kept every ``.worktrees`` checkout forever ("in use by a running hermes session").+"""+import os+import shutil+import subprocess+import sys++import pytest++from hermes_cli import worktree_ops+from tests.hermes_cli import test_worktree++[email protected](sys.platform == "win32", reason="POSIX git shim")+def test_stale_worktrees_are_reaped_on_git_without_list_z(tmp_path, monkeypatch):+ import cli++ git_repo = tmp_path / "repo"+ for args in (["init", str(git_repo)], ["-C", str(git_repo), "commit", "--allow-empty", "-m", "init"],+ ["-C", str(git_repo), "update-ref", "refs/remotes/origin/main", "HEAD"]):+ subprocess.run(["git", "-c", "user.name=T", "-c", "user.email=t@t", *args], capture_output=True, check=True)++ real_git = shutil.which("git")+ shim = tmp_path / "old-git"+ shim.mkdir()+ (shim / "git").write_text(+ "#!/bin/sh\n"+ 'case " $* " in *" worktree list "*" -z "*) echo "error: unknown switch \\`z\'" >&2; exit 129;; esac\n'+ f'exec "{real_git}" "$@"\n')+ (shim / "git").chmod(0o755)+ dead = test_worktree.TestWorktreeLockReaping._mk(cli, git_repo, "hermes-dead", pid=999999)+ unlocked = test_worktree.TestWorktreeLockReaping._mk(cli, git_repo, "hermes-nolock")+ live = test_worktree.TestWorktreeLockReaping._mk(cli, git_repo, "hermes-live", pid=os.getpid())+ monkeypatch.setenv("PATH", f"{shim}:{os.environ['PATH']}")+ assert subprocess.run(["git", "worktree", "list", "--porcelain", "-z"], cwd=git_repo,+ capture_output=True, check=False).returncode == 129++ assert worktree_ops._worktree_lock_is_live(str(git_repo), str(dead)) == "dead"+ assert worktree_ops._worktree_lock_is_live(str(git_repo), str(unlocked)) is None+ cli._prune_stale_worktrees(str(git_repo))+ assert not dead.exists() and not unlocked.exists()+ assert live.exists(), "a lock whose owner runs is still live"