fix(workspace): role-aware worktree refresh at every spawn (#692)

* fix(workspace): refresh a present per-task worktree at every respawn

ensure_worktree_self_heal treated an already-present worktree as a pure
no-op (venv-link + chown only), so a worktree created once at first claim
or first claim_review stayed frozen at that commit across every later
respawn even as new commits landed on origin — the root mechanism behind
a live multi-round QA/PR-gate bounce loop, where the reviewer kept
re-examining its own stale round-1 checkout.

_ensure_worktree_before_spawn now classifies the caller's role
(WORKTREE_AUTHOR_ROLES: developer/documenter, mirroring the gateway
commit tool's RBAC) and _refresh_present_worktree compares local HEAD
against origin/<branch>: behind-or-equal fast-forwards for every role
(never discarding an author's uncommitted edits to do it); strictly
ahead is always left alone; diverged only resets for a pure reader,
whose local history can never be anything but a stale prior-round
checkout.

conventions_check_for_task's list-vs-content gap (list from git objects,
content from the physical worktree) is closed as a side effect: the
reviewer's worktree is now current as of spawn, and the branch under
review gains no further commits while it sits in awaiting_pr_review.

* fix(workspace): refresh re-added worktrees; fail the dirty guard toward preservation

- A pruned worktree re-added from a surviving local ref now runs the same
  fetch-and-classify refresh as a present one, so an evicted reviewer
  worktree cannot resurrect a stale checkout.
- A failing git status reads as dirty, never clean: the guard that
  protects an author's uncommitted edits fails toward preservation.
- The hard reset verifies the worktree is actually on the task branch
  first; a detached or drifted worktree is left alone with a warning.
- The conventions-check docstring states the remaining second-claim
  ceiling instead of claiming full closure.

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
Renzo F
2026-07-24 20:29:20 +02:00
committed by GitHub
co-authored by Renn F
parent e97f46af6e
commit 987eb09c78
6 changed files with 518 additions and 28 deletions
@@ -263,7 +263,14 @@ def _ref_exists(repo: Path, ref: str) -> bool:
)
async def test_self_heal_noop_when_worktree_present(clone: Path) -> None:
async def test_self_heal_present_worktree_fetches_but_noops_without_origin(
clone: Path,
) -> None:
# A present worktree is no longer an unconditional no-op (the respawn
# bug): a fetch is now always attempted. This `clone` fixture carries no
# `origin` remote at all, so `origin/<branch>` can never resolve and the
# refresh has nothing to compare against — same observable outcome as
# the old no-op, but for a different reason (unresolvable, not skipped).
svc = _service()
wt = clone / ".worktrees" / "a3c40fe7"
with patch("roboco.services.workspace._ensure_agent_owned"):
@@ -275,15 +282,21 @@ async def test_self_heal_noop_when_worktree_present(clone: Path) -> None:
) as fetch,
patch("roboco.services.workspace._ensure_agent_owned"),
):
await svc.ensure_worktree_self_heal(clone, wt, "feature/a3c40fe7", "proj")
await svc.ensure_worktree_self_heal(
clone, wt, "feature/a3c40fe7", "proj", can_author=True
)
assert fetch.await_count == 0, "present worktree must not trigger a fetch"
assert fetch.await_count == 1, "present worktree must now attempt a fetch"
assert _git(wt, "rev-parse", "--abbrev-ref", "HEAD").strip() == "feature/a3c40fe7"
async def test_self_heal_readds_pruned_worktree_from_local_ref(clone: Path) -> None:
# Common resume case: clone healthy, worktree pruned, local branch ref
# survives -> re-add with NO fetch (no origin round-trip on every spawn).
# survives -> re-add, THEN run it through the same fetch-and-classify
# refresh a present worktree gets (a stale local ref must not resurrect an
# untouched checkout). This `clone` fixture carries no `origin` remote, so
# there is nothing to classify against — the refresh's own fetch still
# runs, it just has no origin/<branch> to compare to.
svc = _service()
wt = clone / ".worktrees" / "a3c40fe7"
with patch("roboco.services.workspace._ensure_agent_owned"):
@@ -297,13 +310,52 @@ async def test_self_heal_readds_pruned_worktree_from_local_ref(clone: Path) -> N
) as fetch,
patch("roboco.services.workspace._ensure_agent_owned"),
):
await svc.ensure_worktree_self_heal(clone, wt, "feature/a3c40fe7", "proj")
# can_author is irrelevant on the absent-worktree path (pre-refresh).
await svc.ensure_worktree_self_heal(
clone, wt, "feature/a3c40fe7", "proj", can_author=True
)
assert fetch.await_count == 0, "local ref survives -> no fetch needed"
assert fetch.await_count == 1, (
"a re-add from a surviving local ref must now refresh"
)
assert wt.exists()
assert _git(wt, "rev-parse", "--abbrev-ref", "HEAD").strip() == "feature/a3c40fe7"
async def test_self_heal_readd_from_stale_local_ref_lands_on_origin_tip_for_reader(
tmp_path: Path,
) -> None:
# THE BUG SCENARIO: a reviewer's round-1 claim_review creates the worktree
# + local ref at origin's tip A; the worktree is evicted (disk pressure /
# manual cleanup) while the local ref survives; a dev then pushes tip B.
# A round-2 respawn's re-add must land on B, not resurrect the stale local
# ref's A.
branch = "feature/pruned-stale-ref"
remote = _bare_remote_with_branch(tmp_path, branch, push_branch=False)
clone = await _synced_clone_and_worktree(tmp_path, remote, branch)
wt = clone / ".worktrees" / "pruned-stale-ref"
_git(clone, "worktree", "remove", str(wt), "--force") # evicted; local ref survives
assert not wt.exists()
assert _ref_exists(clone, f"refs/heads/{branch}"), (
"precondition: local ref survives"
)
_push_extra_commit(tmp_path, remote, branch, "other") # origin advances to tip B
_git(clone, "fetch", "origin", branch) # what the mocked _fetch_branch_ref would do
svc = _service()
await _run_self_heal(svc, clone, wt, branch, can_author=False)
assert wt.exists()
assert (wt / "origin_advance.txt").exists(), (
"a re-add from a stale local ref must land on origin's tip, not the "
"ref's stale commit"
)
assert (
_git(wt, "rev-parse", "HEAD").strip()
== _git(clone, "rev-parse", f"origin/{branch}").strip()
)
def _bare_remote_with_branch(tmp_path: Path, branch: str, push_branch: bool) -> Path:
"""A bare remote carrying `main`; optionally also `branch` with a commit."""
remote = tmp_path / "remote.git"
@@ -363,7 +415,8 @@ async def test_self_heal_recovers_branch_from_origin(tmp_path: Path) -> None:
) as fetch,
patch("roboco.services.workspace._ensure_agent_owned"),
):
await svc.ensure_worktree_self_heal(clone, wt, branch, "proj")
# can_author is irrelevant on the absent-worktree path (pre-refresh).
await svc.ensure_worktree_self_heal(clone, wt, branch, "proj", can_author=True)
assert fetch.await_count == 1, "missing local ref must trigger a fetch"
assert wt.exists()
@@ -394,13 +447,204 @@ async def test_self_heal_falls_back_to_origin_head_when_branch_not_pushed(
) as fetch,
patch("roboco.services.workspace._ensure_agent_owned"),
):
await svc.ensure_worktree_self_heal(clone, wt, branch, "proj")
# can_author is irrelevant on the absent-worktree path (pre-refresh).
await svc.ensure_worktree_self_heal(clone, wt, branch, "proj", can_author=True)
assert fetch.await_count == 1, "missing local ref still attempts a fetch"
assert wt.exists(), "fallback -b from origin/HEAD must break the loop"
assert _git(wt, "rev-parse", "--abbrev-ref", "HEAD").strip() == branch
# ---------------------------------------------------------------------------
# _refresh_present_worktree — role-aware respawn refresh of an ALREADY-PRESENT
# worktree (the respawn bug). A worktree created once (first claim / first
# claim_review) must not stay frozen at that commit across every later
# respawn while origin moves on. `_fetch_branch_ref` is mocked (a spy, as
# above) — the tests pre-seed `origin/<branch>`'s remote-tracking ref with a
# real `git fetch` so the classification runs against real git state.
# ---------------------------------------------------------------------------
async def _synced_clone_and_worktree(tmp_path: Path, remote: Path, branch: str) -> Path:
"""Clone `remote`, create+push a worktree on `branch` at origin's tip.
Mirrors `create_branch`'s real shape: the worktree branch is cut, then
pushed, so local and `origin/<branch>` start perfectly in sync.
"""
clone = tmp_path / "clone"
subprocess.run(
["git", "clone", str(remote), str(clone)], check=True, capture_output=True
)
svc = _service()
wt = clone / ".worktrees" / branch.rsplit("/", 1)[-1]
with patch("roboco.services.workspace._ensure_agent_owned"):
await svc.ensure_worktree(clone, wt, branch, "main")
_git(wt, "push", "origin", branch)
return clone
def _push_extra_commit(tmp_path: Path, remote: Path, branch: str, name: str) -> None:
"""A second clone pushes one more commit onto `branch` (simulates a dev's
force-pushed fix landing on origin between two reviewer respawns)."""
other = tmp_path / name
subprocess.run(
["git", "clone", str(remote), str(other)], check=True, capture_output=True
)
_git(other, "checkout", branch)
(other / "origin_advance.txt").write_text(name)
_git(other, "add", "origin_advance.txt")
_git(other, "commit", "-m", "origin advances")
_git(other, "push", "origin", branch)
def _commit_local_only(wt: Path) -> None:
"""A commit in the worktree that never reaches origin (unpushed work)."""
(wt / "local_only.txt").write_text("mine")
_git(wt, "add", "local_only.txt")
_git(wt, "commit", "-m", "local unpushed work")
async def _run_self_heal(
svc: WorkspaceService, clone: Path, wt: Path, branch: str, *, can_author: bool
) -> None:
with (
patch.object(WorkspaceService, "_fetch_branch_ref", new_callable=AsyncMock),
patch("roboco.services.workspace._ensure_agent_owned"),
):
await svc.ensure_worktree_self_heal(
clone, wt, branch, "proj", can_author=can_author
)
async def test_refresh_reader_diverged_resets_to_origin(tmp_path: Path) -> None:
branch = "feature/reader-diverged"
remote = _bare_remote_with_branch(tmp_path, branch, push_branch=False)
clone = await _synced_clone_and_worktree(tmp_path, remote, branch)
wt = clone / ".worktrees" / "reader-diverged"
_commit_local_only(wt) # local ref now ahead of origin/<branch>
_push_extra_commit(tmp_path, remote, branch, "other") # ...and origin too
_git(clone, "fetch", "origin", branch) # what the mocked _fetch_branch_ref would do
assert (wt / "local_only.txt").exists(), "precondition: local commit present"
svc = _service()
await _run_self_heal(svc, clone, wt, branch, can_author=False)
assert not (wt / "local_only.txt").exists(), (
"reader's diverged local history is disposable — must reset to origin"
)
assert (wt / "origin_advance.txt").exists(), "origin's tip must now be checked out"
assert (
_git(wt, "rev-parse", "HEAD").strip()
== _git(clone, "rev-parse", f"origin/{branch}").strip()
)
async def test_refresh_author_ahead_untouched(tmp_path: Path) -> None:
branch = "feature/author-ahead"
remote = _bare_remote_with_branch(tmp_path, branch, push_branch=False)
clone = await _synced_clone_and_worktree(tmp_path, remote, branch)
wt = clone / ".worktrees" / "author-ahead"
_commit_local_only(wt) # strictly ahead — origin never moved
_git(clone, "fetch", "origin", branch)
svc = _service()
await _run_self_heal(svc, clone, wt, branch, can_author=True)
assert (wt / "local_only.txt").exists(), "strictly-ahead work is never discarded"
async def test_refresh_author_diverged_untouched(tmp_path: Path) -> None:
branch = "feature/author-diverged"
remote = _bare_remote_with_branch(tmp_path, branch, push_branch=False)
clone = await _synced_clone_and_worktree(tmp_path, remote, branch)
wt = clone / ".worktrees" / "author-diverged"
_commit_local_only(wt)
_push_extra_commit(tmp_path, remote, branch, "other")
_git(clone, "fetch", "origin", branch)
svc = _service()
await _run_self_heal(svc, clone, wt, branch, can_author=True)
assert (wt / "local_only.txt").exists(), (
"an author's diverged history is sync_branch's job, never a silent reset"
)
assert not (wt / "origin_advance.txt").exists(), "no reset must have run at all"
async def test_refresh_behind_fast_forwards_for_any_role(tmp_path: Path) -> None:
branch = "feature/behind"
remote = _bare_remote_with_branch(tmp_path, branch, push_branch=False)
clone = await _synced_clone_and_worktree(tmp_path, remote, branch)
wt = clone / ".worktrees" / "behind"
_push_extra_commit(tmp_path, remote, branch, "other") # local has nothing unique
_git(clone, "fetch", "origin", branch)
svc = _service()
await _run_self_heal(svc, clone, wt, branch, can_author=True)
assert (wt / "origin_advance.txt").exists(), (
"behind-or-equal is safe to fast-forward for every role"
)
async def test_refresh_dirty_author_tree_preserved_even_when_behind(
tmp_path: Path,
) -> None:
branch = "feature/dirty-author"
remote = _bare_remote_with_branch(tmp_path, branch, push_branch=False)
clone = await _synced_clone_and_worktree(tmp_path, remote, branch)
wt = clone / ".worktrees" / "dirty-author"
(wt / "pyproject.toml").write_text("[project]\nname = 'edited'\n") # uncommitted
_push_extra_commit(tmp_path, remote, branch, "other")
_git(clone, "fetch", "origin", branch)
svc = _service()
await _run_self_heal(svc, clone, wt, branch, can_author=True)
assert (wt / "pyproject.toml").read_text() == "[project]\nname = 'edited'\n", (
"an author's uncommitted edit must never be discarded by a reset"
)
assert not (wt / "origin_advance.txt").exists(), "no reset must have run at all"
def test_worktree_is_dirty_treats_failed_status_as_dirty(tmp_path: Path) -> None:
# A failed `git status` (nonzero returncode, empty stdout) must read as
# dirty, never clean — a false "clean" here lets an author+behind branch
# proceed straight to `reset --hard` and discard uncommitted edits.
failed = subprocess.CompletedProcess(
args=[], returncode=128, stdout="", stderr="fatal: not a git repository"
)
with patch.object(WorkspaceService, "_worktree_git", return_value=failed):
assert WorkspaceService._worktree_is_dirty(tmp_path) is True
async def test_refresh_skips_reset_when_worktree_drifted_off_task_branch(
tmp_path: Path,
) -> None:
# A worktree parked on some OTHER branch (a crashed mid-rebase, a drifted
# checkout) must never have the task branch's ref reset under it — a
# `reset --hard` runs in the worktree's own checked-out branch, not
# necessarily the task branch, so blindly resetting would move the wrong
# ref.
branch = "feature/drifted"
remote = _bare_remote_with_branch(tmp_path, branch, push_branch=False)
clone = await _synced_clone_and_worktree(tmp_path, remote, branch)
wt = clone / ".worktrees" / "drifted"
_push_extra_commit(tmp_path, remote, branch, "other") # task branch now behind
_git(clone, "fetch", "origin", branch)
_git(wt, "checkout", "-b", "other-work") # worktree drifts off the task branch
svc = _service()
with patch("roboco.services.workspace.logger.warning") as warn:
await _run_self_heal(svc, clone, wt, branch, can_author=True)
assert warn.called, "a drifted worktree must log a warning instead of resetting"
assert not (wt / "origin_advance.txt").exists(), (
"a worktree drifted off its task branch must be left alone"
)
assert _git(wt, "rev-parse", "--abbrev-ref", "HEAD").strip() == "other-work"
# ---------------------------------------------------------------------------
# Clone-root-left-on-task-branch recovery (live be-pm needs_revision wedge,
# 2026-06-30). F123 invariant: the clone root parks on the default branch (or
@@ -479,8 +723,16 @@ async def test_self_heal_recovers_clone_root_left_on_task_branch(clone: Path) ->
_clone_on_branch(clone, branch)
wt = clone / ".worktrees" / "d3dab0fc"
with patch("roboco.services.workspace._ensure_agent_owned"):
await svc.ensure_worktree_self_heal(clone, wt, branch, "proj")
with (
patch.object(WorkspaceService, "_fetch_branch_ref", new_callable=AsyncMock),
patch("roboco.services.workspace._ensure_agent_owned"),
):
# The local ref here comes straight from `_clone_on_branch`, not a
# prior `ensure_worktree` — a surviving local ref now also re-adds
# through the present-worktree refresh; origin/<branch> is
# unresolvable (only origin/main was seeded), so the refresh's fetch
# is a no-op past the re-add.
await svc.ensure_worktree_self_heal(clone, wt, branch, "proj", can_author=True)
assert (wt / ".git").is_file()
assert _git(wt, "rev-parse", "--abbrev-ref", "HEAD").strip() == branch