The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): preserve running checkout across branch-switch updates
funky-xamarin57b3868d5229
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 8a1b7206372..4b2100aec05 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -807,7 +807,7 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_rsys.exit(1)-def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha) -> None:+def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=None) -> None:"""Post-pull syntax guard: roll back to *pre_pull_sha* and ``sys.exit(1)`` when a criticalfile no longer compiles (a bad admin-merge past CI must not brick the CLI)."""syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(_m().PROJECT_ROOT)@@ -822,13 +822,21 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha) -> None:print()if pre_pull_sha:print(f"→ Rolling back to {pre_pull_sha[:10]}...")- rollback_result = _git_run(git_cmd, ["reset", "--hard", pre_pull_sha])+ rollback_args = ["reset", "--hard", pre_pull_sha]+ if rollback_branch is not None:+ # Restore the checkout we left, never reset the update branch onto+ # commits from a parked feature branch (or a detached release).+ target = pre_pull_sha if rollback_branch == "HEAD" else rollback_branch+ rollback_args = (+ ["checkout", "--detach", target] if rollback_branch == "HEAD"+ else ["checkout", target])+ rollback_result = _git_run(git_cmd, rollback_args)if rollback_result.returncode == 0:print(" ✓ Rollback complete — your install is unchanged.")print(" Try ``hermes update`` again later once a fix lands.")else:print(" ✗ Rollback failed. Recover manually with:")- print(f" cd {_m().PROJECT_ROOT} && git reset --hard {pre_pull_sha}")+ print(f" cd {_m().PROJECT_ROOT} && git {shlex.join(rollback_args)}")if rollback_result.stderr.strip():print(f" ({rollback_result.stderr.strip().splitlines()[0]})")else:@@ -839,7 +847,7 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha) -> None:def _pull_updates(git_cmd, branch, auto_stash_ref, *, prompt_for_restore, gw_input_fn, discard_local_changes,- keep_stash, target_ref=None, pre_sync_sha=None, sync_upstream=False, assume_yes=False,+ keep_stash, target_ref=None, pre_sync_sha=None, rollback_branch=None, sync_upstream=False, assume_yes=False,in_place_update=False, _windows_gateway_resume=None):"""Fast-forward onto ``origin/<branch>`` and settle the autostash. Divergence by shape:custom branch -> merge, same branch -> rescue ref then reset; a@@ -888,7 +896,9 @@ def _pull_updates(_verify_head_after_pull(git_cmd, branch, pre_sync_sha or pre_pull_sha, in_place_update=in_place_update,_windows_gateway_resume=_windows_gateway_resume)- _rollback_if_pulled_syntax_error(git_cmd, pre_sync_sha or pre_pull_sha)+ _rollback_if_pulled_syntax_error(+ git_cmd, pre_sync_sha or pre_pull_sha,+ **({"rollback_branch": rollback_branch} if rollback_branch is not None else {}))update_succeeded = Truefinally:if auto_stash_ref is not None:@@ -921,6 +931,7 @@ class _CheckoutPlan:switch_block_reason: "str | None"upstream_checked: boolpre_sync_sha: str | None = None+ rollback_branch: str | None = Nonedef _apply_parked_branch_guard(@@ -991,13 +1002,15 @@ def _prepare_checkout_for_update(_park_detached_head(git_cmd, _m().PROJECT_ROOT, branch)auto_stash_ref = _m()._stash_local_changes_if_needed(git_cmd, _m().PROJECT_ROOT)moved_from_sha = None- if (- not release_tag and not in_place_update and current_branch != branch- and _git_run(git_cmd, ["checkout", branch]).returncode != 0):- # `checkout -B` lands ON the target, so HEAD..target would count 0 and the update would- # finish as "Already up to date!" with nothing synced (#125112): count from here instead.+ rollback_branch = None+ if not release_tag and not in_place_update and current_branch != branch:+ # Both checkout forms can land on the fetched tip before the count runs.+ # Keep the running code AND its branch identity for syntax rollback.moved_from_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)- track_result = _git_run(git_cmd, ["checkout", "-B", branch, f"origin/{branch}"])+ rollback_branch = current_branch+ track_result = _git_run(git_cmd, ["checkout", branch])+ if track_result.returncode != 0:+ track_result = _git_run(git_cmd, ["checkout", "-B", branch, f"origin/{branch}"])if track_result.returncode != 0:# Restore the stash before bailing so the user isn't stranded.if auto_stash_ref is not None:@@ -1035,6 +1048,13 @@ def _prepare_checkout_for_update(# counted == 0 means local-ahead: falls through to the up-to-date path.commit_count = counted if counted is not None else -1+ # Switching away from a locally-ahead commit can change the running tree+ # without adding ancestors. It still needs the post-update pipeline.+ if commit_count == 0 and moved_from_sha:+ landed_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)+ if landed_sha and landed_sha != moved_from_sha:+ commit_count = -1+# A fork can match origin yet trail upstream, so the sync can move HEAD with# commit_count == 0; detect that BEFORE the no-update return so deps, restarts AND the# fleet matrix still run (it used to live in the early-return branch and verified nothing).@@ -1055,13 +1075,13 @@ def _prepare_checkout_for_update(git_cmd, _m().PROJECT_ROOT, pre_sync_sha, post_sync_sha)# HEAD moving is proof of an update even if the count can't be read.commit_count = max(1, synced_count)- moved_from_sha = pre_sync_sha+ moved_from_sha = moved_from_sha or pre_sync_shareturn _CheckoutPlan(auto_stash_ref=auto_stash_ref, commit_count=commit_count, in_place_update=in_place_update,parked_branch_switched=parked_branch_switched, prompt_for_restore=prompt_for_restore,switch_block_reason=switch_block_reason, upstream_checked=upstream_checked,- pre_sync_sha=moved_from_sha)+ pre_sync_sha=moved_from_sha, rollback_branch=rollback_branch)@dataclass@@ -1480,6 +1500,7 @@ def _cmd_update_impl(args, gateway_mode: bool):git_cmd, branch, _plan.auto_stash_ref, prompt_for_restore=_plan.prompt_for_restore,gw_input_fn=gw_input_fn, discard_local_changes=opts.discard_local_changes,keep_stash=opts.keep_stash, target_ref=target_ref, pre_sync_sha=_plan.pre_sync_sha,+ rollback_branch=_plan.rollback_branch,sync_upstream=is_fork and branch == "main" and not release_sha, assume_yes=assume_yes,in_place_update=_plan.in_place_update, _windows_gateway_resume=_windows_gateway_resume)_apply_pulled_update(diff --git a/tests/hermes_cli/test_update_existing_branch_baseline.py b/tests/hermes_cli/test_update_existing_branch_baseline.pynew file mode 100644index 00000000000..08beaff61f0--- /dev/null+++ b/tests/hermes_cli/test_update_existing_branch_baseline.py@@ -0,0 +1,126 @@+"""Real Git regression coverage for updates that land via an existing branch."""+import subprocess++import pytest++from hermes_cli import update_cmd+from tests.hermes_cli.test_update_target_identity import update_tree # noqa: F401+++def git(root, *args):+ result = subprocess.run(["git", *args], cwd=root, capture_output=True, text=True)+ assert result.returncode == 0, result.stderr+ return result.stdout.strip()+++def checkout(tmp_path, monkeypatch):+ root = tmp_path / "checkout"+ root.mkdir()+ git(root, "init", "-q", "-b", "main")+ git(root, "config", "user.name", "Fixture")+ git(root, "config", "user.email", "[email protected]")+ (root / "cli.py").write_text("value = 1\n", encoding="utf8")+ git(root, "add", ".")+ git(root, "commit", "-qm", "old")+ old = git(root, "rev-parse", "HEAD")+ (root / "cli.py").write_text("value = 2\n", encoding="utf8")+ git(root, "commit", "-qam", "new")+ tip = git(root, "rev-parse", "HEAD")+ git(root, "update-ref", "refs/remotes/origin/main", tip)+ git(root, "checkout", "-q", "--detach", old)+ monkeypatch.setattr(update_cmd._m(), "PROJECT_ROOT", root)+ return root, old, tip+++def prepare(root):+ return update_cmd._prepare_checkout_for_update(+ ["git"], "main", update_cmd._current_branch_name(["git"], check=True),+ is_fork=False, assume_yes=True, gateway_mode=False, gw_input_fn=None,+ switch_branch=False, _windows_gateway_resume=None,+ )+++def test_existing_main_counts_from_running_detached_code(checkout):+ root, old, tip = checkout+ plan = prepare(root)+ assert git(root, "rev-parse", "HEAD") == tip+ assert plan.commit_count == 1+ assert plan.pre_sync_sha == old+ update_cmd._pull_updates(+ ["git"], "main", plan.auto_stash_ref, prompt_for_restore=False,+ gw_input_fn=None, discard_local_changes=False, keep_stash=False,+ pre_sync_sha=plan.pre_sync_sha,+ rollback_branch=plan.rollback_branch,+ )+ assert git(root, "rev-parse", "HEAD") == tip+++def test_same_commit_switch_is_still_a_noop(checkout):+ root, old, tip = checkout+ git(root, "checkout", "-q", "--detach", tip)+ assert prepare(root).commit_count == 0++[email protected]("parked", [False, True])+def test_syntax_failure_returns_to_original_checkout_without_rewriting_main(checkout, parked):+ root, old, tip = checkout+ if parked:+ git(root, "checkout", "-qb", "feature")+ (root / "local.txt").write_text("local work\n", encoding="utf8")+ git(root, "add", ".")+ git(root, "commit", "-qm", "local")+ old = git(root, "rev-parse", "HEAD")+ # Commit an actually invalid critical file on main; no mocked syntax verdict.+ git(root, "checkout", "-q", "main")+ (root / "cli.py").write_text("def broken(\n", encoding="utf8")+ git(root, "commit", "-qam", "bad upstream")+ bad = git(root, "rev-parse", "HEAD")+ git(root, "update-ref", "refs/remotes/origin/main", bad)+ git(root, "checkout", "-q", "feature" if parked else old)+ plan = prepare(root)+ with pytest.raises(SystemExit) as exc:+ update_cmd._pull_updates(+ ["git"], "main", plan.auto_stash_ref, prompt_for_restore=False,+ gw_input_fn=None, discard_local_changes=False, keep_stash=False,+ pre_sync_sha=plan.pre_sync_sha, rollback_branch=plan.rollback_branch,+ )+ assert exc.value.code == 1+ assert git(root, "rev-parse", "HEAD") == old+ assert git(root, "rev-parse", "--abbrev-ref", "HEAD") == ("feature" if parked else "HEAD")+ assert git(root, "rev-parse", "main") == bad+ assert (root / "cli.py").read_text(encoding="utf8") == "value = 1\n"+++def test_locally_ahead_switch_still_needs_completion(checkout):+ root, old, tip = checkout+ git(root, "checkout", "-q", "--detach", tip)+ git(root, "commit", "--allow-empty", "-qm", "local detached commit")+ before = git(root, "rev-parse", "HEAD")+ plan = prepare(root)+ assert plan.commit_count != 0+ assert plan.pre_sync_sha == before+ assert git(root, "rev-parse", "HEAD") == tip+++def test_command_hands_off_after_existing_main_switch(update_tree, monkeypatch, capsys):+ t = update_tree+ monkeypatch.setattr("hermes_cli.update_owning_install.retarget_to_owning_install", lambda *_: None)+ run = subprocess.run++ def local_git_only(command, *args, **kwargs):+ from pathlib import Path+ assert Path(command[0]).name.lower() in {"git", "git.exe"}, command+ assert Path(kwargs["cwd"]).resolve() in {t.clone, t.origin}, command+ return run(command, *args, **kwargs)++ monkeypatch.setattr(subprocess, "run", local_git_only)+ git(t.clone, "fetch", "-q", "origin", "main")+ git(t.clone, "branch", "-f", "main", "origin/main")+ git(t.clone, "checkout", "-q", "--detach", t.base)+ t.args.channel = "main"+ monkeypatch.setattr(update_cmd._m(), "_sync_with_upstream_if_needed", lambda *a, **k: True)+ update_cmd._m().cmd_update(t.args)+ assert git(t.clone, "rev-parse", "HEAD") == t.newer+ assert len(t.requests) == 1+ assert "Already up to date" not in capsys.readouterr().out