Skip to content

The agent that grows with you

fix(update): the fork sync judges its target before moving and owes a commit every landing holds (review G1, O4, F23)

Tekniuma0c51c6dc834
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 61ffef103f3..18a5c1c2060 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -100,7 +100,7 @@ from hermes_cli.update_cmd_git import ( # noqa: F401
_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, _push_synced_fork, _should_skip_upstream_prompt, _sync_fork_with_upstream,
- _sync_with_upstream_if_needed)
+ _sync_with_upstream_if_needed, UpstreamTargetBroken)
from hermes_cli.update_cmd_maint import ( # noqa: F401
_PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE, _clear_stale_sqlite_sidecars,
_checkout_version, _ensure_acp_launcher, _ensure_fhs_path_guard, _finish_dashboard_update_cleanup,
@@ -921,10 +921,16 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=N
syntax_ok, failing_path, syntax_error = (broken is None, *(broken or (None, None)))
else:
syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(_m().PROJECT_ROOT)
- if syntax_ok:
- return
+ if not syntax_ok:
+ _roll_back_broken_update(git_cmd, pre_pull_sha, failing_path, syntax_error, rollback_branch=rollback_branch)
+
+
+def _roll_back_broken_update(git_cmd, pre_pull_sha, failing_path, syntax_error, *, rollback_branch=None,
+ header="✗ Pulled code has a syntax error in a critical file:") -> NoReturn:
+ """Restore the checkout to *pre_pull_sha* after a startup file failed the syntax check, then
+ ``sys.exit(1)``."""
print()
- print("✗ Pulled code has a syntax error in a critical file:")
+ print(header)
print(f" {failing_path}")
# py_compile errors can be multi-line; show enough for the SyntaxError text.
for line in str(syntax_error).splitlines()[:6] if syntax_error else ():
@@ -1011,6 +1017,10 @@ def _refuse_unselected_head(git_cmd, target_sha: str, unmoved: str | None) -> No
sys.exit(1)
+def _upstream_broken_header(broken) -> str:
+ return f"✗ upstream/main ({broken.sha[:10]}) has a syntax error in a critical file; it was not merged:"
+
+
def _update_movement_baseline(git_cmd, pre_pull_sha, pre_sync_sha, rollback_branch, target_sha):
"""Distinguish a branch awaiting repair from an already-applied early sync."""
if rollback_branch is not None and pre_pull_sha and target_sha:
@@ -1113,8 +1123,15 @@ def _pull_updates(
_verify_head_after_pull(
git_cmd, branch, movement_baseline, 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)
+ try:
+ _m()._sync_with_upstream_if_needed(
+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)
+ except UpstreamTargetBroken as broken: # refused before its move: the update rolls back
+ _verify_head_after_pull( # never reset an unexpected branch's ref onto pre
+ git_cmd, branch, movement_baseline, in_place_update=in_place_update,
+ _windows_gateway_resume=_windows_gateway_resume)
+ _roll_back_broken_update(git_cmd, pre_sync_sha or pre_pull_sha, broken.path, broken.error,
+ rollback_branch=rollback_branch, header=_upstream_broken_header(broken))
# Refuse an unexpected branch before syntax rollback can reset its ref.
_verify_head_after_pull(
git_cmd, branch, movement_baseline, in_place_update=in_place_update,
@@ -1393,8 +1410,16 @@ def _prepare_checkout_for_update(
upstream_checked = True
if commit_count == 0 and is_fork and branch == "main" and not release_tag:
pre_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)
- upstream_checked = _m()._sync_with_upstream_if_needed(
- git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)
+ try:
+ upstream_checked = _m()._sync_with_upstream_if_needed(
+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)
+ except UpstreamTargetBroken as broken: # nothing moved; local edits stay parked, like a rollback
+ if auto_stash_ref is not None:
+ print(f" ℹ️ Local changes preserved in stash (ref: {auto_stash_ref})")
+ print(" Restore manually with: git stash apply")
+ _clear_pending_autostash()
+ _roll_back_broken_update(git_cmd, pre_sync_sha, broken.path, broken.error,
+ header=_upstream_broken_header(broken))
post_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)
if pre_sync_sha and post_sync_sha and pre_sync_sha != post_sync_sha:
synced_count = _count_commits_between(
diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.py
index 0f35b4a82b0..e406952c905 100644
--- a/hermes_cli/update_cmd_commit.py
+++ b/hermes_cli/update_cmd_commit.py
@@ -171,6 +171,20 @@ def commit_obligations_armed() -> bool:
return _armed_snapshot is not None
+def debt_sha_for_move(pre: str, target: str) -> str:
+ """The commit a fast-forward ``pre`` -> ``target`` arms the obligations for.
+
+ A later move of this run (the upstream sync after the origin pull) owes ``pre``: the commit the
+ earlier move already owes, which every landing of a fast-forward contains, and the fleet
+ discharge holds the gateways to the checkout's actual HEAD whenever it contains the debt. Its
+ failure then needs no retarget write, which could itself fail and leave the debt naming a commit
+ the checkout never reached (review O4). The run's first move owes its ``target``: its failure
+ hands the obligations back whole (``disarm_commit_obligations``).
+ """
+ start = _run_start[1][0] if _run_start is not None else ""
+ return pre if start and pre != start else target
+
+
def arm_commit_point(git_cmd, root: Path, expected_sha: str, **move) -> str | None:
"""Arm the obligations, then the tree-move marker (``arm_tree_move(**move)``): no marker, no move.
diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.py
index 6c9bfce5b8c..7ceb1307316 100644
--- a/hermes_cli/update_cmd_git.py
+++ b/hermes_cli/update_cmd_git.py
@@ -363,13 +363,22 @@ def _offer_upstream_remote(git_cmd: list[str], cwd: Path, *, assume_yes: bool, i
return True
+class UpstreamTargetBroken(Exception):
+ """The fork sync's upstream target fails the startup syntax check: refused before its move."""
+
+ def __init__(self, sha: str, path: str, error: str) -> None:
+ super().__init__(f"upstream/main ({sha[:10]}) has a syntax error in {path}")
+ self.sha, self.path, self.error = sha, path, error
+
+
def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes: bool = False, input_fn=None,
checkout_move=None) -> bool:
"""Offer to add ``upstream``, compare origin/main vs upstream/main, ff-pull when strictly behind, then push origin.
Returns True only when origin/main was actually verified against upstream/main; False when the check never
happened, so the caller never reports "up to date" on an origin-only compare. Fetches only upstream/main:
- a bare fetch drags in thousands of auto-generated branches.
+ a bare fetch drags in thousands of auto-generated branches. ``UpstreamTargetBroken`` when the
+ upstream commit fails the startup syntax check: nothing moved, the caller rolls the update back.
``checkout_move(target)`` is the caller's context for the one tree write (the merge): the
paused gateways' tree gate is bound to *target* before git writes a file.
@@ -418,7 +427,13 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:
print(" ✗ Could not resolve HEAD. Skipping upstream sync.")
return False
target = upstream # the counted commit is the marker's target and the merge's (m2)
- refused = _commit.arm_commit_point(git_cmd, cwd, target, pre=pre, target=target, stash=None)
+ # Judged BEFORE the move, like the origin target's preflight: the marker goes on git's exit 0,
+ # so a broken target must never land on the strength of the caller's later guard (review G1).
+ from hermes_cli.update_cmd import _UPDATE_CRITICAL_FILES
+ if broken := _commit.target_syntax_error(git_cmd, cwd, target, _UPDATE_CRITICAL_FILES):
+ raise UpstreamTargetBroken(target, *broken)
+ refused = _commit.arm_commit_point(git_cmd, cwd, _commit.debt_sha_for_move(pre, target), pre=pre,
+ target=target, stash=None)
try:
# The fetch above already brought upstream/main: a local fast-forward (no network, so no
# credential helper is started under the checkout lock fd a mutator inherits) to the
@@ -439,7 +454,13 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:
if detail := (getattr(exc, "stderr", None) or ("" if isinstance(exc, subprocess.CalledProcessError) else str(exc))):
print(f" ({detail})")
return False
- interrupted_pull_marker(cwd).unlink(missing_ok=True)
+ interrupted_pull_marker(cwd).unlink(missing_ok=True) # git exited 0: whole at what it landed on
+ if (landed := _git_stdout(git_cmd, ["rev-parse", "-q", "--verify", "HEAD"], cwd)) != upstream:
+ # Not the commit the debt was armed for (O3's check, here): owed for the HEAD it is on, or
+ # handed back at the run's start commit; the caller's HEAD check refuses the update.
+ _commit.disarm_commit_obligations()
+ print(f" ✗ HEAD is on {(landed or '?')[:10]} after the upstream merge, not {upstream[:10]}.")
+ return False
print(" ✓ Updated from upstream")
# The fork push waits for a validated update: ``_push_synced_fork`` after the syntax guard.
return True
diff --git a/tests/hermes_cli/test_update_fork_sync_identity.py b/tests/hermes_cli/test_update_fork_sync_identity.py
index 6dccb8d8105..c9b708faa15 100644
--- a/tests/hermes_cli/test_update_fork_sync_identity.py
+++ b/tests/hermes_cli/test_update_fork_sync_identity.py
@@ -12,7 +12,9 @@ import os
import subprocess
from pathlib import Path
-from hermes_cli.update_cmd_git import _sync_with_upstream_if_needed
+import pytest
+
+from hermes_cli.update_cmd_git import UpstreamTargetBroken, _sync_with_upstream_if_needed
def _env(home: Path) -> dict:
@@ -168,3 +170,62 @@ def test_a_custody_refused_upstream_merge_after_the_pull_still_owes_the_pulled_c
assert "process job (access denied)" in capsys.readouterr().out
assert _git(clone, "rev-parse", "HEAD") == commits[1]
assert (read_host_obligation() or {}).get("expected_sha") == commits[1]
+
+
+def test_a_failed_upstream_sync_whose_retarget_write_fails_still_owes_the_pulled_commit(tmp_path, monkeypatch):
+ """After the origin pull c0 -> c1, the fork ff to c2 armed the debt for c2, failed, and its
+ retarget back to c1 hit a writer that now refuses: the debt stayed c2 with HEAD on c1 (review
+ O4). The later move owes c1 from the start (every landing of the ff contains it), so a failed
+ retarget changes nothing."""
+ from hermes_cli import update_cmd_commit, update_cmd_fleet, update_custody
+ from hermes_cli.update_host_obligation import read_host_obligation
+
+ clone, commits = _fork_behind_upstream(tmp_path, monkeypatch)
+ update_cmd_commit.reset_for_tests()
+ _git(clone, "reset", "-q", "--hard", commits[0])
+ update_cmd_commit.record_run_start(["git"], clone)
+ update_cmd_commit.arm_commit_obligations(clone, commits[1])
+ _git(clone, "reset", "-q", "--hard", commits[1]) # the committed origin pull
+ real_write, real_git, writes = update_cmd_fleet._write_fleet_restart_pending_marker, update_custody.run_git, []
+
+ def writer_then_refuses(**kw):
+ writes.append(kw.get("expected_sha"))
+ return real_write(**kw) if len(writes) == 1 else False # the store turns unwritable
+
+ def merge_fails(git_cmd, args, *rest, **kw):
+ if args[:1] == ["merge"]:
+ raise subprocess.CalledProcessError(128, args, stderr="fatal: Unable to create index.lock")
+ return real_git(git_cmd, args, *rest, **kw)
+
+ monkeypatch.setattr(update_cmd_fleet, "_write_fleet_restart_pending_marker", writer_then_refuses)
+ monkeypatch.setattr(update_custody, "run_git", merge_fails)
+ try:
+ assert _sync_with_upstream_if_needed(["git"], clone, assume_yes=True) is False
+ finally:
+ update_cmd_commit.reset_for_tests()
+ assert _git(clone, "rev-parse", "HEAD") == commits[1]
+ assert commits[2] not in writes
+ assert (read_host_obligation() or {}).get("expected_sha") == commits[1]
+
+
+def test_a_broken_upstream_target_is_refused_before_the_second_move(tmp_path, monkeypatch, capsys):
+ """The fork ff dropped its marker on git's exit 0 and only the caller's later syntax guard
+ judged the result, so a kill in between left a broken c2 with no recovery record (review G1).
+ The upstream target is compiled before its move, like the origin target's preflight."""
+ from hermes_cli import update_cmd_commit
+ from hermes_cli._early_recovery import interrupted_pull_marker
+
+ clone, commits = _fork_behind_upstream(tmp_path, monkeypatch)
+ upstream = tmp_path / "upstream"
+ (upstream / "hermes_constants.py").write_text("def broken(:\n", encoding="utf-8")
+ _git(upstream, "add", "hermes_constants.py")
+ _git(upstream, "commit", "-qm", "broken c3")
+ update_cmd_commit.reset_for_tests()
+ try:
+ with pytest.raises(UpstreamTargetBroken) as refused:
+ _sync_with_upstream_if_needed(["git"], clone, assume_yes=True)
+ finally:
+ update_cmd_commit.reset_for_tests()
+ assert refused.value.path == "hermes_constants.py"
+ assert _git(clone, "rev-parse", "HEAD") == commits[1]
+ assert not interrupted_pull_marker(clone).exists()
diff --git a/tests/hermes_cli/test_update_target_identity.py b/tests/hermes_cli/test_update_target_identity.py
index 683d141f218..e35bdf875f6 100644
--- a/tests/hermes_cli/test_update_target_identity.py
+++ b/tests/hermes_cli/test_update_target_identity.py
@@ -434,9 +434,13 @@ def test_update_syntax_failure_restores_pre_update_head(update_tree, monkeypatch
unexpected_head = git(remote, 'rev-parse', 'HEAD')
if sync_phase == 'late-other-branch':
def switch_after_sync(*args, **kwargs):
- result = _sync_with_upstream_if_needed(*args, **kwargs)
- git(t.clone, 'checkout', '-qb', 'unexpected')
- return result
+ try: # the broken upstream target is now refused (raised) before its move (review G1)
+ return _sync_with_upstream_if_needed(*args, **kwargs)
+ finally:
+ git(t.clone, 'checkout', '-qb', 'unexpected')
+ switched.append(git(t.clone, 'rev-parse', 'HEAD'))
+
+ switched = []
monkeypatch.setattr(cli_main, '_sync_with_upstream_if_needed', switch_after_sync)
local = t.clone / '.gitignore'
@@ -453,16 +457,17 @@ def test_update_syntax_failure_restores_pre_update_head(update_tree, monkeypatch
assert not t.requests
output = capsys.readouterr().out
if sync_phase == 'late-other-branch':
- assert git(t.clone, 'rev-parse', 'unexpected') == unexpected_head
+ # The broken upstream commit never landed; the unexpected branch keeps the HEAD it was cut at.
+ assert git(t.clone, 'rev-parse', 'unexpected') == switched[0] != unexpected_head
assert git(t.clone, 'branch', '--show-current') == 'unexpected'
- assert (t.clone / 'hermes_cli/config.py').read_bytes() == bad.read_bytes()
+ assert not (t.clone / 'hermes_cli/config.py').exists()
assert "checkout is on 'unexpected'" in output
assert 'Rolling back' not in output
else:
# Origin's own target is refused before HEAD moves (the commit point's preflight); an
- # upstream sync's target is still caught by the post-pull guard and rolled back.
+ # upstream sync's target is refused before ITS move, and the update rolls back (review G1).
assert ('The update target has a syntax error' if sync_phase == 'origin'
- else 'Pulled code has a syntax error') in output
+ else 'has a syntax error in a critical file; it was not merged') in output
assert git(t.clone, 'rev-parse', 'HEAD') == t.base
assert not (t.clone / 'hermes_cli' / 'config.py').exists()
if sync_phase == 'origin' and dirty: