Fetch origin and cut agent branches from origin/HEAD at spawn

Agents spawned by handler were getting branches several commits behind
main. Two compounding causes: sync_project ran 'git pull --ff-only' in
the project root, which only moves whichever branch the root checkout
happens to be on — an agent parked on a feature branch left origin/*
stale (and the pull's 'no tracking information' failure degraded to an
easy-to-miss sync_note). Then worktree spawns cut new branches from the
root's HEAD, inheriting that stale state.

sync_project now fetches origin (refreshing origin/* regardless of the
checkout), re-pins origin/HEAD, and fast-forwards the checkout only when
it sits on the default branch — a diverged default branch still fails
loudly. New worktree branches are cut from origin/HEAD with --no-track
so they start at the remote default branch's tip and don't adopt it as
upstream.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V7mF6qeryi9nJthaxYkfPm
This commit is contained in:
Claude
2026-07-23 04:21:13 +00:00
parent 4b1f35df98
commit f03b03ab5c
7 changed files with 243 additions and 22 deletions
+13 -5
View File
@@ -150,7 +150,7 @@ def test_sync_endpoint_400_without_remote(client, auth, env, tmp_path):
@pytest.fixture
def fake_sync_gitops(monkeypatch):
"""Fake the clone/pull side of the gitops seam."""
state = {"clone": [], "pull": [], "config": [], "repos": set(), "ok": True, "out": ""}
state = {"clone": [], "fetch": [], "config": [], "repos": set(), "ok": True, "out": ""}
def is_repo(path):
return path in state["repos"]
@@ -162,17 +162,25 @@ def fake_sync_gitops(monkeypatch):
state["repos"].add(dest)
return state["ok"], state["out"]
def pull_ff(cwd, env=None):
state["pull"].append({"cwd": cwd, "env": env or {}})
def fetch(cwd, env=None):
state["fetch"].append({"cwd": cwd, "env": env or {}})
return state["ok"], state["out"]
def set_default_head(cwd, env=None):
return True, ""
def default_branch_ref(cwd):
return None
def config_local(cwd, key, value):
state["config"].append({"cwd": cwd, "key": key, "value": value})
return True, ""
monkeypatch.setattr(gitops, "is_repo", is_repo)
monkeypatch.setattr(gitops, "clone", clone)
monkeypatch.setattr(gitops, "pull_ff", pull_ff)
monkeypatch.setattr(gitops, "fetch", fetch)
monkeypatch.setattr(gitops, "set_default_head", set_default_head)
monkeypatch.setattr(gitops, "default_branch_ref", default_branch_ref)
monkeypatch.setattr(gitops, "config_local", config_local)
return state
@@ -192,7 +200,7 @@ def test_cmd_sync_clones_then_pulls(env, fake_sync_gitops):
result = worker.execute_command(command)
assert result["action"] == "pulled"
assert fake_sync_gitops["pull"][0]["cwd"] == "/tmp/r"
assert fake_sync_gitops["fetch"][0]["cwd"] == "/tmp/r"
def test_cmd_sync_failure_is_command_error(env, fake_sync_gitops):
+85
View File
@@ -0,0 +1,85 @@
"""``sync_project`` against real git repos — the fetch-not-pull regression.
A pull only moves whichever branch the root has checked out; with the root parked on
an agent's feature branch, ``origin/*`` went stale and every branch cut for a new
agent started several commits behind the remote's default branch. These tests use a
filesystem remote (no host, no credentials) so the git behaviour itself is exercised.
"""
from __future__ import annotations
import subprocess
import pytest
from handler.control import reposync
def _git(cwd, *args):
subprocess.run(["git", "-C", str(cwd), *args], check=True, capture_output=True)
def _sha(cwd, ref="HEAD") -> str:
return subprocess.run(
["git", "-C", str(cwd), "rev-parse", ref],
check=True, capture_output=True, text=True,
).stdout.strip()
@pytest.fixture
def remote_and_root(tmp_path):
"""An origin repo, a clone of it as the project root, then origin moves ahead."""
origin = tmp_path / "origin"
origin.mkdir()
_git(origin, "init", "-q", "-b", "main")
for repo_dir in (origin,):
_git(repo_dir, "config", "user.email", "t@t.co")
_git(repo_dir, "config", "user.name", "t")
_git(repo_dir, "config", "commit.gpgsign", "false")
_git(origin, "commit", "-q", "--allow-empty", "-m", "one")
root = tmp_path / "proj"
subprocess.run(
["git", "clone", "-q", str(origin), str(root)], check=True, capture_output=True
)
_git(root, "config", "user.email", "t@t.co")
_git(root, "config", "user.name", "t")
_git(root, "config", "commit.gpgsign", "false")
_git(origin, "commit", "-q", "--allow-empty", "-m", "two")
return origin, root
def _project(origin, root) -> dict:
return {"id": "p", "root_dir": str(root), "git_remote": str(origin)}
def test_sync_refreshes_origin_even_when_root_parked_on_agent_branch(
env, remote_and_root
):
origin, root = remote_and_root
_git(root, "checkout", "-q", "-b", "agent/old-work")
# Simulate a clone that never had origin/HEAD — sync must re-pin it too.
_git(root, "remote", "set-head", "origin", "-d")
result = reposync.sync_project(_project(origin, root))
assert result["action"] == "pulled"
assert _sha(root, "origin/main") == _sha(origin, "main")
assert _sha(root, "refs/remotes/origin/HEAD") == _sha(origin, "main")
# The parked checkout itself is left alone — only origin/* moves.
assert _sha(root, "HEAD") != _sha(origin, "main")
def test_sync_fast_forwards_a_checkout_sitting_on_the_default_branch(
env, remote_and_root
):
origin, root = remote_and_root
result = reposync.sync_project(_project(origin, root))
assert result["action"] == "pulled"
assert _sha(root, "HEAD") == _sha(origin, "main")
def test_sync_fails_loudly_when_the_default_branch_diverged(env, remote_and_root):
origin, root = remote_and_root
_git(root, "commit", "-q", "--allow-empty", "-m", "local divergence")
with pytest.raises(reposync.SyncError, match="fast-forward"):
reposync.sync_project(_project(origin, root))
+54
View File
@@ -31,6 +31,36 @@ def repo(tmp_path):
return root
@pytest.fixture
def cloned(tmp_path):
"""A root cloned from an origin whose main has since moved on.
Mirrors the spawn-time state after ``reposync.sync_project``: origin/* is fresh
(fetched), but the root's checkout still sits on the older commit.
"""
origin = tmp_path / "origin"
origin.mkdir()
_git(origin, "init", "-q", "-b", "main")
_git(origin, "config", "user.email", "t@t.co")
_git(origin, "config", "user.name", "t")
_git(origin, "config", "commit.gpgsign", "false")
_git(origin, "commit", "-q", "--allow-empty", "-m", "one")
root = tmp_path / "proj"
subprocess.run(
["git", "clone", "-q", str(origin), str(root)], check=True, capture_output=True
)
_git(origin, "commit", "-q", "--allow-empty", "-m", "two")
_git(root, "fetch", "-q", "origin")
return root
def _sha(cwd, ref="HEAD") -> str:
return subprocess.run(
["git", "-C", str(cwd), "rev-parse", ref],
check=True, capture_output=True, text=True,
).stdout.strip()
def _is_worktree(root, path) -> bool:
out = subprocess.run(
["git", "-C", str(root), "worktree", "list", "--porcelain"],
@@ -54,6 +84,30 @@ def test_creates_branch_when_it_does_not_exist(repo):
assert "feat/new-thing" in branches
def test_new_branch_is_cut_from_remote_default_not_root_head(cloned):
# The regression: new agent branches were cut from the root's HEAD, so a checkout
# sitting behind (or parked on an earlier agent's branch) produced branches several
# commits behind origin's default branch.
target = worktree.resolve_working_dir(
str(cloned), "agent", worktree_branch="feat/fresh"
)
assert _sha(target) == _sha(cloned, "origin/main")
assert _sha(target) != _sha(cloned, "HEAD")
def test_new_branch_from_remote_default_gets_no_upstream(cloned):
# --no-track: without it the new branch adopts origin/main as upstream, and the
# agent's plain `git push` would aim at the default branch.
target = worktree.resolve_working_dir(
str(cloned), "agent", worktree_branch="feat/fresh"
)
upstream = subprocess.run(
["git", "-C", target, "rev-parse", "--abbrev-ref", "@{upstream}"],
capture_output=True, text=True,
)
assert upstream.returncode != 0
def test_checks_out_existing_branch(repo):
_git(repo, "branch", "feat/existing")
target = worktree.resolve_working_dir(