The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): on macOS only a git working in this checkout keeps a dead index.lock
Teknium3f7a34921ce6
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex a60f526875f..6adfd8d3ead 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -762,13 +762,40 @@ def _held_open_lsof(path: Path, root: Path | None, any_git: bool) -> _Holder | breturn _Holder(f"pid {pids[0]} ({names[0] if names else '?'})")if found.returncode not in (0, 1): # lsof exits 1 when nothing has the file openreturn None- return False if root is None else _ps_git_holder(path.parent, any_git)+ return False if root is None else _ps_git_holder(lsof, path.parent, root, any_git)-def _ps_git_holder(git_dir: Path, any_git: bool) -> _Holder | bool | None:+def _lsof_cwds(lsof: str, pids: list[str]) -> dict[str, str] | None:+ """Each pid's cwd from ``lsof -d cwd`` (macOS has no /proc); None when lsof cannot answer."""+ try:+ out = subprocess.run([lsof, "-a", "-d", "cwd", "-F", "pn", "-p", ",".join(pids)], capture_output=True,+ text=True, encoding="utf-8", errors="replace", timeout=20, stdin=subprocess.DEVNULL)+ except (OSError, subprocess.SubprocessError):+ return None+ if out.returncode not in (0, 1):+ return None+ cwds: dict[str, str] = {}+ pid = None+ for line in out.stdout.splitlines():+ if line.startswith("p"):+ pid = line[1:]+ elif line.startswith("n") and pid is not None:+ cwds[pid] = line[1:]+ return cwds+++def _still_running(pid: int) -> bool:+ import psutil++ return psutil.pid_exists(pid)+++def _ps_git_holder(lsof: str, git_dir: Path, root: Path, any_git: bool) -> _Holder | bool | None:"""An empty ``lsof`` is no proof: ``git commit`` waiting in the editor has closed its lock fd.- ``ps`` cannot say where a git works, so every git (by executable name, dashed forms included)- that could write ``git_dir`` and is not a pure reader keeps the lock."""+ Every git (by executable name, dashed forms included) that could write ``git_dir``, is not a pure+ reader, and works in the checkout (its cwd from ``lsof -d cwd``, or a path argument) keeps the+ lock; one whose cwd cannot be read makes the answer None. Gits elsewhere on the machine do not+ count, or any commit open in another repository would block every launch-time repair."""def ps(*columns: str) -> list[list[str]] | None:try:out = subprocess.run(["ps", "-A", *(f"-o{c}=" for c in columns)], capture_output=True,@@ -785,6 +812,7 @@ def _ps_git_holder(git_dir: Path, any_git: bool) -> _Holder | bool | None:if named is None or commands is None:return Noneargv = {row[0]: row[1].split() for row in commands if len(row) == 2}+ candidates: dict[str, list[str]] = {}for row in named:if len(row) != 3 or not (row[0].isdigit() and row[1].isdigit()) or int(row[0]) == os.getpid():continue@@ -794,7 +822,19 @@ def _ps_git_holder(git_dir: Path, any_git: bool) -> _Holder | bool | None:if _git_program(args[0]) is None:args = [row[2]] # an argv[0] with spaces: no subcommand, so it countsif _could_write(int(row[1]), git_dir) and _counts_as_holder(args, any_git):- return _Holder(f"pid {row[0]} ({' '.join([os.path.basename(args[0]), *args[1:3]])})")+ candidates[row[0]] = args+ if not candidates:+ return False+ cwds = _lsof_cwds(lsof, sorted(candidates))+ if cwds is None:+ return None+ places = _checkout_places(root, git_dir)+ for pid, args in candidates.items():+ cwd = cwds.get(pid)+ if cwd is None and _still_running(int(pid)):+ return None # a lock-keeping git we cannot place may be working here+ if git_works_in(args, cwd, None, places):+ return _Holder(f"pid {pid} ({' '.join([os.path.basename(args[0]), *args[1:3]])})")return Falsediff --git a/tests/hermes_cli/test_gitlock.py b/tests/hermes_cli/test_gitlock.pyindex 5cecf353553..09dec15f6f0 100644--- a/tests/hermes_cli/test_gitlock.py+++ b/tests/hermes_cli/test_gitlock.py@@ -39,10 +39,10 @@ def repo(tmp_path: Path) -> Path:subprocess.run(["git", "init", "-q"], cwd=root, check=True)subprocess.run(["git", "config", "user.email", "[email protected]"], cwd=root, check=True)subprocess.run(["git", "config", "user.name", "Test"], cwd=root, check=True)- (root / "a.txt").write_text("one\n")+ (root / "a.txt").write_text("one\n", encoding="utf-8")subprocess.run(["git", "add", "a.txt"], cwd=root, check=True)subprocess.run(["git", "commit", "-q", "-m", "first"], cwd=root, check=True)- (root / "b.txt").write_text("two\n")+ (root / "b.txt").write_text("two\n", encoding="utf-8")subprocess.run(["git", "add", "b.txt"], cwd=root, check=True)subprocess.run(["git", "commit", "-q", "-m", "second"], cwd=root, check=True)return root@@ -412,7 +412,7 @@ def _git_in_the_editor(repo: Path, tmp_path: Path, argv: list[str]) -> subproces"Path(sys.argv[1] + '.ready').write_text('')\n""while not Path(sys.argv[1] + '.go').exists(): time.sleep(0.02)\n""Path(sys.argv[1]).write_text('fixture\\n')\n", encoding="utf-8")- (repo / "a.txt").write_text("changed\n")+ (repo / "a.txt").write_text("changed\n", encoding="utf-8")proc = subprocess.Popen(argv, cwd=repo, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,env={**os.environ, "GIT_EDITOR": f"{sys.executable} {editor}"})msg = repo / ".git" / "COMMIT_EDITMSG"@@ -438,7 +438,7 @@ def test_a_killed_updates_lock_stays_while_any_git_works_in_the_checkout(repo: Plock = repo / ".git" / "index.lock"_killed_update_receipt()if form.startswith("dashed"):- exec_path = subprocess.run(["git", "--exec-path"], capture_output=True, text=True, check=True).stdout.strip()+ exec_path = subprocess.run(["git", "--exec-path"], capture_output=True, text=True, encoding="utf-8", check=True).stdout.strip()dashed = Path(exec_path) / "git-commit"if not dashed.exists():pytest.skip("this git ships no dashed git-commit")@@ -452,7 +452,7 @@ def test_a_killed_updates_lock_stays_while_any_git_works_in_the_checkout(repo: Passert release_dead_index_lock(repo) is Falseassert lock.exists(), f"{form}: the reclaim deleted a lock a live git may own"finally:- Path(f"{repo / '.git' / 'COMMIT_EDITMSG'}.go").write_text("")+ Path(f"{repo / '.git' / 'COMMIT_EDITMSG'}.go").write_text("", encoding="utf-8")if form.startswith("dashed"):assert proc.wait(timeout=20) == 0, "the user's commit failed"else:@@ -481,10 +481,11 @@ def test_lock_keeping_git_is_recognised_in_every_form_and_by_path_components(tmplock = root / ".git" / "index.lock"lock.write_bytes(b"")- def ps_lists(command: str):+ def ps_lists(command: str, cwd: Path = root):def run(argv, **_kw):if argv[0] == "lsof":- return subprocess.CompletedProcess(argv, 1, "", "")+ return subprocess.CompletedProcess(argv, 0 if "cwd" in argv else 1,+ f"p4242\nn{cwd}\n" if "cwd" in argv else "", "")rows = (f"4242 {getattr(os, 'getuid', lambda: 0)()} {command.split()[0]}" if "-ocomm=" in argv else f"4242 {command}")return subprocess.CompletedProcess(argv, 0, rows + "\n", "")return run@@ -492,6 +493,8 @@ def test_lock_keeping_git_is_recognised_in_every_form_and_by_path_components(tmpmonkeypatch.setattr("shutil.which", lambda name: name)monkeypatch.setattr(er.subprocess, "run", ps_lists("/Library/Developer/CommandLineTools/usr/libexec/git-core/git-commit -a"))assert er._held_open_lsof(lock, root, False), "macOS: a dashed git-commit with its fd closed keeps the lock"+ monkeypatch.setattr(er.subprocess, "run", ps_lists("git commit -a", tmp_path / "hermes-backup"))+ assert er._held_open_lsof(lock, root, False) is False, "a commit in another repository is not this checkout's"monkeypatch.setattr(er.subprocess, "run", ps_lists("git log --oneline"))assert er._held_open_lsof(lock, root, False) is False and er._held_open_lsof(lock, root, True)monkeypatch.undo()