Skip to content

The agent that grows with you

fix(update): validate late upstream sync before restoring local work

ethernetcc1b5e2adde5
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 60979931665..f588ac959d5 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -916,15 +916,14 @@ 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):
+ keep_stash, target_ref=None, pre_sync_sha=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 -> reset, orphan history -> rescue ref first; a
post-pull syntax error in a critical file rolls back. Exits on failure; returns pre-pull SHA."""
update_succeeded = False
- # Pre-pull SHA for auto-rollback (stray conflict markers once bricked every updater).
- # Capture the pre-pull SHA so we can auto-roll-back if the new code has a syntax error in a
- # critical-path file (PR #28452 incident: orphan merge-conflict markers in hermes_cli/config.py bricked
- # every user who ran ``hermes update`` for the 7 minutes between the bad commit and the fix landing).
+ # Rescue refs must retain the immediate pre-pull tip, even when syntax
+ # rollback needs to cross an earlier upstream sync.
pre_pull_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)
try:
# merge --ff-only the already-fetched ref instead of `git pull`, which would do a
@@ -938,7 +937,18 @@ def _pull_updates(
_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)
+ if sync_upstream:
+ # Do not let a second mutation hide a failed origin merge or move an
+ # unexpected branch. Keep local edits parked through the final check.
+ _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)
+ _m()._sync_with_upstream_if_needed(
+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)
_rollback_if_pulled_syntax_error(git_cmd, pre_sync_sha or pre_pull_sha)
+ _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)
update_succeeded = True
finally:
if auto_stash_ref is not None:
@@ -1328,16 +1338,12 @@ def _finish_already_up_to_date(
def _apply_pulled_update(
- git_cmd, branch, pre_pull_sha, _plan, opts, *, is_fork,
- _windows_gateway_resume, completion_request: dict) -> None:
+ git_cmd, branch, pre_pull_sha, _plan, *, _windows_gateway_resume, completion_request: dict) -> None:
"""Post-pull phase: verify HEAD, sync Python/Node/web/Desktop, maintenance, fleet restart."""
post_pull_sha = _verify_head_after_pull(
git_cmd, branch, _plan.pre_sync_sha or pre_pull_sha, in_place_update=_plan.in_place_update,
_windows_gateway_resume=_windows_gateway_resume)
- if is_fork and branch == "main":
- _m()._sync_with_upstream_if_needed(
- git_cmd, _m().PROJECT_ROOT, assume_yes=opts.assume_yes, input_fn=opts.gw_input_fn)
if completion_request is not None:
completion_request["expected_sha"] = _capture_head_sha(git_cmd, _m().PROJECT_ROOT) or post_pull_sha
_complete_source_update(completion_request)
@@ -1487,9 +1493,11 @@ def _cmd_update_impl(args, gateway_mode: bool):
pre_pull_sha = _pull_updates(
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)
+ keep_stash=opts.keep_stash, target_ref=target_ref, pre_sync_sha=_plan.pre_sync_sha,
+ sync_upstream=is_fork and branch == "main" and not release_tag, assume_yes=assume_yes,
+ in_place_update=_plan.in_place_update, _windows_gateway_resume=_windows_gateway_resume)
_apply_pulled_update(
- git_cmd, branch, pre_pull_sha, _plan, opts, is_fork=is_fork and not release_tag,
+ git_cmd, branch, pre_pull_sha, _plan,
_windows_gateway_resume=_windows_gateway_resume, completion_request=completion_request)
except subprocess.CalledProcessError as e:
try:
diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py
index 8b14ab22130..66f32f8b0c9 100644
--- a/tests/hermes_cli/test_cmd_update.py
+++ b/tests/hermes_cli/test_cmd_update.py
@@ -1,12 +1,10 @@
-"""Tests for cmd_update — branch fallback when remote branch doesn't exist."""
+"""Git trampoline recovery; branch updates use the real target-identity suite."""
import subprocess
-from types import SimpleNamespace
from unittest.mock import patch
import pytest
-from hermes_cli.main import cmd_update
from hermes_cli import update_cmd
@@ -18,92 +16,11 @@ def _isolate_venv_holders(monkeypatch):
monkeypatch.setattr("hermes_cli.update_cmd_windows._detect_venv_python_processes", lambda: [])
-def _make_run_side_effect(branch="main", verify_ok=True, commit_count="0"):
- """Build a side_effect function for subprocess.run that simulates git commands."""
-
- def side_effect(cmd, **kwargs):
- joined = " ".join(str(c) for c in cmd)
-
- # git rev-parse --abbrev-ref HEAD (get current branch)
- if "rev-parse" in joined and "--abbrev-ref" in joined:
- return subprocess.CompletedProcess(cmd, 0, stdout=f"{branch}\n", stderr="")
-
- # git rev-parse --verify origin/{branch} (check remote branch exists)
- if "rev-parse" in joined and "--verify" in joined:
- rc = 0 if verify_ok else 128
- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr="")
-
- # git rev-list HEAD..origin/{branch} --count
- if "rev-list" in joined:
- return subprocess.CompletedProcess(cmd, 0, stdout=f"{commit_count}\n", stderr="")
-
- # Fallback: return a successful CompletedProcess with empty stdout
- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
-
- return side_effect
-
-
-def mock_args():
- return SimpleNamespace()
-
-
pytestmark = pytest.mark.usefixtures(
"isolated_update_processes", "isolated_update_checkout",
)
-class TestCmdUpdateBranchFallback:
- """cmd_update falls back to main when current branch has no remote counterpart."""
-
-
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_fork_upstream_sync_that_moves_head_runs_post_update_steps(
- self, mock_run, _mock_which, mock_args, capsys
- ):
- """A fork sync that pulls code must continue through post-update work."""
- from hermes_cli import main as hm
- from hermes_cli import update_cmd
-
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="0"
- )
-
- # The first two reads bracket the upstream sync (aaaaaaa -> bbbbbbb:
- # the sync moved HEAD). The NEXT two bracket the pull inside the
- # normal update path (bbbbbbb -> ccccccc) — the head-moved no-op
- # guard added after this PR exits 1 when that pair is equal, so the
- # mock must show the pull advancing HEAD too.
- shas = iter(["aaaaaaa", "bbbbbbb", "bbbbbbb", "ccccccc"])
-
- with patch.object(
- hm,
- "_get_origin_url",
- return_value="https://github.com/example/hermes-agent.git",
- ), patch.object(
- update_cmd,
- "_capture_head_sha",
- side_effect=lambda *_args, **_kwargs: next(shas, "ccccccc"),
- ), patch.object(
- hm, "_sync_with_upstream_if_needed"
- ), patch.object(
- update_cmd,
- "_complete_source_update",
- # Unlike product preparation, this phase only runs after a pull.
- # Stop before skills sync and fleet restart; the regression took
- # the current-checkout path instead and never reached this phase.
- side_effect=SystemExit(0),
- ) as post_update_step:
- with pytest.raises(SystemExit) as exit_info:
- cmd_update(mock_args)
-
- assert exit_info.value.code == 0
- post_update_step.assert_called_once()
- captured = capsys.readouterr()
- assert "Already up to date!" not in captured.out
-
-
class TestGitTrampolineSelfHeal:
"""Proactive Git-for-Windows trampoline self-heal (#87876).
@@ -129,12 +46,12 @@ class TestGitTrampolineSelfHeal:
stderr="BUG (fork bomb): tried to spawn itself, check your PATH\n",
)
+ @pytest.mark.platforms("windows")
def test_healthy_git_command_unchanged(self):
from hermes_cli import update_cmd
git_cmd = ["git", "-c", "windows.appendAtomically=false"]
with (
- patch("sys.platform", "win32"),
patch(
"hermes_cli.update_cmd.subprocess.run",
side_effect=self._fake_run_healthy,
@@ -145,6 +62,7 @@ class TestGitTrampolineSelfHeal:
assert result == git_cmd
locate.assert_not_called()
+ @pytest.mark.platforms("windows")
def test_trampoline_swaps_to_real_git(self, capsys):
from pathlib import Path
@@ -153,7 +71,6 @@ class TestGitTrampolineSelfHeal:
git_cmd = ["git", "-c", "windows.appendAtomically=false"]
real = Path(r"C:\Program Files\Git\mingw64\libexec\git-core\git.exe")
with (
- patch("sys.platform", "win32"),
patch(
"hermes_cli.update_cmd.subprocess.run",
side_effect=self._fake_run_trampoline,
@@ -167,12 +84,12 @@ class TestGitTrampolineSelfHeal:
out = capsys.readouterr().out
assert "switching to real git" in out
+ @pytest.mark.platforms("windows")
def test_trampoline_no_real_git_keeps_command(self, capsys):
from hermes_cli import update_cmd
git_cmd = ["git", "-c", "windows.appendAtomically=false"]
with (
- patch("sys.platform", "win32"),
patch(
"hermes_cli.update_cmd.subprocess.run",
side_effect=self._fake_run_trampoline,
@@ -184,14 +101,12 @@ class TestGitTrampolineSelfHeal:
out = capsys.readouterr().out
assert "ZIP path" in out
+ @pytest.mark.platforms("not windows")
def test_off_windows_noop(self):
from hermes_cli import update_cmd
git_cmd = ["git"]
- with (
- patch("sys.platform", "linux"),
- patch("hermes_cli.update_cmd.subprocess.run") as run,
- ):
+ with patch("hermes_cli.update_cmd.subprocess.run") as run:
result = update_cmd._ensure_non_trampoline_git(git_cmd)
assert result == git_cmd
run.assert_not_called()
diff --git a/tests/hermes_cli/test_update_completion_routing.py b/tests/hermes_cli/test_update_completion_routing.py
index 22f26005139..48470df880d 100644
--- a/tests/hermes_cli/test_update_completion_routing.py
+++ b/tests/hermes_cli/test_update_completion_routing.py
@@ -72,10 +72,9 @@ def test_every_route_hands_off_once(route, tmp_path, monkeypatch):
plan = update_cmd._CheckoutPlan(
in_place_update=False, auto_stash_ref=None, parked_branch_switched=False,
upstream_checked=True, commit_count=1, prompt_for_restore=False, switch_block_reason=None)
- opts = SimpleNamespace(assume_yes=True, gw_input_fn=None, pre_update_version="old")
if route == "pulled":
update_cmd._apply_pulled_update(
- ["git"], "main", "old-sha", plan, opts, is_fork=False, _windows_gateway_resume=None,
+ ["git"], "main", "old-sha", plan, _windows_gateway_resume=None,
completion_request=request)
elif route == "current":
update_cmd._finish_already_up_to_date(
diff --git a/tests/hermes_cli/test_update_target_identity.py b/tests/hermes_cli/test_update_target_identity.py
index 575b7b047eb..a372cd9db20 100644
--- a/tests/hermes_cli/test_update_target_identity.py
+++ b/tests/hermes_cli/test_update_target_identity.py
@@ -5,6 +5,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import os
from pathlib import Path
import subprocess
+import sys
import threading
from types import SimpleNamespace
from urllib.parse import urlsplit
@@ -89,7 +90,9 @@ def update_tree(tmp_path, monkeypatch):
@pytest.mark.parametrize('case', ['main', 'explicit', 'missing', 'no-move', 'wrong-branch',
'fork-no-upstream', 'fork-upstream', 'fork-upstream-push-ok',
- 'fork-upstream-wrong-branch', 'fork-upstream-reverted', 'check-main',
+ 'fork-upstream-wrong-branch', 'fork-upstream-reverted',
+ 'fork-late', 'fork-late-push-ok', 'fork-late-wrong-branch',
+ 'fork-late-reverted', 'check-main',
'check-explicit', 'check-missing', 'check-upstream'])
def test_branch_update_uses_real_refs_and_completion_request(update_tree, monkeypatch, case, capsys):
t = update_tree
@@ -104,18 +107,25 @@ def test_branch_update_uses_real_refs_and_completion_request(update_tree, monkey
if case in {'missing', 'check-missing'}:
t.args.branch = 'absent'
if case.startswith('fork-') or case == 'check-upstream':
- # Origin is current; only upstream has the next commit.
- git(t.origin, 'reset', '--hard', t.base)
- if case.startswith('fork-upstream') or case == 'check-upstream':
+ # Early sync starts level with origin; late sync first consumes origin.
+ git(t.origin, 'reset', '--hard', t.wanted if case.startswith('fork-late') else t.base)
+ if case.startswith(('fork-upstream', 'fork-late')) or case == 'check-upstream':
upstream = t.origin.parent / 'upstream'
git(t.origin.parent, 'clone', '-q', str(t.origin), str(upstream))
git(upstream, 'reset', '--hard', t.newer)
git(t.clone, 'remote', 'add', 'upstream', str(upstream))
- if case == 'fork-upstream-push-ok':
+ if case.endswith('push-ok'):
git(t.origin, 'config', 'receive.denyCurrentBranch', 'updateInstead')
+ local = t.clone / '.gitignore'
+ local_work = local.read_bytes() + b'# local work\n'
+ if case.startswith('fork-late'):
+ local.write_bytes(local_work)
run = subprocess.run
+ pushes = []
def fault(command, *args, **kwargs):
+ assert Path(command[0]).name.lower() in {'git', 'git.exe'} or command[0] == sys.executable, command
+ assert Path(kwargs['cwd']).resolve() in {t.clone, t.origin}, command
if 'merge' in command and '--ff-only' in command:
if case == 'no-move':
return subprocess.CompletedProcess(command, 0, stdout='', stderr='')
@@ -125,16 +135,28 @@ def test_branch_update_uses_real_refs_and_completion_request(update_tree, monkey
if case == 'fork-upstream-reverted':
run(['git', 'reset', '--hard', t.base], cwd=t.clone, check=True, capture_output=True)
return result
- return run(command, *args, **kwargs)
+ result = run(command, *args, **kwargs)
+ if 'pull' in command and case.startswith('fork-late'):
+ if case.endswith('wrong-branch'):
+ run(['git', 'checkout', '-qb', 'wrong'], cwd=t.clone, check=True, capture_output=True)
+ if case.endswith('reverted'):
+ run(['git', 'reset', '--hard', t.base], cwd=t.clone, check=True, capture_output=True)
+ if 'push' in command and 'origin' in command:
+ pushes.append(result.returncode)
+ return result
monkeypatch.setattr(subprocess, 'run', fault)
fails = case in {'missing', 'check-missing', 'no-move', 'wrong-branch',
- 'fork-upstream-wrong-branch', 'fork-upstream-reverted'}
+ 'fork-upstream-wrong-branch', 'fork-upstream-reverted',
+ 'fork-late-wrong-branch', 'fork-late-reverted'}
if fails:
with pytest.raises(SystemExit) as error:
cli_main.cmd_update(t.args)
assert error.value.code == 1
assert t.requests == []
+ if case.startswith('fork-late'):
+ assert git(t.clone, 'show', 'stash@{0}:.gitignore') == local_work.decode().strip()
+ assert local.read_bytes() != local_work
else:
cli_main.cmd_update(t.args)
if t.args.check:
@@ -151,12 +173,17 @@ def test_branch_update_uses_real_refs_and_completion_request(update_tree, monkey
expected = t.base if case == 'fork-no-upstream' else t.wanted if case == 'explicit' else t.newer
assert git(t.clone, 'rev-parse', 'HEAD') == expected
assert request['source'] == str(t.clone)
- if case.startswith('fork-upstream'):
+ if case.startswith(('fork-upstream', 'fork-late')):
assert request['expected_sha'] == expected
output = capsys.readouterr().out
assert 'Code did not move' not in output
assert 'Already up to date' not in output
- assert git(t.origin, 'rev-parse', 'HEAD') == (t.newer if case.endswith('push-ok') else t.base)
+ origin_before = t.wanted if case.startswith('fork-late') else t.base
+ assert git(t.origin, 'rev-parse', 'HEAD') == (t.newer if case.endswith('push-ok') else origin_before)
+ assert pushes and all((rc == 0) is case.endswith('push-ok') for rc in pushes)
+ if case.startswith('fork-late'):
+ assert local.read_bytes() == local_work
+ assert not git(t.clone, 'stash', 'list')
if case == 'fork-no-upstream':
assert 'official repo not checked' in request['completion_message']
assert git(t.clone, 'remote') == 'origin'
@@ -235,7 +262,7 @@ def test_stable_git_uses_remote_identity_without_moving_local_tags(update_tree,
assert request['expected_sha'] == expected
assert git(t.clone, 'rev-parse', 'HEAD') == expected
content = 'unreleased-main\n' if server == 'explicit-branch' else 'release\n'
- assert (t.clone / 'content.txt').read_text(encoding='utf-8') == content
+ assert (t.clone / 'content.txt').read_text(encoding='utf-8-sig') == content
branch = 'retained-branch' if server in {'at-release', 'explicit-branch'} else ''
assert git(t.clone, 'branch', '--show-current') == branch
assert resolved == (server != 'explicit-branch')
@@ -343,7 +370,7 @@ def test_stable_zip_consumes_the_same_commit_through_the_real_swap(update_tree,
assert request['plan'] == plan.to_dict()
assert request['receipt']['plan'] == plan.to_dict()
assert request['snapshot_id'] == 'release-snapshot'
- assert (t.clone / 'content.txt').read_text(encoding='utf-8') == 'release\n'
+ assert (t.clone / 'content.txt').read_text(encoding='utf-8-sig') == 'release\n'
assert [url for url in urls if '/archive/' in url] == [
f'https://github.com/NousResearch/hermes-agent/archive/{t.wanted}.zip']
assert t.resumed
@@ -357,17 +384,19 @@ def test_stable_zip_consumes_the_same_commit_through_the_real_swap(update_tree,
server.server_close()
[email protected]('sync_first', [False, True])
-def test_update_syntax_failure_restores_pre_update_head(update_tree, monkeypatch, capsys, sync_first):
[email protected]('sync_phase', ['origin', 'early', 'late'])
[email protected]('dirty', [False, True])
+def test_update_syntax_failure_restores_pre_update_head(update_tree, monkeypatch, capsys, sync_phase, dirty):
t = update_tree
git(t.clone, 'checkout', '-q', 'main')
t.args.channel = 'main'
monkeypatch.setattr(cli_main, '_sync_with_upstream_if_needed', _sync_with_upstream_if_needed)
- if sync_first:
+ if sync_phase != 'origin':
upstream = t.origin.parent / 'upstream'
git(t.origin.parent, 'clone', '-q', str(t.origin), str(upstream))
git(t.clone, 'remote', 'add', 'upstream', str(upstream))
- git(t.origin, 'reset', '--hard', t.base)
+ if sync_phase == 'early':
+ git(t.origin, 'reset', '--hard', t.base)
remote = upstream
else:
remote = t.origin
@@ -377,6 +406,14 @@ def test_update_syntax_failure_restores_pre_update_head(update_tree, monkeypatch
git(remote, 'add', 'hermes_cli/config.py')
git(remote, '-c', 'user.name=Fixture', '-c', '[email protected]',
'-c', 'commit.gpgsign=false', 'commit', '-qm', 'invalid syntax')
+ local = t.clone / '.gitignore'
+ staged = local.read_bytes() + b'# staged local work\n'
+ unstaged = staged + b'# unstaged local work\n'
+ if dirty:
+ local.write_bytes(staged)
+ git(t.clone, 'add', '.gitignore')
+ local.write_bytes(unstaged)
+ (t.clone / 'notes.txt').write_bytes(b'untracked local work\n')
with pytest.raises(SystemExit) as error:
cli_main.cmd_update(t.args)
assert error.value.code == 1
@@ -384,3 +421,13 @@ def test_update_syntax_failure_restores_pre_update_head(update_tree, monkeypatch
assert 'Pulled code has a syntax error' in capsys.readouterr().out
assert git(t.clone, 'rev-parse', 'HEAD') == t.base
assert not (t.clone / 'hermes_cli' / 'config.py').exists()
+ assert not git(t.clone, 'status', '--porcelain')
+ assert bool(git(t.clone, 'stash', 'list')) is dirty
+ if dirty:
+ assert git(t.clone, 'show', 'stash@{0}^2:.gitignore') == staged.decode().strip()
+ assert git(t.clone, 'show', 'stash@{0}:.gitignore') == unstaged.decode().strip()
+ assert git(t.clone, 'show', 'stash@{0}^3:notes.txt') == 'untracked local work'
+ git(t.clone, 'stash', 'apply', '--index')
+ assert local.read_bytes() == unstaged
+ assert git(t.clone, 'show', ':.gitignore') == staged.decode().strip()
+ assert (t.clone / 'notes.txt').read_bytes() == b'untracked local work\n'