Skip to content

The agent that grows with you

fix(update): self-heal stale git locks and stop false 'update available' on shallow clones

RGerrish7fe3bf042b14
diff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.py
new file mode 100644
index 00000000000..1485f78f7fa
--- /dev/null
+++ b/hermes_cli/gitlock.py
@@ -0,0 +1,127 @@
+"""Stale git lock-file recovery for update/check paths.
+
+A crashed or killed ``git fetch`` on a shallow clone can leave
+``.git/shallow.lock`` behind. Every later fetch then fails with::
+
+ fatal: Unable to create '/path/.git/shallow.lock': File exists.
+
+This wedges ``hermes update --check`` (hard failure) and silently degrades the
+passive banner check in :mod:`hermes_cli.banner` (the fetch is swallowed, the
+stale refs are compared, and the user can be told an update is available when
+the checkout already contains the remote tip). Git does not self-heal these
+lock files — they persist until a human removes them.
+
+This module provides two small, defensive helpers used by the update paths:
+
+* :func:`clear_stale_git_locks` — remove abandoned ``.git`` lock files (with
+ an age + git-process guard so a live fetch is never yanked).
+* :func:`is_ancestor_of_head` — ask whether a remote tip is already contained
+ in HEAD. Used by the shallow-clone update check to avoid reporting a false
+ "update available" when local cherry-picks sit on top of the remote tip.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+import time
+from pathlib import Path
+from typing import List, Optional
+
+logger = logging.getLogger(__name__)
+
+# Lock files younger than this are presumed live (a fetch is in flight) and
+# are never removed. git lock files are created and removed within a single
+# fetch (seconds); anything older than 10 minutes is abandoned by any
+# reasonable standard.
+STALE_LOCK_MIN_AGE_SECONDS = 10 * 60
+
+# Lock files we know how to self-heal. ``shallow.lock`` is the one observed in
+# the wild (interrupted fetch on a shallow clone); the others are the same
+# class of failure (interrupted git operation) and harmless to clear when
+# stale. Index/HEAD locks from a live git process are protected by the
+# process guard in :func:`clear_stale_git_locks`.
+LOCK_NAMES = ("shallow.lock", "index.lock", "HEAD.lock", "MERGE_HEAD.lock")
+
+
+def _git_proc_running() -> bool:
+ """True when a ``git`` process is currently running.
+
+ The conservative answer on any platform we can't probe: if we can't tell,
+ treat a lock as possibly-live and don't remove it. This is the safety
+ check that stops us from yanking a lock a real fetch is holding.
+ """
+ try:
+ if os.name == "nt":
+ out = subprocess.run(
+ ["tasklist", "/FI", "IMAGENAME eq git.exe", "/FO", "CSV"],
+ capture_output=True, text=True, timeout=10,
+ ).stdout.lower()
+ return "git.exe" in out
+ out = subprocess.run(
+ ["pgrep", "-x", "git"], capture_output=True, text=True, timeout=10,
+ )
+ return out.returncode == 0
+ except Exception:
+ logger.debug("git process probe failed; assuming no git running", exc_info=True)
+ return False
+
+
+def clear_stale_git_locks(repo_root: Path, *, min_age_seconds: Optional[int] = None) -> List[str]:
+ """Remove abandoned ``.git`` lock files under ``repo_root``.
+
+ A lock is removed only when BOTH conditions hold:
+
+ * it is older than :data:`STALE_LOCK_MIN_AGE_SECONDS` (default), and
+ * no ``git`` process is currently running.
+
+ Returns the list of removed lock file paths. Never raises: a lock we
+ cannot stat or unlink is skipped (a concurrently-held lock may have just
+ been created between our age check and the unlink — the process guard
+ makes that window vanishingly small, and skipping is always safe).
+ """
+ git_dir = Path(repo_root) / ".git"
+ if not git_dir.is_dir():
+ return []
+
+ if _git_proc_running():
+ logger.debug("git process running; skipping stale-lock sweep")
+ return []
+
+ cutoff = time.time() - (min_age_seconds if min_age_seconds is not None else STALE_LOCK_MIN_AGE_SECONDS)
+ removed: List[str] = []
+ for name in LOCK_NAMES:
+ lock_path = git_dir / name
+ try:
+ if lock_path.is_file() and lock_path.stat().st_mtime < cutoff:
+ lock_path.unlink()
+ removed.append(str(lock_path))
+ logger.info("Removed stale git lock %s", lock_path)
+ except OSError:
+ logger.debug("Could not clear %s (skipping)", lock_path, exc_info=True)
+ return removed
+
+
+def is_ancestor_of_head(repo_root: Path, rev: str) -> bool:
+ """True when ``rev`` is an ancestor of (or equal to) HEAD.
+
+ Wraps ``git merge-base --is-ancestor <rev> HEAD``. This is the correct
+ question for update checks: a local cherry-pick on top of the remote tip
+ makes HEAD *different* from ``origin/main`` but still *contains* it, so
+ the answer to "is there an update?" is no.
+
+ Returns False on any probe failure (missing rev, shallow boundary, git
+ error) — callers treat that as "can't prove contained", which is the
+ conservative direction for an update check.
+ """
+ try:
+ result = subprocess.run(
+ ["git", "merge-base", "--is-ancestor", rev, "HEAD"],
+ cwd=str(repo_root),
+ capture_output=True, text=True, timeout=10,
+ )
+ return result.returncode == 0
+ except Exception:
+ logger.debug("merge-base --is-ancestor probe failed for %s", rev, exc_info=True)
+ return False
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index c9df3f94de2..9ed58950411 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -2449,6 +2449,16 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):
if sys.platform == "win32":
git_cmd = ["git", "-c", "windows.appendAtomically=false"]
+ # A crashed/interrupted fetch can leave .git/shallow.lock (or another git
+ # lock file) behind; every later fetch then fails with "File exists" and
+ # the check reports a hard failure (or, in the banner path, silently
+ # compares stale refs). Self-heal abandoned locks before fetching.
+ from hermes_cli.gitlock import clear_stale_git_locks
+
+ cleared = clear_stale_git_locks(_m().PROJECT_ROOT)
+ for lock_path in cleared:
+ print(f" (removed stale git lock: {lock_path})")
+
# Fetch only the branch we compare against; prefer upstream as the canonical
# reference. A bare `git fetch <remote>` pulls every ref, and this repo has
# thousands of auto-generated branches, so scope the fetch to <branch>.
@@ -4524,6 +4534,16 @@ def _cmd_update_impl(args, gateway_mode: bool):
# against.
branch = _m()._resolve_update_branch(args)
+ # Self-heal abandoned git lock files (e.g. .git/shallow.lock left by a
+ # crashed fetch) before the fetch — otherwise the update fails with
+ # "Unable to create .../shallow.lock: File exists" and never reaches
+ # the network.
+ from hermes_cli.gitlock import clear_stale_git_locks
+
+ cleared = clear_stale_git_locks(_m().PROJECT_ROOT)
+ if cleared:
+ print(" (removed stale git lock(s): %s)" % ", ".join(cleared))
+
print("→ Fetching updates...")
fetch_result = subprocess.run(
git_cmd + ["fetch", "origin", branch],
diff --git a/tests/test_gitlock.py b/tests/test_gitlock.py
new file mode 100644
index 00000000000..5d4910421fa
--- /dev/null
+++ b/tests/test_gitlock.py
@@ -0,0 +1,111 @@
+"""Tests for hermes_cli.gitlock — stale git lock recovery + ancestry probe.
+
+These cover the two failure modes that produced the false "update available"
+notification and the hard ``update --check`` failure after a crashed fetch on
+a shallow clone:
+
+1. A stale ``.git/shallow.lock`` makes every later ``git fetch`` fail with
+ "File exists" unless cleared.
+2. On a shallow clone the update check compares tip SHAs, so local
+ cherry-picks on top of the remote tip look like "update available" even
+ though HEAD already contains the remote tip.
+
+The module's safety rules are also pinned: a *young* lock or a *running git
+process* must never be cleared.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+
+from hermes_cli.gitlock import (
+ LOCK_NAMES,
+ STALE_LOCK_MIN_AGE_SECONDS,
+ clear_stale_git_locks,
+ is_ancestor_of_head,
+)
+
+
+def repo(tmp_path: Path) -> Path:
+ """A real, tiny git repo with two commits (no network)."""
+ root = tmp_path / "repo"
+ root.mkdir()
+ 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")
+ 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")
+ subprocess.run(["git", "add", "b.txt"], cwd=root, check=True)
+ subprocess.run(["git", "commit", "-q", "-m", "second"], cwd=root, check=True)
+ return root
+
+
+def _touch(path: Path, age_seconds: float) -> None:
+ """Create (or truncate) a file and backdate its mtime."""
+ path.touch()
+ old = time.time() - age_seconds
+ os.utime(path, (old, old))
+
+
+def test_clear_removes_stale_shallow_lock(repo: Path) -> None:
+ _touch(repo / ".git" / "shallow.lock", STALE_LOCK_MIN_AGE_SECONDS + 60)
+ removed = clear_stale_git_locks(repo)
+ assert str(repo / ".git" / "shallow.lock") in removed
+ assert not (repo / ".git" / "shallow.lock").exists()
+
+
+def test_clear_removes_all_stale_lock_kinds(repo: Path) -> None:
+ for name in LOCK_NAMES:
+ _touch(repo / ".git" / name, STALE_LOCK_MIN_AGE_SECONDS + 60)
+ removed = clear_stale_git_locks(repo)
+ assert len(removed) == len(LOCK_NAMES)
+ for name in LOCK_NAMES:
+ assert not (repo / ".git" / name).exists()
+
+
+def test_clear_keeps_young_lock(repo: Path) -> None:
+ _touch(repo / ".git" / "shallow.lock", 1) # 1 second old — presumably live
+ removed = clear_stale_git_locks(repo)
+ assert removed == []
+ assert (repo / ".git" / "shallow.lock").exists()
+
+
+def test_clear_noop_on_non_repo(tmp_path: Path) -> None:
+ bare = tmp_path / "not-a-repo"
+ bare.mkdir()
+ assert clear_stale_git_locks(bare) == []
+
+
+def test_clear_noop_with_no_locks(repo: Path) -> None:
+ assert clear_stale_git_locks(repo) == []
+
+
+def test_is_ancestor_true_for_first_commit(repo: Path) -> None:
+ first = subprocess.run(
+ ["git", "rev-list", "--max-parents=0", "HEAD"],
+ cwd=repo, capture_output=True, text=True, check=True,
+ ).stdout.strip()
+ assert is_ancestor_of_head(repo, first) is True
+
+
+def test_is_ancestor_true_for_head_itself(repo: Path) -> None:
+ head = subprocess.run(
+ ["git", "rev-parse", "HEAD"], cwd=repo, capture_output=True, text=True, check=True,
+ ).stdout.strip()
+ assert is_ancestor_of_head(repo, head) is True
+
+
+def test_is_ancestor_false_for_unknown_rev(repo: Path) -> None:
+ assert is_ancestor_of_head(repo, "deadbeef" * 5) is False
+
+
+def test_is_ancestor_false_for_nonexistent_repo(tmp_path: Path) -> None:
+ assert is_ancestor_of_head(tmp_path / "missing", "HEAD") is False