Skip to content

The agent that grows with you

fix(update): back up HEAD to a rescue ref before orphan-history reset

JoaoMarcos4486b50fb43a77
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index e9af95edd2b..0158390266e 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -5180,10 +5180,13 @@ _LAZY_COMMAND_EXPORTS = {
"_npm_lockfile_changed",
"_npm_manifest_paths",
"_npm_manifests_digest",
+ "_ORPHAN_RESCUE_REF_MAX_AGE_DAYS",
+ "_ORPHAN_RESCUE_REFS_TO_KEEP",
"_orphaned_desktop_backend_pids",
"_pending_fleet_restart_needed",
"_pause_windows_gateways_for_update",
"_print_curator_first_run_notice",
+ "_prune_orphan_rescue_refs",
"_print_curator_recent_run_notice",
"_print_fts_optimize_available_notice",
"_print_parked_branch_kept_notice",
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 0009b70a8ad..2c42fbd9893 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -549,6 +549,82 @@ def _capture_head_sha(git_cmd, cwd) -> str | None:
except (subprocess.CalledProcessError, OSError):
return None
+_ORPHAN_RESCUE_REFS_TO_KEEP = 10
+_ORPHAN_RESCUE_REF_MAX_AGE_DAYS = 30
+
+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 so backups stay bounded.
+
+ Each orphan-history divergence (#87694) parks the pre-reset HEAD under
+ ``refs/hermes-update-backups/orphan-<branch>-<ts>-<sha>``. A rescue ref
+ pins every object reachable from that commit against ``git gc`` — and in
+ the incident shape those objects include a full working-tree snapshot
+ (the autostash orphan commit), which can be multi-GB when the tree holds
+ large stray files. Left alone, a repeatedly corrupted install would grow
+ ``.git`` without bound.
+
+ Two independent limits, both enforced on every orphan incident:
+
+ - **Count cap:** keep only the ``keep`` most-recent refs.
+ - **Age expiry:** drop any ref older than ``max_age_days``, parsed from
+ the ``YYYYMMDD-HHMMSS`` timestamp embedded in the ref name (refs with
+ unparseable names are left alone rather than guessed at).
+
+ Ref names sort chronologically (timestamp prefix), so lexicographic
+ order from ``for-each-ref`` is also creation order. Deleting a ref makes
+ its objects eligible for ``git gc``; actual disk reclaim happens on the
+ next gc (git auto-gc, or the user running ``git gc``). Best-effort: any
+ failure here must not block the update itself.
+ """
+ try:
+ list_result = subprocess.run(
+ git_cmd + [
+ "for-each-ref",
+ "--format=%(refname)",
+ "--sort=refname",
+ f"refs/hermes-update-backups/orphan-{branch}-*",
+ ],
+ cwd=cwd,
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ )
+ 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)
+ # Age expiry: ref names embed a UTC YYYYMMDD-HHMMSS timestamp right
+ # after the branch segment; anything older than max_age_days goes.
+ if max_age_days > 0:
+ from datetime import timedelta, timezone
+
+ cutoff = datetime.now(timezone.utc) - timedelta(days=max_age_days)
+ prefix = f"refs/hermes-update-backups/orphan-{branch}-"
+ for ref in refs:
+ stamp = ref[len(prefix):][:15] # "YYYYMMDD-HHMMSS"
+ try:
+ ref_time = datetime.strptime(stamp, "%Y%m%d-%H%M%S").replace(
+ tzinfo=timezone.utc
+ )
+ except ValueError:
+ continue
+ if ref_time < cutoff:
+ stale.add(ref)
+ for ref in sorted(stale):
+ subprocess.run(
+ git_cmd + ["update-ref", "-d", ref],
+ cwd=cwd,
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ )
+ except OSError:
+ pass
+
# Files that define the editable install. A pull that touches none of them
# cannot have invalidated it.
_INSTALL_DEFINING_FILES = (
@@ -8710,6 +8786,64 @@ def _cmd_update_impl(args, gateway_mode: bool):
# Same branch as the update target — a true upstream
# force-push/rebase. Local changes are already stashed;
# reset to match the remote exactly (original behaviour).
+ #
+ # Divergence here comes in two shapes: ordinary (a common
+ # ancestor still exists — the reset below is a normal,
+ # safe re-sync onto the remote) and orphan (no common
+ # ancestor at all, e.g. a corrupted local HEAD or a repo
+ # re-init — see #87694). In the orphan case `reset --hard`
+ # would silently discard the entire local commit graph
+ # with no way back, so park pre_pull_sha behind a rescue
+ # ref first.
+ merge_base_result = subprocess.run(
+ git_cmd + ["merge-base", "HEAD", f"origin/{branch}"],
+ cwd=_m().PROJECT_ROOT,
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ )
+ has_common_ancestor = bool(
+ merge_base_result.returncode == 0
+ and merge_base_result.stdout.strip()
+ )
+ if not has_common_ancestor and pre_pull_sha:
+ from datetime import datetime as _dt, timezone
+
+ # Suffix with the pre-pull SHA (not just a second-
+ # resolution timestamp) so two updates racing within
+ # the same second (e.g. a retried update) get distinct
+ # refs instead of the second `update-ref` silently
+ # overwriting the first backup.
+ rescue_ref = (
+ f"refs/hermes-update-backups/orphan-{branch}-"
+ f"{_dt.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}"
+ f"-{pre_pull_sha[:12]}"
+ )
+ update_ref_result = subprocess.run(
+ git_cmd + ["update-ref", rescue_ref, pre_pull_sha],
+ cwd=_m().PROJECT_ROOT,
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ )
+ if update_ref_result.returncode == 0:
+ print(
+ " ⚠ Local history shares no common ancestor with "
+ f"origin/{branch} (orphan divergence) — backed up "
+ f"current HEAD to {rescue_ref} before resetting. "
+ f"This backup expires after "
+ f"{_ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days."
+ )
+ else:
+ # update-ref's return code is intentionally not
+ # fatal (disk full, permissions) — but don't tell
+ # the user a backup exists when the write failed.
+ print(
+ " ⚠ Local history shares no common ancestor with "
+ f"origin/{branch} (orphan divergence) — attempted "
+ f"to back up current HEAD to {rescue_ref} before "
+ "resetting, but the backup write failed "
+ f"(pre-reset SHA was {pre_pull_sha})."
+ )
+ _prune_orphan_rescue_refs(git_cmd, _m().PROJECT_ROOT, branch)
print(
" ⚠ Fast-forward not possible (history diverged), resetting to match remote..."
)
diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.py
index a04d9c4977a..f7147dfa5ca 100644
--- a/tests/hermes_cli/test_update_autostash.py
+++ b/tests/hermes_cli/test_update_autostash.py
@@ -40,6 +40,34 @@ def _patch_managed_uv(request):
yield
[email protected](autouse=True)
+def _patch_gateway_discovery():
+ """Keep cmd_update's gateway auto-restart phase off this machine's gateways.
+
+ Tests in this file that reach the full success path (e.g. the #87694
+ orphan-history rescue-ref tests) would otherwise hit real gateway
+ discovery: an unmocked ``find_gateway_pids`` on a box with a live gateway
+ reaches the conftest live-system guard and turns into a spurious
+ ``sys.exit(1)`` (#78574). Discovery returning nothing makes the phase a
+ clean no-op — none of the tests here assert on gateway restarts.
+
+ ``_purge_stale_hermes_modules`` must also be stubbed: it evicts
+ ``hermes_cli.gateway`` from ``sys.modules`` mid-update, and the restart
+ phase's fresh ``from hermes_cli.gateway import ...`` then loads an
+ UNPATCHED copy of the module — silently discarding every mock here and
+ letting real gateway discovery (and real ``os.kill``) run on the dev box.
+ """
+ with patch("hermes_cli.gateway.find_gateway_pids", return_value=[]), \
+ patch("hermes_cli.gateway.supports_systemd_services", return_value=False), \
+ patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]), \
+ patch("hermes_cli.update_inventory.collect_runtime_inventory", return_value=None), \
+ patch("hermes_cli.update_inventory.report_unaccounted_runtimes", return_value=False), \
+ patch.object(hermes_main, "_fleet_probe_expected_runtimes", lambda *a, **kw: False), \
+ patch.object(hermes_main, "_purge_stale_hermes_modules", lambda *a, **kw: None), \
+ patch("hermes_cli.update_receipt.collect_fleet_versions", return_value=[]):
+ yield
+
+
@@ -118,9 +146,33 @@ def _make_update_side_effect(
reset_fails=False,
fetch_fails=False,
fetch_stderr="",
+ merge_base_exists=True,
+ update_ref_fails=False,
+ pre_pull_sha_unavailable=False,
+ existing_rescue_refs=None,
):
- """Build a subprocess.run side_effect for cmd_update tests."""
+ """Build a subprocess.run side_effect for cmd_update tests.
+
+ ``merge_base_exists`` controls the ``git merge-base HEAD origin/<branch>``
+ probe used by the ff-only-fallback orphan-history guard (#87694): True
+ (default) simulates ordinary divergence (a common ancestor exists, e.g.
+ upstream force-push), False simulates orphan/unrelated-history divergence
+ (no common ancestor at all).
+
+ ``update_ref_fails`` simulates ``git update-ref`` itself failing (disk
+ full, permissions) when writing the orphan rescue ref.
+
+ ``pre_pull_sha_unavailable`` simulates ``_capture_head_sha`` being unable
+ to resolve HEAD before the pull (empty rev-parse output) — the rescue-ref
+ guard requires a truthy ``pre_pull_sha`` and must degrade gracefully
+ without one.
+
+ ``existing_rescue_refs`` simulates the refs already present under
+ ``refs/hermes-update-backups/orphan-<branch>-*`` (oldest first) so the
+ ``_prune_orphan_rescue_refs`` cleanup pass has something to trim.
+ """
recorded = []
+ head_sha_calls = []
def side_effect(cmd, **kwargs):
recorded.append(cmd)
@@ -131,10 +183,43 @@ def _make_update_side_effect(
return SimpleNamespace(stdout="", stderr="", returncode=0)
if "rev-parse" in joined and "--abbrev-ref" in joined:
return SimpleNamespace(stdout=f"{current_branch}\n", stderr="", returncode=0)
+ if "show-current" in joined:
+ return SimpleNamespace(stdout=f"{current_branch}\n", stderr="", returncode=0)
+ if "rev-parse" in joined and "HEAD" in joined:
+ # First call = pre-pull HEAD, every later call = post-pull HEAD
+ # (issue #79678's "did HEAD actually move" guard depends on these
+ # differing after a successful reset/merge).
+ head_sha_calls.append(1)
+ if len(head_sha_calls) == 1:
+ if pre_pull_sha_unavailable:
+ return SimpleNamespace(stdout="", stderr="", returncode=0)
+ return SimpleNamespace(
+ stdout="1111111111111111111111111111111111111beef\n", stderr="", returncode=0
+ )
+ return SimpleNamespace(
+ stdout="2222222222222222222222222222222222222cafe\n", stderr="", returncode=0
+ )
if "checkout" in joined and "main" in joined:
return SimpleNamespace(stdout="", stderr="", returncode=0)
if "rev-list" in joined:
return SimpleNamespace(stdout=f"{commit_count}\n", stderr="", returncode=0)
+ if "merge-base" in joined:
+ if merge_base_exists:
+ return SimpleNamespace(stdout="abc123deadbeef\n", stderr="", returncode=0)
+ return SimpleNamespace(
+ stdout="", stderr="fatal: Not a valid commit name origin/main\n", returncode=1
+ )
+ if "for-each-ref" in joined:
+ refs = existing_rescue_refs or []
+ return SimpleNamespace(stdout="\n".join(refs) + ("\n" if refs else ""), stderr="", returncode=0)
+ if "update-ref" in joined and "-d" in cmd:
+ return SimpleNamespace(stdout="", stderr="", returncode=0)
+ if "update-ref" in joined:
+ if update_ref_fails:
+ return SimpleNamespace(
+ stdout="", stderr="fatal: unable to write ref\n", returncode=128
+ )
+ return SimpleNamespace(stdout="", stderr="", returncode=0)
if "--ff-only" in joined:
if ff_only_fails:
return SimpleNamespace(
@@ -193,6 +278,241 @@ def test_cmd_update_skips_stash_restore_when_reset_fails(monkeypatch, tmp_path,
assert "preserved in stash" in out
+# ---------------------------------------------------------------------------
+# #87694: orphan/unrelated-history divergence must be backed up to a rescue
+# ref before `reset --hard` discards it (ordinary divergence is unaffected).
+# ---------------------------------------------------------------------------
+
+def test_cmd_update_orphan_history_backs_up_before_reset(monkeypatch, tmp_path, capsys):
+ """No common ancestor with origin/<branch> → HEAD is parked behind a
+ ``refs/hermes-update-backups/orphan-*`` ref before the reset proceeds."""
+ _setup_update_mocks(monkeypatch, tmp_path)
+
+ side_effect, recorded = _make_update_side_effect(
+ ff_only_fails=True, merge_base_exists=False,
+ )
+ monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
+
+ 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 len(update_ref_calls) == 1
+ ref_name = update_ref_calls[0][update_ref_calls[0].index("update-ref") + 1]
+ assert ref_name.startswith("refs/hermes-update-backups/orphan-main-")
+ assert update_ref_calls[0][update_ref_calls[0].index("update-ref") + 2] == (
+ "1111111111111111111111111111111111111beef"
+ )
+ # Ref name carries the pre-pull SHA, not just a second-resolution
+ # timestamp, so two updates racing within the same second don't collide.
+ assert ref_name.endswith("-111111111111")
+
+ out = capsys.readouterr().out
+ assert "orphan divergence" in out
+ assert ref_name in out
+ # The user is told the backup is temporary and when it expires.
+ assert f"expires after {hermes_main._ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days" in out
+
+
+def test_cmd_update_orphan_rescue_ref_write_failure_message_is_honest(monkeypatch, tmp_path, capsys):
+ """When ``git update-ref`` fails, the printed message must not claim a
+ backup exists — it should say the write was attempted and failed."""
+ _setup_update_mocks(monkeypatch, tmp_path)
+
+ side_effect, recorded = _make_update_side_effect(
+ ff_only_fails=True, merge_base_exists=False, update_ref_fails=True,
+ )
+ monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
+
+ hermes_main.cmd_update(SimpleNamespace())
+
+ out = capsys.readouterr().out
+ assert "orphan divergence" in out
+ assert "backup write failed" in out
+ assert "backed up current HEAD" not in out
+
+
+def test_cmd_update_orphan_rescue_refs_pruned_beyond_keep_limit(monkeypatch, tmp_path, capsys):
+ """Recent orphan rescue refs beyond the retention count are deleted so a
+ repeatedly corrupted install doesn't pin unbounded objects against gc."""
+ from datetime import datetime, timedelta, timezone
+
+ _setup_update_mocks(monkeypatch, tmp_path)
+
+ # All refs are recent (within the age window) so only the count cap
+ # applies — the age-expiry path is exercised separately below.
+ now = datetime.now(timezone.utc)
+ total = hermes_main._ORPHAN_RESCUE_REFS_TO_KEEP + 2
+ stale_refs = [
+ "refs/hermes-update-backups/orphan-main-"
+ f"{(now - timedelta(hours=total - i)).strftime('%Y%m%d-%H%M%S')}-abc"
+ for i in range(total)
+ ]
+ side_effect, recorded = _make_update_side_effect(
+ ff_only_fails=True, merge_base_exists=False, existing_rescue_refs=stale_refs,
+ )
+ monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
+
+ hermes_main.cmd_update(SimpleNamespace())
+
+ delete_calls = [
+ c for c in recorded
+ if "update-ref" in " ".join(str(x) for x in c) and "-d" in c
+ ]
+ assert len(delete_calls) == total - hermes_main._ORPHAN_RESCUE_REFS_TO_KEEP
+ deleted_refs = {c[c.index("-d") + 1] for c in delete_calls}
+ assert deleted_refs == set(stale_refs[: total - hermes_main._ORPHAN_RESCUE_REFS_TO_KEEP])
+
+
+def test_cmd_update_orphan_rescue_refs_expired_by_age(monkeypatch, tmp_path, capsys):
+ """Rescue refs older than the max-age window are deleted even when the
+ count cap alone would have kept them — the age expiry is what bounds a
+ multi-GB snapshot's lifetime for a user who never runs another orphan
+ incident past the count cap."""
+ from datetime import datetime, timedelta, timezone
+
+ _setup_update_mocks(monkeypatch, tmp_path)
+
+ now = datetime.now(timezone.utc)
+ old = now - timedelta(days=hermes_main._ORPHAN_RESCUE_REF_MAX_AGE_DAYS + 5)
+ fresh = now - timedelta(days=1)
+ expired_ref = (
+ "refs/hermes-update-backups/orphan-main-"
+ f"{old.strftime('%Y%m%d-%H%M%S')}-old1"
+ )
+ fresh_ref = (
+ "refs/hermes-update-backups/orphan-main-"
+ f"{fresh.strftime('%Y%m%d-%H%M%S')}-new1"
+ )
+ side_effect, recorded = _make_update_side_effect(
+ ff_only_fails=True, merge_base_exists=False,
+ existing_rescue_refs=[expired_ref, fresh_ref],
+ )
+ monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
+
+ hermes_main.cmd_update(SimpleNamespace())
+
+ delete_calls = [
+ c for c in recorded
+ if "update-ref" in " ".join(str(x) for x in c) and "-d" in c
+ ]
+ deleted_refs = {c[c.index("-d") + 1] for c in delete_calls}
+ assert deleted_refs == {expired_ref}
+
+
+def test_prune_orphan_rescue_refs_leaves_unparseable_names_alone():
+ """A ref whose timestamp segment doesn't parse must never be age-deleted
+ (it can still fall to the count cap, but not to a guessed age)."""
+ from types import SimpleNamespace as NS
+ from unittest.mock import patch as mock_patch
+
+ weird = "refs/hermes-update-backups/orphan-main-not-a-timestamp-xyz"
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append(cmd)
+ if "for-each-ref" in cmd:
+ return NS(stdout=weird + "\n", stderr="", returncode=0)
+ return NS(stdout="", stderr="", returncode=0)
+
+ with mock_patch.object(hermes_main.subprocess, "run", side_effect=fake_run):
+ hermes_main._prune_orphan_rescue_refs(["git"], ".", "main")
+
+ delete_calls = [c for c in calls if "update-ref" in c and "-d" in c]
+ 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."""
+ _setup_update_mocks(monkeypatch, tmp_path)
+
+ side_effect, recorded = _make_update_side_effect(
+ ff_only_fails=True, merge_base_exists=True,
+ )
+ monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
+
+ 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 == []
+
+ out = capsys.readouterr().out
+ assert "orphan divergence" not in out
+ assert "Fast-forward not possible (history diverged), resetting to match remote" in out
+
+
+def test_cmd_update_orphan_rescue_ref_write_failure_is_non_fatal(monkeypatch, tmp_path, capsys):
+ """#87694 stress test: ``git update-ref`` itself fails (disk full,
+ permissions) while parking the orphan rescue ref. The backup attempt is
+ best-effort — so the reset must still proceed and the update succeed."""
+ _setup_update_mocks(monkeypatch, tmp_path)
+
+ side_effect, recorded = _make_update_side_effect(
+ ff_only_fails=True, merge_base_exists=False, update_ref_fails=True,
+ )
+ monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
+
+ 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 len(update_ref_calls) == 1
+
+ reset_calls = [
+ c for c in recorded if "reset" in " ".join(str(x) for x in c) and "--hard" in c
+ ]
+ assert len(reset_calls) == 1
+
+ out = capsys.readouterr().out
+ assert "orphan divergence" in out
+
+
+def test_cmd_update_orphan_guard_skips_rescue_ref_when_pre_pull_sha_missing(
+ monkeypatch, tmp_path, capsys
+):
+ """#87694 stress test: if capturing the pre-pull HEAD SHA itself fails
+ (empty ``rev-parse HEAD`` output), the rescue-ref guard requires a
+ truthy ``pre_pull_sha`` and must skip the backup rather than writing a
+ ref pointing at nothing — the reset must still proceed without crashing.
+ """
+ _setup_update_mocks(monkeypatch, tmp_path)
+
+ side_effect, recorded = _make_update_side_effect(
+ ff_only_fails=True, merge_base_exists=False, pre_pull_sha_unavailable=True,
+ )
+ monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
+
+ 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 == []
+
+ out = capsys.readouterr().out
+ assert "orphan divergence" not in out
+
+
+def test_cmd_update_orphan_rescue_ref_persists_when_reset_fails(monkeypatch, tmp_path, capsys):
+ """#87694 stress test: even when the subsequent ``reset --hard`` itself
+ fails, the rescue ref must already have been written — the backup is
+ not lost just because the overall update aborts."""
+ _setup_update_mocks(monkeypatch, tmp_path)
+
+ side_effect, recorded = _make_update_side_effect(
+ ff_only_fails=True, merge_base_exists=False, reset_fails=True,
+ )
+ monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
+
+ with pytest.raises(SystemExit) as exc_info:
+ hermes_main.cmd_update(SimpleNamespace())
+ assert exc_info.value.code == 1
+
+ update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)]
+ assert len(update_ref_calls) == 1
+
+ out = capsys.readouterr().out
+ assert "orphan divergence" in out
+ assert "Failed to reset to origin/main" in out
+
+
# ---------------------------------------------------------------------------
# Non-interactive update.non_interactive_local_changes setting
# (chat app / gateway): "discard" throws stashed changes away, "stash"
@@ -792,3 +1112,123 @@ def test_gateway_restore_prompt_defaults_to_keep_stash(tmp_path, capsys):
assert restored is False
assert prompts == [("Restore local changes now? [y/N]", "n")]
assert "still preserved in git stash" in capsys.readouterr().out
+
+
+# ---------------------------------------------------------------------------
+# #87694: real-git sanity check for the merge-base premise the orphan guard
+# relies on — two independently-initialized repos (no shared history) must
+# report no merge-base, while an ordinary branch divergence must report one.
+# ---------------------------------------------------------------------------
+
+def test_merge_base_detects_orphan_vs_ordinary_divergence_with_real_git(tmp_path):
+ """Anchors the assumption behind the #87694 orphan-history guard: `git
+ merge-base` fails/empties on truly unrelated histories, and succeeds on
+ ordinary (e.g. force-pushed) divergence. If a future git version changes
+ this contract, this test breaks instead of the guard silently going
+ inert."""
+ import shutil
+ import subprocess
+
+ if shutil.which("git") is None:
+ pytest.skip("git not available")
+
+ def git(cwd, *args, check=True):
+ return subprocess.run(
+ ["git", *args], cwd=cwd, capture_output=True, text=True, check=check
+ )
+
+ # Ordinary divergence: two branches of the SAME repo, one reset to an
+ # earlier point then given a new commit (simulates an upstream force-push).
+ ordinary = tmp_path / "ordinary"
+ ordinary.mkdir()
+ git(ordinary, "init", "-q", "-b", "main")
+ git(ordinary, "config", "user.email", "[email protected]")
+ git(ordinary, "config", "user.name", "t")
+ (ordinary / "f.txt").write_text("v1\n")
+ git(ordinary, "add", "-A")
+ git(ordinary, "commit", "-qm", "init")
+ git(ordinary, "checkout", "-qb", "origin-main")
+ (ordinary / "f.txt").write_text("v2\n")
+ git(ordinary, "add", "-A")
+ git(ordinary, "commit", "-qm", "upstream")
+ git(ordinary, "checkout", "-q", "main")
+ result = git(ordinary, "merge-base", "HEAD", "origin-main", check=False)
+ assert result.returncode == 0
+ assert result.stdout.strip()
+
+ # Orphan divergence: two independently-init'd repos wired as remotes,
+ # sharing zero history.
+ orphan = tmp_path / "orphan"
+ orphan.mkdir()
+ git(orphan, "init", "-q", "-b", "main")
+ git(orphan, "config", "user.email", "[email protected]")
+ git(orphan, "config", "user.name", "t")
+ (orphan / "f.txt").write_text("local\n")
+ git(orphan, "add", "-A")
+ git(orphan, "commit", "-qm", "local init")
+
+ remote = tmp_path / "orphan-remote"
+ remote.mkdir()
+ git(remote, "init", "-q", "-b", "main")
+ git(remote, "config", "user.email", "[email protected]")
+ git(remote, "config", "user.name", "t")
+ (remote / "f.txt").write_text("remote\n")
+ git(remote, "add", "-A")
+ git(remote, "commit", "-qm", "remote init")
+
+ git(orphan, "remote", "add", "origin", str(remote))
+ git(orphan, "fetch", "-q", "origin")
+ result = git(orphan, "merge-base", "HEAD", "origin/main", check=False)
+ assert result.returncode != 0
+ assert not result.stdout.strip()
+
+
+def test_prune_orphan_rescue_refs_with_real_git_unpins_objects(tmp_path):
+ """End-to-end with real git: an orphan rescue ref pins a snapshot's
+ objects against gc; pruning the ref (age-expired) makes them collectable.
+ This is the sabotage/size test for the #87745 bounded-growth mitigation."""
+ import shutil
+ import subprocess
+
+ if shutil.which("git") is None:
+ pytest.skip("git not available")
+
+ def git(*args, check=True):
+ return subprocess.run(
+ ["git", *args], cwd=tmp_path, capture_output=True, text=True, check=check
+ )
+
+ git("init", "-q", "-b", "main")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "t")
+ git("config", "gc.auto", "0")
+ (tmp_path / "f.txt").write_text("base\n")
+ git("add", "-A")
+ git("commit", "-qm", "init")
+
+ # Snapshot commit carrying a "large" payload (scaled down for CI).
+ import os
+
+ (tmp_path / "big.bin").write_bytes(os.urandom(512 * 1024))
+ git("add", "-A")
+ git("commit", "-qm", "snapshot")
+ snap_sha = git("rev-parse", "HEAD").stdout.strip()
+
+ # Rewind, park the snapshot behind an AGE-EXPIRED rescue ref.
+ git("reset", "-q", "--hard", "HEAD~1")
+ old_ref = "refs/hermes-update-backups/orphan-main-20200101-000000-" + snap_sha[:12]
+ git("update-ref", old_ref, snap_sha)
+
+ # With the ref present, gc cannot drop the snapshot objects.
+ git("reflog", "expire", "--expire=now", "--all")
+ git("gc", "-q", "--prune=now")
+ assert git("cat-file", "-e", snap_sha, check=False).returncode == 0
+
+ # Prune (the ref's 2020 timestamp is way past the age window) → ref gone.
+ hermes_main._prune_orphan_rescue_refs(["git"], tmp_path, "main")
+ remaining = git("for-each-ref", "refs/hermes-update-backups/").stdout
+ assert old_ref not in remaining
+
+ # And gc can now reclaim the snapshot's objects.
+ git("gc", "-q", "--prune=now")
+ assert git("cat-file", "-e", snap_sha, check=False).returncode != 0