The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): anchor discarded local commits before the diverged reset
moep9021cc8bfef39c
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 702742bd18c..d16623930ee 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -793,22 +793,32 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha) -> None:print(" Then re-run the update. Local work is untouched.")sys.exit(1)return- # Same branch: a true upstream force-push/rebase; local changes are stashed, so reset.- # Orphan divergence (no common ancestor: corrupted HEAD, re-init) would lose the whole- # local graph, so park pre_pull_sha behind a rescue ref first.+ # Same branch: the reset below is right either way, but the two causes of divergence here+ # are indistinguishable from the checkout alone. An upstream force-push/rebase loses+ # nothing; local commits on this branch lose everything, and the reflog is the only way+ # back — a 90-day expiry the user has to know to reach for, in a directory Hermes updates+ # unattended. So park pre_pull_sha behind a rescue ref for BOTH, orphan divergence (no+ # common ancestor: corrupted HEAD, re-init) included.merge_base_result = _git_run(git_cmd, ["merge-base", "HEAD", f"origin/{branch}"])- has_common_ancestor = merge_base_result.returncode == 0 and merge_base_result.stdout.strip()- if not has_common_ancestor and pre_pull_sha:+ has_common_ancestor = bool(+ merge_base_result.returncode == 0 and merge_base_result.stdout.strip())+ if pre_pull_sha:from datetime import datetime as _dt, timezone# SHA suffix so two updates in the same second get distinct refs.+ kind = "diverged" if has_common_ancestor else "orphan"rescue_ref = (- f"refs/hermes-update-backups/orphan-{branch}-"+ f"refs/hermes-update-backups/{kind}-{branch}-"f"{_dt.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}-{pre_pull_sha[:12]}")- head = f" ⚠ Local history shares no common ancestor with origin/{branch} (orphan divergence) — "+ head = (+ f" ⚠ Local history has diverged from origin/{branch} — "+ if has_common_ancestor else+ f" ⚠ Local history shares no common ancestor with origin/{branch} (orphan divergence) — ")if _git_run(git_cmd, ["update-ref", rescue_ref, pre_pull_sha]).returncode == 0:print(f"{head}backed up current HEAD to {rescue_ref} before resetting. "f"This backup expires after {_ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days.")+ if has_common_ancestor:+ print(f" Recover local commits with: git log {rescue_ref}")else:# update-ref failure is intentionally non-fatal, but never claim a backup exists.print(diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.pyindex 0b32663651f..1417195fdbb 100644--- a/hermes_cli/update_cmd_git.py+++ b/hermes_cli/update_cmd_git.py@@ -41,7 +41,11 @@ def _git_stdout(git_cmd, args, cwd, **kw) -> Optional[str]:def _prune_orphan_rescue_refs(git_cmd, cwd, branch, keep=_ORPHAN_RESCUE_REFS_TO_KEEP, max_age_days=_ORPHAN_RESCUE_REF_MAX_AGE_DAYS) -> None:- """Expire old orphan rescue refs (``refs/hermes-update-backups/orphan-<branch>-<ts>-<sha>``).+ """Expire old rescue refs (``refs/hermes-update-backups/<kind>-<branch>-<ts>-<sha>``).++ ``<kind>`` is ``orphan`` (no common ancestor) or ``diverged`` (local commits on the target+ branch). Both are written before the same ``reset --hard`` and both pin objects, so both+ expire on the same terms; each kind keeps its own ``keep`` newest.Each ref pins a possibly multi-GB snapshot against ``git gc``, so a repeatedly corrupted install wouldgrow ``.git`` unbounded. Keep the ``keep`` newest AND drop any older than ``max_age_days`` by the@@ -54,18 +58,22 @@ def _prune_orphan_rescue_refs("""from hermes_cli.update_cmd import _git_runwith suppress(OSError):- prefix = f"refs/hermes-update-backups/orphan-{branch}-"- list_result = _git_run(git_cmd, ["for-each-ref", "--format=%(refname)", "--sort=refname", f"{prefix}*"], cwd)- if list_result.returncode != 0:- return- refs = [line.strip() for line in list_result.stdout.splitlines() if line.strip()]- stale = set(refs[:-keep] if keep > 0 else refs)- if max_age_days > 0:- cutoff = datetime.now(timezone.utc) - timedelta(days=max_age_days)- for ref in refs:- with suppress(ValueError):- if datetime.strptime(ref[len(prefix):][:15], "%Y%m%d-%H%M%S").replace(tzinfo=timezone.utc) < cutoff:- stale.add(ref)+ stale: set[str] = set()+ for kind in ("orphan", "diverged"):+ prefix = f"refs/hermes-update-backups/{kind}-{branch}-"+ list_result = _git_run(+ git_cmd, ["for-each-ref", "--format=%(refname)", "--sort=refname", f"{prefix}*"], cwd)+ if list_result.returncode != 0:+ return+ refs = [line.strip() for line in list_result.stdout.splitlines() if line.strip()]+ stale |= set(refs[:-keep] if keep > 0 else refs)+ if max_age_days > 0:+ cutoff = datetime.now(timezone.utc) - timedelta(days=max_age_days)+ for ref in refs:+ with suppress(ValueError):+ stamp = datetime.strptime(ref[len(prefix):][:15], "%Y%m%d-%H%M%S")+ if stamp.replace(tzinfo=timezone.utc) < cutoff:+ stale.add(ref)for ref in sorted(stale):_git_run(git_cmd, ["update-ref", "-d", ref], cwd)diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.pyindex f77a1a7b343..1cf5b2450ad 100644--- a/tests/hermes_cli/test_update_autostash.py+++ b/tests/hermes_cli/test_update_autostash.py@@ -399,9 +399,19 @@ def test_prune_orphan_rescue_refs_leaves_unparseable_names_alone():assert delete_calls == []-def test_cmd_update_ordinary_divergence_skips_rescue_ref(monkeypatch, tmp_path, capsys):- """Common ancestor still exists (e.g. upstream force-push) → no rescue- ref, no orphan messaging, behavior identical to before #87694."""+def test_cmd_update_ordinary_divergence_also_leaves_a_rescue_ref(monkeypatch, tmp_path, capsys):+ """Common ancestor still exists → rescue ref under the ``diverged-`` kind, no orphan messaging.++ Divergence on the target branch has two causes the checkout cannot tell apart: an upstream+ force-push, where nothing local is lost, and local commits on that branch, where the reset+ discards all of them. This case used to write no ref at all, which is correct only for the+ first cause.++ The #87694 size concern is specific to the orphan shape: there ``pre_pull_sha`` is an+ autostash orphan commit carrying a full working-tree snapshot, which can be multi-GB. Here it+ is ordinary branch history whose objects the reflog pins anyway for its expiry window, so the+ ref adds no meaningful footprint — and it expires under the same keep/age rules.+ """_setup_update_mocks(monkeypatch, tmp_path)side_effect, recorded = _make_update_side_effect(@@ -411,11 +421,17 @@ def test_cmd_update_ordinary_divergence_skips_rescue_ref(monkeypatch, tmp_path,hermes_main.cmd_update(SimpleNamespace())- update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)]- assert update_ref_calls == []+ update_ref_calls = [+ c for c in recorded+ if "update-ref" in " ".join(str(x) for x in c) and "-d" not in c+ ]+ assert len(update_ref_calls) == 1, "the discarded local history needs exactly one anchor"+ ref_name = str(update_ref_calls[0][2])+ assert ref_name.startswith("refs/hermes-update-backups/diverged-main-")out = capsys.readouterr().outassert "orphan divergence" not in out+ assert "Local history has diverged" in outassert "Fast-forward not possible (history diverged), resetting to match remote" in outdiff --git a/tests/hermes_cli/test_update_diverged_rescue_ref.py b/tests/hermes_cli/test_update_diverged_rescue_ref.pynew file mode 100644index 00000000000..470ea77206e--- /dev/null+++ b/tests/hermes_cli/test_update_diverged_rescue_ref.py@@ -0,0 +1,85 @@+"""`hermes update` must not drop local commits without leaving a way back.++When the checkout sits on the update's target branch and its history has+diverged, the update resets hard to ``origin/<branch>``. Divergence there has+two indistinguishable causes: an upstream force-push (nothing local is lost)+and local commits on that branch (everything is). The rescue ref that makes+the second case recoverable was written only for orphan divergence — a+disjoint history — which is the rarer of the two.+"""++from __future__ import annotations++import subprocess++import pytest++from hermes_cli import update_cmd+++GIT = ["git"]+++def _git(repo, *args, check=True):+ return subprocess.run(+ GIT + list(args), cwd=repo, capture_output=True, text=True, check=check)+++def _commit(repo, name, text):+ (repo / name).write_text(text, encoding="utf-8")+ _git(repo, "add", name)+ _git(repo, "-c", "user.name=t", "-c", "[email protected]",+ "commit", "-q", "-m", f"add {name}")+ return _git(repo, "rev-parse", "HEAD").stdout.strip()+++def diverged_checkout(tmp_path, monkeypatch):+ """A checkout on ``main`` carrying a local commit its ``origin/main`` does not have."""+ upstream = tmp_path / "upstream"+ upstream.mkdir()+ _git(upstream, "init", "-q", "-b", "main")+ _commit(upstream, "shared.txt", "shared\n")+ _commit(upstream, "upstream-only.txt", "upstream\n")++ checkout = tmp_path / "checkout"+ _git(tmp_path, "clone", "-q", str(upstream), str(checkout))+ _git(checkout, "reset", "-q", "--hard", "HEAD~1") # back to the shared commit+ local_sha = _commit(checkout, "local-fix.txt", "local\n") # diverges from origin/main++ monkeypatch.setattr(update_cmd._m(), "PROJECT_ROOT", checkout)+ return checkout, local_sha+++def _rescue_refs(checkout):+ out = _git(checkout, "for-each-ref", "--format=%(refname) %(objectname)",+ "refs/hermes-update-backups/").stdout+ return dict(line.split() for line in out.splitlines() if line.strip())+++def test_reset_leaves_a_rescue_ref_for_the_discarded_commits(diverged_checkout):+ """The reset is fine; losing the only pointer to the local work is not."""+ checkout, local_sha = diverged_checkout++ update_cmd._reconcile_diverged_checkout(GIT, "main", local_sha)++ head = _git(checkout, "rev-parse", "HEAD").stdout.strip()+ origin = _git(checkout, "rev-parse", "origin/main").stdout.strip()+ assert head == origin, "the reset itself must still happen"++ refs = _rescue_refs(checkout)+ assert local_sha in refs.values(), (+ "the discarded commit must stay reachable through a rescue ref; without one "+ f"it is recoverable only from the reflog. refs found: {refs}")+++def test_the_rescue_ref_carries_the_whole_discarded_history(diverged_checkout):+ """A ref on the tip is enough: every dropped commit is reachable from it."""+ checkout, local_sha = diverged_checkout++ update_cmd._reconcile_diverged_checkout(GIT, "main", local_sha)++ ref = next(r for r, sha in _rescue_refs(checkout).items() if sha == local_sha)+ listed = _git(checkout, "log", "--format=%H", ref).stdout.split()+ assert local_sha in listed+ assert len(listed) >= 2, "the shared base must remain reachable from the rescue ref too"