Skip to content

The agent that grows with you

fix(update): heal stale shallow history before the bounded fetch

Konstantin Khlopkove377309d8643
diff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.py
index ec44a2620ea..b98b49f1451 100644
--- a/hermes_cli/gitlock.py
+++ b/hermes_cli/gitlock.py
@@ -433,6 +433,35 @@ def _partial_clone_filter(repo_root: Path, **run_kwargs) -> "str | None":
return configured.stdout.strip() or None
+def heal_shallow_history(repo_root: Path, branch: str, **run_kwargs) -> bool:
+ """Unshallow a stale installer checkout before the updater's bounded fetch.
+
+ A depth-1 install that has fallen far behind ``branch`` cannot complete the
+ plain ``git fetch origin <branch>`` inside the updater's 300s network cap:
+ the server must send the full ancestry of every side branch merged past the
+ shallow boundary, each attempt is killed mid-transfer, and the unshallow
+ step that would make later fetches incremental only ran *after* a
+ successful update — so a stale shallow install could never update at all
+ (#123254). This heals the checkout first, with the same commit-graph-only
+ shape and 900s budget the post-update tag fetch uses, pulling ``branch``
+ along so the bounded fetch that follows is small again.
+
+ Returns whether the checkout was shallow. Raises on fetch failure; the
+ checkout is left exactly as it was, so callers can downgrade the failure
+ to a warning and keep the previous fetch behaviour.
+ """
+ shallow = _shallow_file_path(repo_root) is not None
+ if not shallow:
+ return False
+ subprocess.run(
+ ["git", "fetch", "--quiet", "--unshallow", "--filter=tree:0", "--no-tags",
+ "origin", "refs/tags/v*:refs/tags/v*", branch],
+ cwd=str(repo_root), check=True, capture_output=True, text=True,
+ encoding="utf-8", errors="replace", timeout=900, **run_kwargs,
+ )
+ return True
+
+
def fetch_full_commit_graph(repo_root: Path, **run_kwargs) -> bool:
"""Refresh release tags and fill shallow history before publishing identity.
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index f5e872694b2..99896df3782 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -268,13 +268,40 @@ def _git_run(git_cmd, args, cwd=None, *, check=False, network=False):
# fetch writes to tmp_pack_* and only renames on success. Report as a failed run
# so every caller's existing stderr path prints one clear line.
result = subprocess.CompletedProcess(
- exc.cmd, 124, stdout="",
- stderr=f"git {args[0]} timed out after {NETWORK_GIT_TIMEOUT_SECONDS}s with no response from the remote")
+ exc.cmd,
+ 124,
+ stdout="",
+ stderr=f"git {args[0]} was still running after the {NETWORK_GIT_TIMEOUT_SECONDS}s network limit"
+ f" (slow transfer, not a dead remote — a larger fetch may need `hermes update` again or a manual `git fetch`)",
+ )
if check:
raise subprocess.CalledProcessError(124, exc.cmd, output="", stderr=result.stderr) from exc
return result
+def _heal_stale_shallow_checkout(repo_root: Path, branch: str) -> None:
+ """Unshallow a stale installer checkout before the bounded fetch (#123254).
+
+ Non-fatal by design: a server or proxy that rejects the unshallow/filter
+ args leaves the checkout as it was, and the update proceeds with the same
+ fetch (and the same 300s cap) as before — the heal can only widen the set
+ of installs that can update.
+ """
+ from hermes_cli.gitlock import heal_shallow_history
+
+ try:
+ if heal_shallow_history(repo_root, branch, **_no_prompt_git_kwargs()):
+ print(" ✓ Fetched full commit history (shallow checkout healed)")
+ except (OSError, subprocess.SubprocessError) as exc:
+ detail = (getattr(exc, "stderr", None) or str(exc)).strip().splitlines()[
+ -1:
+ ] or [type(exc).__name__]
+ print(
+ f" ⚠ Could not heal the shallow checkout before fetching ({detail[0]}); "
+ "a very stale install may still time out"
+ )
+
+
def _capture_head_sha(git_cmd, cwd) -> str | None:
"""Return the current HEAD SHA, or None if it can't be resolved."""
try:
@@ -1418,6 +1445,11 @@ def _cmd_update_impl(args, gateway_mode: bool):
# runs and failed restores preserve the stash but nothing ever mentioned it again.
_m()._warn_orphaned_update_autostashes(git_cmd, _m().PROJECT_ROOT)
+ # Heal a stale shallow checkout first: the bounded fetch below cannot
+ # finish on one (#123254), and the old post-update heal never got the
+ # chance to run because the fetch itself never succeeded.
+ _heal_stale_shallow_checkout(_m().PROJECT_ROOT, branch)
+
print("→ Fetching updates...")
if release_sha:
fetch_args = ["fetch", "--no-tags", "origin", target_ref]
diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.py
index eddb579c7cd..b6f29a46e8f 100644
--- a/hermes_cli/update_cmd_git.py
+++ b/hermes_cli/update_cmd_git.py
@@ -407,6 +407,15 @@ _FETCH_FAILURE_RULES = (
(lambda s: "Permission denied (publickey)" in s or "Host key verification failed" in s,
"✗ SSH authentication failed — check your SSH key is added to GitHub, or switch"
" `origin` to HTTPS: `git remote set-url origin https://github.com/NousResearch/hermes-agent.git`."),
+ # A wall-clock timeout kill says nothing about the transport: the fetch was
+ # likely still transferring when the cap hit (#123254) — a huge pack on a
+ # slow link, not a dead remote, and the install usually needs the shallow
+ # heal (or one manual fetch) rather than network debugging.
+ (lambda s: "network limit" in s,
+ "✗ The fetch exceeded the update time limit while still transferring — this is a"
+ " slow/large fetch, not a broken connection. A very stale shallow install can hit"
+ " this repeatedly; re-running `hermes update` (which now heals the shallow history"
+ " first) or one manual `git fetch origin` usually gets past it."),
)
diff --git a/tests/hermes_cli/test_update_fetch_failure_classifier.py b/tests/hermes_cli/test_update_fetch_failure_classifier.py
index 39395133eaf..0c9fdf453b5 100644
--- a/tests/hermes_cli/test_update_fetch_failure_classifier.py
+++ b/tests/hermes_cli/test_update_fetch_failure_classifier.py
@@ -155,3 +155,18 @@ def test_update_and_upstream_network_calls_disable_terminal_prompts(monkeypatch,
assert env["GIT_ASKPASS"] == "fixture-askpass", args
assert env["GIT_CONFIG_COUNT"] == "1", args
assert env["GIT_CONFIG_VALUE_0"] == "fixture-helper", args
+
+
+class TestTimeoutIsNotANetworkOutage:
+ def test_wall_clock_kill_reports_slow_transfer_not_dead_remote(self):
+ # The updater kills fetches on a 300s wall-clock cap; on a stale
+ # shallow install the transport is healthy and mid-transfer when the
+ # kill lands (#123254), so the diagnosis must not send the user
+ # debugging their network.
+ msg = update_cmd._classify_fetch_failure(
+ "git fetch was still running after the 300s network limit"
+ " (slow transfer, not a dead remote — a larger fetch may need"
+ " `hermes update` again or a manual `git fetch`)")
+ assert "update time limit" in msg
+ assert "not a broken connection" in msg
+ assert "Network error" not in msg
diff --git a/tests/hermes_cli/test_update_shallow_heal.py b/tests/hermes_cli/test_update_shallow_heal.py
new file mode 100644
index 00000000000..8baf6f0736c
--- /dev/null
+++ b/tests/hermes_cli/test_update_shallow_heal.py
@@ -0,0 +1,154 @@
+"""Heal-before-fetch for stale shallow installer checkouts (#123254).
+
+A depth-1 install far behind ``origin/main`` cannot finish ``git fetch origin
+main`` inside the updater's 300s network cap: the server must send the full
+ancestry of every side branch merged past the shallow boundary, every attempt
+is killed mid-transfer, and the unshallow step that would make later fetches
+incremental only ran *after* a successful update — so a stale shallow install
+could never update at all. The updater now heals the checkout before the
+bounded fetch, non-fatally, and the timeout wording no longer blames a dead
+remote for a wall-clock kill on a healthy transfer.
+
+These run against real local git repositories; only the timing caps are
+irrelevant here (the fetches are local and instant).
+"""
+
+from __future__ import annotations
+
+import subprocess
+
+import hermes_cli.gitlock as gitlock
+import hermes_cli.update_cmd as update_cmd
+
+
+def _git(cwd, *args, check=True):
+ return subprocess.run(
+ ["git", *args],
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=check,
+ )
+
+
+def _origin_with_history(tmp_path, *, allow_filter=True):
+ 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")
+ _git(origin, "commit", "--allow-empty", "-qm", "c0")
+ _git(origin, "commit", "--allow-empty", "-qm", "c1")
+ _git(origin, "tag", "v0.21.2")
+ if allow_filter:
+ # file:// transport requires opt-in; real hosting does this by default.
+ _git(origin, "config", "uploadpack.allowFilter", "true")
+ return origin
+
+
+def _shallow_clone(tmp_path, origin):
+ clone = tmp_path / "clone"
+ subprocess.run(
+ ["git", "clone", "-q", "--depth", "1", f"file://{origin}", str(clone)],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ return clone
+
+
+class TestHealShallowHistory:
+ def test_heals_stale_shallow_clone_and_returns_true(self, tmp_path):
+ origin = _origin_with_history(tmp_path)
+ clone = _shallow_clone(tmp_path, origin)
+ assert (clone / ".git" / "shallow").exists()
+
+ assert gitlock.heal_shallow_history(clone, "main") is True
+
+ assert not (clone / ".git" / "shallow").exists()
+ # The history behind the boundary is present, so the bounded fetch
+ # that follows is incremental instead of re-downloading the graph.
+ assert _git(clone, "rev-list", "--count", "--all").stdout.strip() == "2"
+
+ def test_full_clone_is_a_noop_returning_false(self, tmp_path):
+ origin = _origin_with_history(tmp_path)
+ clone = tmp_path / "clone"
+ subprocess.run(
+ ["git", "clone", "-q", f"file://{origin}", str(clone)],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+
+ assert gitlock.heal_shallow_history(clone, "main") is False
+ assert _git(clone, "rev-list", "--count", "--all").stdout.strip() == "2"
+
+ def test_origin_without_tags_still_unshallows(self, tmp_path):
+ # The tag refspec alone matches nothing on a tag-less origin and git
+ # fails the whole fetch; the branch refspec must ride along.
+ origin = _origin_with_history(tmp_path)
+ _git(origin, "tag", "-d", "v0.21.2")
+ clone = _shallow_clone(tmp_path, origin)
+
+ assert gitlock.heal_shallow_history(clone, "main") is True
+ assert not (clone / ".git" / "shallow").exists()
+
+
+class TestUpdateHealIsNonFatal:
+ def test_heal_failure_keeps_the_update_alive(self, tmp_path, monkeypatch, capsys):
+ origin = _origin_with_history(tmp_path)
+ clone = _shallow_clone(tmp_path, origin)
+
+ def broken_heal(*a, **kw):
+ raise subprocess.CalledProcessError(
+ 128, "git", stderr="fatal: filter not supported"
+ )
+
+ monkeypatch.setattr(gitlock, "heal_shallow_history", broken_heal)
+ # Must not raise: the update proceeds with the old fetch behaviour.
+ update_cmd._heal_stale_shallow_checkout(clone, "main")
+ out = capsys.readouterr().out
+ assert "Could not heal the shallow checkout" in out
+ assert "filter not supported" in out
+
+ def test_healed_checkout_prints_one_line(self, tmp_path, capsys):
+ origin = _origin_with_history(tmp_path)
+ clone = _shallow_clone(tmp_path, origin)
+
+ update_cmd._heal_stale_shallow_checkout(clone, "main")
+
+ assert "shallow checkout healed" in capsys.readouterr().out
+ assert not (clone / ".git" / "shallow").exists()
+
+ def test_full_checkout_stays_silent(self, tmp_path, capsys):
+ origin = _origin_with_history(tmp_path)
+ clone = tmp_path / "clone"
+ subprocess.run(
+ ["git", "clone", "-q", f"file://{origin}", str(clone)],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+
+ update_cmd._heal_stale_shallow_checkout(clone, "main")
+
+ assert capsys.readouterr().out == ""
+
+
+class TestTimeoutWording:
+ def test_wall_clock_kill_does_not_blame_a_dead_remote(self, monkeypatch):
+ # A wall-clock kill says nothing about the transport: the fetch may
+ # have been actively transferring a multi-hundred-MB pack (#123254).
+ def never_finishes(cmd, **kw):
+ raise subprocess.TimeoutExpired(cmd, update_cmd.NETWORK_GIT_TIMEOUT_SECONDS)
+
+ monkeypatch.setattr(update_cmd.subprocess, "run", never_finishes)
+ result = update_cmd._git_run(
+ ["git"], ["fetch", "origin", "main"], cwd="/tmp", network=True
+ )
+ assert result.returncode == 124
+ assert "no response from the remote" not in result.stderr
+ assert "network limit" in result.stderr
+ assert "manual `git fetch`" in result.stderr