Skip to content

The agent that grows with you

fix(cli): prune stale shallow grafts left by depth-1 update checks (#105951)

liuhao10245bfa389e8ac2
diff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.py
index 3f714ad8343..cb1f9cdf252 100644
--- a/hermes_cli/gitlock.py
+++ b/hermes_cli/gitlock.py
@@ -126,3 +126,68 @@ def is_ancestor_of_head(repo_root: Path, rev: str) -> bool:
logger.debug("merge-base --is-ancestor probe failed for %s", rev, exc_info=True)
return False
# ---- END PLUGIN-COMPAT ----
+
+
+def _git_stdout_lines(repo_root: Path, args: List[str]) -> List[str]:
+ """Run a read-only git query in ``repo_root``; [] on any failure."""
+ try:
+ result = subprocess.run(
+ ["git", *args], cwd=str(repo_root),
+ capture_output=True, text=True, timeout=10,
+ )
+ if result.returncode != 0:
+ return []
+ return [line.strip() for line in result.stdout.splitlines() if line.strip()]
+ except Exception:
+ logger.debug("git query failed: %s", args, exc_info=True)
+ return []
+
+
+def prune_stale_shallow_grafts(repo_root: Path) -> int:
+ """Drop ``.git/shallow`` graft lines no live ref still points at (#105951).
+
+ Every ``git fetch --depth 1`` appends the fetched tip to ``.git/shallow`` as a new
+ graft and never removes the previous one, so a long-lived shallow installer checkout
+ accumulates one graft per update check (57 observed in the wild). The stale grafts
+ break ``merge-base`` and push ``hermes update`` into the orphan-divergence reset path
+ on every run. Keep only the boundaries that still protect referenced tips (HEAD,
+ FETCH_HEAD, and every ref tip): the dropped commits are already unreachable and their
+ objects are left for ``git gc``. Returns the number of graft lines removed; never
+ raises, and restores the original file if the trimmed set breaks history walking.
+ """
+ try:
+ shallow_rel = _git_stdout_lines(repo_root, ["rev-parse", "--git-path", "shallow"])
+ if not shallow_rel:
+ return 0
+ shallow_path = Path(shallow_rel[0])
+ if not shallow_path.is_absolute():
+ shallow_path = Path(repo_root) / shallow_path
+ if not shallow_path.is_file():
+ return 0
+ lines = [line for line in shallow_path.read_text(encoding="utf-8").splitlines() if line]
+ if not lines:
+ return 0
+ keep = set(lines) & {
+ *(_git_stdout_lines(repo_root, ["rev-parse", "HEAD"]) or []),
+ *(_git_stdout_lines(repo_root, ["rev-parse", "--verify", "--quiet", "FETCH_HEAD"]) or []),
+ *_git_stdout_lines(repo_root, ["for-each-ref", "--format=%(objectname)"]),
+ }
+ if len(keep) == len(lines):
+ return 0
+ original = shallow_path.read_text(encoding="utf-8")
+ tmp_path = shallow_path.with_name(shallow_path.name + ".hermes-prune")
+ tmp_path.write_text("\n".join(sorted(keep)) + "\n", encoding="utf-8")
+ os.replace(tmp_path, shallow_path)
+ # Fail-safe: if any reachable walk now crosses a boundary we wrongly removed,
+ # put the grafts back — a growing file beats a broken repo.
+ still_walks = _git_stdout_lines(repo_root, ["rev-list", "--count", "HEAD"]) and \
+ _git_stdout_lines(repo_root, ["rev-list", "--count", "--all"])
+ if not still_walks:
+ shallow_path.write_text(original, encoding="utf-8")
+ logger.debug("shallow prune self-check failed; grafts restored")
+ return 0
+ logger.info("Pruned %d stale shallow graft(s) in %s", len(lines) - len(keep), repo_root)
+ return len(lines) - len(keep)
+ except Exception:
+ logger.debug("shallow graft prune failed for %s", repo_root, exc_info=True)
+ return 0
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index beba4e72bf0..32bf9d370e1 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -514,6 +514,15 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):
_print_fetch_failure(fetch_result.stderr)
sys.exit(1)
+ if is_shallow:
+ # The depth-1 fetch above leaves the previous tip behind as a ``.git/shallow`` graft
+ # (git never removes old grafts); prune the stale ones so the file stops growing and
+ # merge-base / the orphan-divergence heuristic keep working (#105951).
+ from hermes_cli.gitlock import prune_stale_shallow_grafts
+ pruned = prune_stale_shallow_grafts(_m().PROJECT_ROOT)
+ if pruned:
+ print(f" (pruned {pruned} stale shallow graft(s) left by past depth-1 checks)")
+
# rev-list on a bogus ref exits 128 and (check=True) would traceback; verify first.
verify_result = _git_run(git_cmd, ["rev-parse", "--verify", "--quiet", compare_branch])
if verify_result.returncode != 0:
diff --git a/tests/hermes_cli/test_shallow_graft_prune.py b/tests/hermes_cli/test_shallow_graft_prune.py
new file mode 100644
index 00000000000..a1e5aeb6ae3
--- /dev/null
+++ b/tests/hermes_cli/test_shallow_graft_prune.py
@@ -0,0 +1,127 @@
+"""Stale shallow-graft pruning after depth-1 update checks (#105951).
+
+Every ``git fetch --depth 1`` appends the fetched tip to ``.git/shallow`` as a
+new graft and never removes the previous one, so a long-lived shallow installer
+checkout accumulates one line per update check (57 observed in the wild). The
+stale grafts break ``merge-base`` and push ``hermes update`` into the
+orphan-divergence reset path. ``prune_stale_shallow_grafts()`` drops grafts no
+live ref points at; ``hermes update --check`` calls it after its successful
+depth-1 fetch, clearing the grafts accumulated by past checks (the passive
+banner check no longer git-fetches since #107648).
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+from hermes_cli.gitlock import prune_stale_shallow_grafts
+
+SHA_A = "a" * 40
+SHA_B = "b" * 40
+
+
+def _git(repo: Path, *args: str) -> str:
+ result = subprocess.run(
+ ["git", *args], cwd=str(repo), capture_output=True, text=True
+ )
+ assert result.returncode == 0, result.stderr
+ return result.stdout.strip()
+
+
+def _shallow_lines(repo: Path) -> list:
+ return [
+ line for line in (repo / ".git" / "shallow").read_text().splitlines() if line
+ ]
+
+
+def _mk_shallow_scenario(tmp_path: Path) -> Path:
+ """Depth-1 clone whose origin advanced twice: shallow carries 3 grafts."""
+ origin = tmp_path / "origin"
+ origin.mkdir()
+ _git(origin, "init", "-q", "-b", "main")
+ _git(origin, "config", "user.email", "[email protected]")
+ _git(origin, "config", "user.name", "t")
+ for i in range(3):
+ _git(origin, "commit", "--allow-empty", "-q", "-m", f"c{i}")
+ clone = tmp_path / "clone"
+ subprocess.run(
+ ["git", "clone", "-q", "--depth", "1", f"file://{origin}", str(clone)],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ for i in range(3, 5):
+ _git(origin, "commit", "--allow-empty", "-q", "-m", f"c{i}")
+ _git(clone, "fetch", "-q", "--depth", "1", "origin", "main")
+ return clone
+
+
+def test_prunes_orphaned_grafts_keeps_referenced_boundaries(tmp_path):
+ clone = _mk_shallow_scenario(tmp_path)
+ assert len(_shallow_lines(clone)) == 3 # HEAD graft + two fetched tips
+
+ head_sha = _git(clone, "rev-parse", "HEAD")
+ tip_sha = _git(clone, "rev-parse", "origin/main")
+
+ removed = prune_stale_shallow_grafts(clone)
+
+ assert removed == 1 # the middle, now-unreferenced tip
+ assert set(_shallow_lines(clone)) == {head_sha, tip_sha}
+ # Boundaries that survive must still walk cleanly.
+ assert _git(clone, "rev-list", "--count", "HEAD") == "1"
+ assert _git(clone, "rev-list", "--count", "origin/main") == "1"
+
+
+def test_prune_is_idempotent_and_noop_without_grafts(tmp_path):
+ clone = _mk_shallow_scenario(tmp_path)
+ assert prune_stale_shallow_grafts(clone) == 1
+ assert prune_stale_shallow_grafts(clone) == 0 # nothing left to drop
+
+ empty_dir = tmp_path / "not-a-repo"
+ empty_dir.mkdir()
+ assert prune_stale_shallow_grafts(empty_dir) == 0 # not a git repo: no-op
+
+ git_no_shallow = tmp_path / "full-clone"
+ git_no_shallow.mkdir()
+ (git_no_shallow / ".git").mkdir()
+ assert prune_stale_shallow_grafts(git_no_shallow) == 0 # no shallow file: no-op
+
+
+def test_update_check_prunes_and_reports_count(tmp_path, monkeypatch, capsys):
+ """`hermes update --check` prunes grafts after its depth-1 fetch and reports the prune."""
+ import hermes_cli.update_cmd as update_cmd
+
+ fake_root = SimpleNamespace(PROJECT_ROOT=tmp_path)
+ monkeypatch.setattr(update_cmd, "_m", lambda: fake_root)
+ (tmp_path / ".git").mkdir()
+ monkeypatch.setattr(
+ "hermes_cli.update_contract.evaluate_update_admission", lambda root: None
+ )
+ monkeypatch.setattr(update_cmd, "_is_shallow_checkout", lambda git_cmd: True)
+ monkeypatch.setattr(update_cmd, "_tip_shas", lambda git_cmd, branch: (SHA_A, SHA_B))
+
+ def fake_git_run(git_cmd, args, **kwargs):
+ joined = " ".join(args)
+ if "get-url" in joined and "upstream" in joined:
+ return MagicMock(returncode=1, stdout="", stderr="") # no upstream remote
+ if "fetch" in joined:
+ return MagicMock(returncode=0, stdout="", stderr="") # depth-1 fetch lands
+ return MagicMock(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(update_cmd, "_git_run", fake_git_run)
+ monkeypatch.setattr(update_cmd, "_base_git_cmd", lambda: ["git"])
+ monkeypatch.setattr("hermes_cli.banner._github_compare_behind", lambda *a, **k: 0)
+ prune_calls = []
+ monkeypatch.setattr(
+ "hermes_cli.gitlock.prune_stale_shallow_grafts",
+ lambda repo: prune_calls.append(repo) or 2,
+ )
+
+ update_cmd._cmd_update_check("main")
+
+ out = capsys.readouterr().out
+ assert prune_calls == [tmp_path]
+ assert "pruned 2 stale shallow graft(s)" in out