The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): keep commits made on a detached HEAD behind a named rescue ref
teknium1ff46826872c7
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex d8ece26c722..bab5db9dc0a 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -91,7 +91,7 @@ from hermes_cli.update_cmd_git import ( # noqa: F401_branch_head_label, _branch_head_suffix, _classify_fetch_failure, _count_commits_between,_discard_lockfile_churn, _ensure_non_trampoline_git, _get_origin_url, _git_is_trampoline,_has_upstream_remote, _is_fork, _locate_real_git, _mark_skip_upstream_prompt,- _normalize_managed_eol, _portable_git_candidates, _print_fetch_failure,+ _normalize_managed_eol, _park_detached_head, _portable_git_candidates, _print_fetch_failure,_print_parked_branch_kept_notice, _print_parked_branch_skip_warning,_prune_orphan_rescue_refs, _should_skip_upstream_prompt, _sync_fork_with_upstream,_sync_with_upstream_if_needed)@@ -824,8 +824,7 @@ def _pull_updates(if merge_ref != f"origin/{branch}":# Keep detached local commits reachable, too. Named branches are# untouched by checkout --detach; an autostash protects dirty files.- if pre_pull_sha and not _git_run(git_cmd, ["branch", "--show-current"]).stdout.strip():- _git_run(git_cmd, ["update-ref", f"refs/hermes/pre-release/{pre_pull_sha}", pre_pull_sha], check=True)+ _park_detached_head(git_cmd, _m().PROJECT_ROOT, branch)_git_run(git_cmd, ["checkout", "--detach", merge_ref], check=True)elif _git_run(git_cmd, ["merge", "--ff-only", merge_ref]).returncode != 0:_reconcile_diverged_checkout(git_cmd, branch, pre_pull_sha, target_ref=merge_ref)@@ -946,6 +945,8 @@ def _prepare_checkout_for_update(if not release_tag and not in_place_update and current_branch == "HEAD" != branch:print(f" ⚠ Currently on detached HEAD — switching to {branch} for update...")+ # Before the stash: its refs/stash would contain HEAD until it is dropped.+ _park_detached_head(git_cmd, _m().PROJECT_ROOT, branch)auto_stash_ref = _m()._stash_local_changes_if_needed(git_cmd, _m().PROJECT_ROOT)if (not release_tag and not in_place_update and current_branch != branchdiff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.pyindex 10be93f7a8d..f9fa9a34bc0 100644--- a/hermes_cli/update_cmd_git.py+++ b/hermes_cli/update_cmd_git.py@@ -58,9 +58,10 @@ def _prune_orphan_rescue_refs() -> None:"""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.+ ``<kind>`` is ``orphan`` (no common ancestor), ``diverged`` (local commits on the target+ branch) or ``detached`` (commits made on a detached HEAD the update moved off). All are written+ before the update moves HEAD and all pin objects, so they 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@@ -74,7 +75,7 @@ def _prune_orphan_rescue_refs(from hermes_cli.update_cmd_git import _git_runwith suppress(OSError):stale: set[str] = set()- for kind in ("orphan", "diverged"):+ for kind in ("orphan", "diverged", "detached"):prefix = f"refs/hermes-update-backups/{kind}-{branch}-"list_result = _git_run(git_cmd, ["for-each-ref", "--format=%(refname)", "--sort=refname", f"{prefix}*"], cwd)@@ -93,6 +94,43 @@ def _prune_orphan_rescue_refs(_git_run(git_cmd, ["update-ref", "-d", ref], cwd)+def _park_detached_head(git_cmd, cwd, branch) -> None:+ """Keep commits made on a detached HEAD reachable before the update moves HEAD off it.++ Such commits belong to no branch: once HEAD moves, only the expiring reflog still reaches them,+ and nothing in the output would name them. When HEAD is detached at a commit no ref contains+ (the autostash's ``refs/stash`` does not count: it is dropped after the update), write+ ``refs/hermes-update-backups/detached-<branch>-<ts>-<sha12>`` (the divergence rescue refs'+ scheme and expiry) and name it. When that write fails, refuse (``sys.exit(1)``) rather than+ orphan the work. Attached HEADs and already-reachable commits are left alone.+ """+ from hermes_cli.update_cmd import _git_run+ if _git_run(git_cmd, ["symbolic-ref", "-q", "HEAD"], cwd).returncode == 0:+ return # on a branch+ head = _git_run(git_cmd, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], cwd)+ sha = (head.stdout or "").strip()+ if head.returncode != 0 or not sha:+ return+ contains = _git_run(git_cmd, ["for-each-ref", "--contains", sha, "--format=%(refname)"], cwd)+ holders = [r for r in (contains.stdout or "").split() if r != "refs/stash"]+ if contains.returncode == 0 and holders:+ return # already reachable from a branch, tag, remote or backup ref+ stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")+ rescue_ref = f"refs/hermes-update-backups/detached-{branch}-{stamp}-{sha[:12]}"+ if _git_run(git_cmd, ["update-ref", rescue_ref, sha], cwd).returncode != 0:+ print(f"✗ HEAD is detached at {sha[:12]}, which no branch or tag contains, and backing it up "+ f"to {rescue_ref} failed.")+ print(f" Update stopped so those commits are not orphaned. Keep them with: "+ f"git -C {cwd} branch <name> {sha[:12]}")+ sys.exit(1)+ count = (_git_run(git_cmd, ["rev-list", "--count", sha, "--not", "--branches", "--tags", "--remotes"],+ cwd).stdout or "").strip()+ print(f" ⚠ {count or 'Some'} commit(s) made on the detached HEAD are on no branch — backed up to "+ f"{rescue_ref} before moving HEAD. This backup expires after {_ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days.")+ print(f" List them with: git log {rescue_ref} --not --branches --tags --remotes")+ _prune_orphan_rescue_refs(git_cmd, cwd, branch)++def _branch_head_label(git_cmd=None, cwd=None) -> str | None:"""``"<branch> @ <short-sha>"`` for the checkout (``detached`` when not on a branch), or None. Never raises.diff --git a/tests/hermes_cli/test_update_detached_rescue_ref.py b/tests/hermes_cli/test_update_detached_rescue_ref.pynew file mode 100644index 00000000000..6977fad88dd--- /dev/null+++ b/tests/hermes_cli/test_update_detached_rescue_ref.py@@ -0,0 +1,88 @@+"""`hermes update` must not orphan commits made on a detached HEAD.++Both update shapes move HEAD off a detached commit: the branch update checks out ``main``, the+release update checks out the release commit. A commit made there is on no branch, so after the+move only the expiring reflog reaches it. The update must park it under+``refs/hermes-update-backups/detached-...`` first and print the ref name. The installed-product+proof is the e2e cell+``tests/e2e/core/upgrade/git/test_foreign_state.py::test_work_committed_on_a_detached_head_stays_reachable``.+"""++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 detached_work(tmp_path, monkeypatch):+ """A checkout detached at ``origin/main~1`` carrying a commit that no ref contains."""+ upstream = tmp_path / "upstream"+ upstream.mkdir()+ _git(upstream, "init", "-q", "-b", "main")+ _commit(upstream, "shared.txt", "shared\n")+ release = _commit(upstream, "release.txt", "release\n")+ checkout = tmp_path / "checkout"+ _git(tmp_path, "clone", "-q", str(upstream), str(checkout))+ _git(checkout, "checkout", "-q", "--detach", "HEAD~1")+ work = _commit(checkout, "detached-work.txt", "work\n")+ monkeypatch.setattr(update_cmd._m(), "PROJECT_ROOT", checkout)+ return checkout, work, release+++def _assert_parked(checkout, work, output):+ refs = _git(checkout, "for-each-ref", "--contains", work, "--format=%(refname)").stdout.split()+ assert len(refs) == 1 and refs[0].startswith("refs/hermes-update-backups/detached-main-"), \+ f"the detached commit must be kept by exactly one rescue ref, got {refs}\n{output}"+ assert refs[0] in output, f"the user must be told where the commit went:\n{output}"+ assert "1 commit(s) made on the detached HEAD" in output, output+++def test_branch_update_from_detached_head_parks_the_work(detached_work, capsys):+ """The branch shape: detached HEAD -> checkout main, with dirty edits riding in the autostash+ (whose refs/stash contains HEAD until it is dropped, so it must not count as keeping it)."""+ checkout, work, _release = detached_work+ (checkout / "shared.txt").write_text("edited\n", encoding="utf-8")++ plan = update_cmd._prepare_checkout_for_update(+ GIT, "main", "HEAD", is_fork=False, assume_yes=True, gateway_mode=False, gw_input_fn=None,+ switch_branch=False, _windows_gateway_resume=None)+ if plan.auto_stash_ref is not None:+ update_cmd._restore_stashed_changes(GIT, checkout, plan.auto_stash_ref, prompt_user=False)++ assert _git(checkout, "branch", "--show-current").stdout.strip() == "main"+ _assert_parked(checkout, work, capsys.readouterr().out)+++def test_release_update_from_detached_head_parks_only_unreachable_work(detached_work, capsys):+ """The release shape moves HEAD with checkout --detach; a detached HEAD that is already on a+ branch or tag (a pinned release) needs no backup and gets none."""+ checkout, work, release = detached_work++ update_cmd._pull_updates(GIT, "main", None, prompt_for_restore=False, gw_input_fn=None,+ discard_local_changes=False, keep_stash=False, target_ref=release)++ assert _git(checkout, "rev-parse", "HEAD").stdout.strip() == release+ _assert_parked(checkout, work, capsys.readouterr().out)++ _git(checkout, "checkout", "-q", "--detach", "origin/main~1")+ update_cmd._pull_updates(GIT, "main", None, prompt_for_restore=False, gw_input_fn=None,+ discard_local_changes=False, keep_stash=False, target_ref=release)+ backups = _git(checkout, "for-each-ref", "--format=%(refname)", "refs/hermes-update-backups/").stdout.split()+ assert len(backups) == 1, f"a detached HEAD already on a branch must not get a backup ref: {backups}"