Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -286,10 +286,13 @@ The push uses a temporary bare repository and ignores local, global, and system
Git configuration so URL rewrites cannot change its destination.
After confirmed remote deletion or absence, cleanup deletes the matching
`origin/lz/<slug>` tracking ref only if it still points to the merged head.
An already-merged PR can resume cleanup from its task worktree. Local removal
requires a clean worktree with no ignored user files. A Git ref lock keeps the
worktree at the merged PR head during removal. Cleanup then deletes the branch
only if it still points at that head.
After confirming the merge, a ref lock verifies the task branch before cleanup
detaches its clean worktree. Cleanup deletes the local branch
only at that head and removes the worktree after branch deletion. If interrupted,
rerunning `loopzero merge` in the detached worktree looks up the previous branch
from Git's checkout history and requires a live merged PR for that exact branch
and head. Another worktree's checkout, a moved branch or an ignored user file
blocks removal.
Hosted eligibility trusts the configured publisher's projection and live identity,
state, head and latest ordering. It cannot recompute private raw or defeat a
coherent forgery by a trusted publisher/editor; native claims do not attest the
Expand Down
37 changes: 24 additions & 13 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1184,10 +1184,12 @@ def _load_review(wt: Path, head: str, kind: str) -> ReviewResult:


def _pr_readiness(
wt: Path, config: Config, *, allow_merged: bool = False, workflow_wait: bool = False
wt: Path, config: Config, *, allow_merged: bool = False, workflow_wait: bool = False,
branch: str | None = None,
) -> tuple[github.PR, github.Readiness | None]:
"""PR plus readiness; readiness is None only for an already merged PR (allow_merged)."""
branch, head = worktree.branch(wt), worktree.head(wt)
branch = branch if branch is not None else worktree.branch(wt)
head = worktree.head(wt)
_require_task_branch(config, branch)
pr = _require_pr(config, branch, allow_merged=allow_merged)
_require_pushed(pr, head)
Expand All @@ -1200,16 +1202,12 @@ def _pr_readiness(
CLEANUP_RETRY = "; fix the cause, then rerun `loopzero merge` in this worktree to finish cleanup"


def _cleanup(wt: Path, pr: github.PR) -> None:
name = None
def _cleanup(wt: Path, pr: github.PR, branch: str | None = None) -> None:
try:
_repo_root(wt)
name = worktree.branch(wt)
worktree.cleanup(wt, pr.head_sha)
worktree.cleanup(wt, pr.head_sha, branch)
except (worktree.WorktreeError, OSError) as exc:
retry = CLEANUP_RETRY if wt.exists() else ""
if not retry and name is not None:
retry = f"; worktree removed; delete local branch {name!r} if it still points at the merged head"
print(f"warning: merged but worktree cleanup failed: {exc}{retry}", file=sys.stderr)


Expand Down Expand Up @@ -1630,21 +1628,34 @@ def _merge_with_mergify(
return None


def _merge_pr_readiness(
wt: Path, config: Config, *, workflow_wait: bool
) -> tuple[str, github.PR, github.Readiness | None]:
if previous := worktree.detached_from(wt):
_repo_root(wt)
_require_task_branch(config, previous)
pr = github.merged_pr_at_head(config.repo, previous, worktree.head(wt))
if pr is None:
raise CliError(f"no merged PR proves cleanup of detached worktree for {previous!r}")
return previous, pr, None
branch = worktree.branch(wt)
pr, readiness = _pr_readiness(wt, config, allow_merged=True, workflow_wait=workflow_wait, branch=branch)
return branch, pr, readiness
Comment thread
eowca marked this conversation as resolved.
Resolved


def cmd_merge(args: argparse.Namespace) -> int:
if args.cancel and args.wait is not None:
raise CliError("merge --cancel cannot be combined with --wait")
wt, config = _context(args, pin_checks=True)
branch = worktree.branch(wt)
if args.cancel:
branch = worktree.branch(wt)
if config.merge_strategy != "mergify":
raise CliError("merge --cancel is only available with delivery.merge = 'mergify'")
pr = _require_pr(config, branch)
mergify.dequeue(config.repo, pr.number)
print(f"requested removal of PR #{pr.number} from Mergify")
return 0
pr, readiness = _pr_readiness(
wt, config, allow_merged=True, workflow_wait=args.wait is not None
)
branch, pr, readiness = _merge_pr_readiness(wt, config, workflow_wait=args.wait is not None)
started = time.monotonic()
deadline = None if args.wait is None else started + args.wait
# --wait=0 observes once; a positive budget also bounds merge or queue admission.
Expand Down Expand Up @@ -1693,7 +1704,7 @@ def cmd_merge(args: argparse.Namespace) -> int:
)
return 0
_cleanup_remote_refs(wt, config, branch, pr.head_sha)
_cleanup(wt, pr)
_cleanup(wt, pr, branch)
print(sha)
return 0

Expand Down
37 changes: 35 additions & 2 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,8 +638,9 @@ def _branch_head(repo: str, branch: str) -> str | None:
return sha


def _commit_branch_prs(repo: str, branch: str) -> tuple[str, list[dict]]:
sha = _branch_head(repo, branch)
def _commit_branch_prs(repo: str, branch: str, sha: str | None = None) -> tuple[str, list[dict]]:
if sha is None:
sha = _branch_head(repo, branch)
if sha is None:
return "", []

Expand All @@ -663,6 +664,38 @@ def _commit_branch_prs(repo: str, branch: str) -> tuple[str, list[dict]]:
raise GhError(("gh", "api", endpoint), "commit PRs exceed 100 pages")


def merged_pr_at_head(repo: str, branch: str, sha: str) -> PR | None:
"""Find a merged PR for the exact source branch and commit."""
Comment thread
eowca marked this conversation as resolved.
Resolved
_, matches = _commit_branch_prs(repo, branch, sha)
return _matching_merged_pr(repo, branch, sha, matches) or _merged_pr_from_history(repo, branch, sha)


def _matching_merged_pr(repo: str, branch: str, sha: str, rows: list) -> PR | None:
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get("head"), dict):
raise GhError(("gh", "api"), "invalid closed PR history")
number = row.get("number")
if row.get("state") != "closed" or row["head"].get("sha") != sha or type(number) is not int:
continue
pr, detail = _pr_detail(repo, number)
if pr.state == "MERGED" and pr.head_sha == sha and _matches_branch(detail["head"], repo, branch):
return pr
return None


def _merged_pr_from_history(repo: str, branch: str, sha: str) -> PR | None:
head = quote(f"{repo.split('/', 1)[0]}:{branch}", safe="")
for page in range(1, 101):
endpoint = f"repos/{repo}/pulls?state=closed&head={head}&per_page={PAGE}&page={page}"
rows = api_get(endpoint)
if not isinstance(rows, list):
raise GhError(("gh", "api", endpoint), "invalid closed PR history")
match = _matching_merged_pr(repo, branch, sha, rows)
if match or len(rows) < PAGE:
return match
raise GhError(("gh", "api", endpoint), "closed PR history exceeds 100 pages")


def _confirm_branch_pr(repo: str, branch: str, endpoint: str, number: int, state: str) -> PR:
pr, detail = _pr_detail(repo, number)
state_matches = pr.state == state or (state == "CLOSED" and pr.state == "MERGED")
Expand Down
60 changes: 50 additions & 10 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager, suppress
from itertools import pairwise
from pathlib import Path
from select import select

Expand Down Expand Up @@ -309,23 +310,62 @@ def _require_no_ignored_user_files(wt: Path) -> None:
raise WorktreeError(f"worktree contains ignored file {path!r}, refusing to remove: {wt}")


def cleanup(wt: Path, expected_head: str) -> None:
"""Remove a clean merged worktree and its branch if it has no local user files."""
def detached_from(wt: Path) -> str | None:
"""Return the branch named by the latest checkout to this detached HEAD."""
if _git(wt, "branch", "--show-current", preserve_whitespace=True):
return None
entries = _git(wt, "reflog", "--format=%H %gs", "HEAD", preserve_whitespace=True).splitlines()
sha = head(wt)
for current, previous in pairwise(entries):
if " checkout: moving from " in current:
match = re.fullmatch(rf"{sha} checkout: moving from (.+) to {sha}", current)
# The prior entry records the actual old SHA, even if checkout
# read its source branch before a concurrent HEAD update.
return match[1] if match and previous.startswith(sha + " ") else None
return None


def cleanup(wt: Path, expected_head: str, name: str | None = None) -> None:
"""Delete a verified merged branch before removing its clean linked worktree."""
wt = Path(wt).absolute()
if not wt.exists():
raise WorktreeError(f"no such worktree: {wt}")
if head(wt) != expected_head:
raise WorktreeError("local HEAD differs from merged PR head")
name = branch(wt)
name = name if name is not None else branch(wt)
gd = Path(_git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True))
ref = f"refs/heads/{name}"
with _lock_verified_ref(wt, ref, expected_head):
if branch(wt) != name:
raise WorktreeError("local branch changed during merge cleanup")
if is_dirty(wt):
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
if Path(_git(wt, "rev-parse", "--absolute-git-dir", preserve_whitespace=True)) == gd:
raise WorktreeError("refusing cleanup from the primary checkout")
current = _git(wt, "branch", "--show-current", preserve_whitespace=True)
if current:
_detach_clean_worktree(wt, expected_head, name)
with _lock_verified_ref(wt, "HEAD", expected_head):
if detached_from(wt) != name:
raise WorktreeError("local checkout changed during merge cleanup")
_require_clean_worktree(wt)
_delete_merged_branch(gd, name, expected_head)
_require_no_ignored_user_files(wt)
_git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout
_git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt))


def _require_clean_worktree(wt: Path) -> None:
if is_dirty(wt):
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
_require_no_ignored_user_files(wt)


def _detach_clean_worktree(wt: Path, expected_head: str, name: str) -> None:
with _lock_verified_ref(wt, f"refs/heads/{name}", expected_head):
if _git(wt, "branch", "--show-current", preserve_whitespace=True) != name:
raise WorktreeError("local branch changed during merge cleanup")
_require_clean_worktree(wt)
# Git needs its own HEAD lock for the switch. Cleanup verifies the checkout
# recorded by Git and takes the detached HEAD lock before deleting anything.
_git(wt, "-c", "core.logAllRefUpdates=true", "switch", "--quiet", "--detach", expected_head)


def _delete_merged_branch(gd: Path, name: str, expected_head: str) -> None:
ref = f"refs/heads/{name}"
worktrees = _git(gd, f"--git-dir={gd}", "worktree", "list", "--porcelain", "-z")
if f"branch {ref}" in worktrees.split("\0"):
raise WorktreeError(f"local branch {name!r} is checked out in another worktree")
Expand Down
77 changes: 40 additions & 37 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3346,41 +3346,21 @@ def finish_checks(_wt, _config, pr, *_args, **_kwargs):
assert budgets == [4.0]


@pytest.mark.parametrize("removed,error,hint", [
(False, "worktree is dirty",
"; fix the cause, then rerun `loopzero merge` in this worktree to finish cleanup"),
(True, "cannot lock ref",
"; worktree removed; delete local branch 'lz/t1' if it still points at the merged head"),
], ids=["worktree-remains", "branch-remains"])
def test_merge_warns_when_cleanup_fails(wt, gh, capsys, monkeypatch, head, removed, error, hint):
def test_merge_warns_when_cleanup_fails(wt, gh, capsys, monkeypatch, head):
arm_squash_merge(gh, head, wt, merge_json(state="MERGED", head=head, sha="d" * 40))
gh.respond("api -X", "")

def fail_cleanup(path, _expected_head):
if removed:
shutil.rmtree(path)
raise cli.worktree.WorktreeError(error)

monkeypatch.setattr(cli.worktree, "cleanup", fail_cleanup)
monkeypatch.setattr(cli.worktree, "cleanup", lambda *_: (_ for _ in ()).throw(
cli.worktree.WorktreeError("worktree is dirty")))
code, out, err = run(capsys, "merge")

assert code == 0 and out.splitlines()[-1] == "d" * 40
assert err.startswith(f"warning: merged but worktree cleanup failed: {error}")
assert err.rstrip().endswith(hint)
assert err.startswith("warning: merged but worktree cleanup failed: worktree is dirty")
assert err.rstrip().endswith("; fix the cause, then rerun `loopzero merge` in this worktree to finish cleanup")


def test_cleanup_hints_name_branch_and_configured_repo_without_commands(
def test_remote_cleanup_hint_names_branch_and_configured_repo_without_commands(
tmp_path: Path, capsys, monkeypatch
) -> None:
branch = "lz/fix$version"
monkeypatch.setattr(cli, "_repo_root", lambda _wt: tmp_path)
monkeypatch.setattr(cli.worktree, "branch", lambda _wt: branch)
monkeypatch.setattr(cli.worktree, "cleanup", lambda *_: (_ for _ in ()).throw(
cli.worktree.WorktreeError("cannot lock ref")))
cli._cleanup(tmp_path / "gone", SimpleNamespace(head_sha="a" * 40))
assert capsys.readouterr().err.rstrip().endswith(
"delete local branch 'lz/fix$version' if it still points at the merged head")

monkeypatch.setattr(cli.github, "delete_remote_branch", lambda *_: (_ for _ in ()).throw(
cli.github.GhError(("gh", "api"), "HTTP 500")))
cli._cleanup_remote_refs(tmp_path / "gone", SimpleNamespace(repo="acme/widgets"), branch, "a" * 40)
Expand Down Expand Up @@ -4561,26 +4541,49 @@ def interrupt(staged, dest, *, src_dir_fd, dst_dir_fd):
assert receipt.read_text() == "user file" and external.stat().st_mode & 0o777 == 0o755


@pytest.mark.parametrize("moved", [False, True])
def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head, moved):
@pytest.mark.parametrize("event", ["gone", "moved", "update-ref", "worktree", "no-proof"])
def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head, event):
cli._review_file(wt, head, "primary").write_text("{broken")
arm_pr(gh, head, isDraft=False, state="MERGED")
gh.append(f"api repos/{REPO}/pulls/7", merge_json(state="MERGED", head=head, sha="c" * 40))
gh.fail(f"api repos/{REPO}/git/ref/heads/lz/t1", "gh: Not Found (HTTP 404)")
merged = merge_json(state="MERGED", head=head, sha="c" * 40)
row = {**closed_history_row(pr_json(state="MERGED", headRefOid=head)), "created_at": "2026-10-07T05:04:00Z"}
gh.append(f"api repos/{REPO}/pulls/7", merged, row, merged)
gh.respond(f"api repos/{REPO}/commits/{head}/pulls?per_page=100&page=1", [] if event == "no-proof" else [row])
history = f"api repos/{REPO}/pulls?state=closed&head=acme%3Alz%2Ft1&per_page=100&page=1"
if event == "no-proof":
gh.respond(history, [])
git(wt, "switch", "--detach", head)
code, _, err = run(capsys, "merge")
assert code == 1 and "no merged PR proves cleanup" in err
assert wt.exists() and git(repo, "branch", "--list", "lz/t1").strip()
return
original = cli.worktree._git
advanced = git(wt, "commit-tree", f"{head}^{{tree}}", "-p", head, "-m", "newer").strip()

def cleanup_git(cwd, *args, **kwargs):
if args[1:3] == ("update-ref", "--no-deref"):
update = ("update-ref", "refs/heads/lz/t1", advanced) if moved else ("branch", "-D", "lz/t1")
if args[1:3] == ("update-ref", "--no-deref") and event in {"gone", "moved"}:
update = ("update-ref", "refs/heads/lz/t1", advanced) if event == "moved" else ("branch", "-D", "lz/t1")
git(repo, *update)
if (len(args) > 1 and args[0].startswith("--git-dir=") and args[1] == event
and args[1:3] != ("worktree", "list")):
raise KeyboardInterrupt
return original(cwd, *args, **kwargs)

monkeypatch.setattr(cli.worktree, "_git", cleanup_git)
code, out, err = run(capsys, "merge")
assert code == 0 and "was already merged" in out and not wt.exists()
assert ("but expected" in err) if moved else err == ""
assert git(repo, "branch", "--list", "lz/t1", "--format=%(objectname)").strip() == (advanced if moved else "")
with monkeypatch.context() as patch:
patch.setattr(cli.worktree, "_git", cleanup_git)
code, out, err = run(capsys, "merge")
if event in {"update-ref", "worktree"}:
assert code == 130 and "interrupted" in err and wt.exists()
assert not git(wt, "branch", "--show-current").strip()
assert bool(git(repo, "branch", "--list", "lz/t1").strip()) == (event == "update-ref")
if event == "worktree":
git(wt, "reset", "--hard", head)
gh.respond(f"api repos/{REPO}/commits/{head}/pulls?per_page=100&page=1", [])
gh.respond(history, [row])
code, out, err = run(capsys, "merge")
assert code == 0 and "was already merged" in out and wt.exists() == (event == "moved")
assert ("but expected" in err) if event == "moved" else err == ""
assert git(repo, "branch", "--list", "lz/t1", "--format=%(objectname)").strip() == (advanced if event == "moved" else "")
assert not any(call["argv"][:2] == ["api", "-X"] for call in gh.calls)


Expand Down
35 changes: 33 additions & 2 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,12 +281,43 @@ def test_task_helpers_errors(repo: Path) -> None:

def test_cleanup_removes_worktree_and_branch(repo: Path, monkeypatch) -> None:
wt, calls, real = worktree.start(repo, "done", "main"), [], worktree._git
monkeypatch.setattr(worktree, "_git", lambda d, *a, **k: calls.append((d, a)) or real(d, *a, **k))
worktree.cleanup(wt, worktree.head(wt)) # #439: no cleanup git runs in (or -C) the primary checkout
expected = worktree.head(wt)
advanced = git(wt, "commit-tree", f"{expected}^{{tree}}", "-p", expected, "-m", "concurrent").strip()

def checked_git(cwd, *args, **kwargs):
calls.append((cwd, args))
if args[1:3] == ("worktree", "remove"):
with pytest.raises(subprocess.CalledProcessError, match="non-zero") as locked:
git(wt, "update-ref", "--no-deref", "HEAD", advanced, expected)
assert "HEAD.lock" in locked.value.stderr
return real(cwd, *args, **kwargs)

monkeypatch.setattr(worktree, "_git", checked_git)
worktree.cleanup(wt, expected) # #439: no cleanup git runs in (or -C) the primary checkout
assert calls and all(Path(d).resolve() != repo.resolve() and "-C" not in a for d, a in calls)
assert not wt.exists() and not git(repo, "branch", "--list", "lz/done") and "done" not in git(repo, "worktree", "list")


@pytest.mark.parametrize("retry", [False, True])
def test_cleanup_keeps_concurrent_detached_commit(repo: Path, monkeypatch, retry: bool) -> None:
wt = worktree.start(repo, "concurrent", "main")
expected = worktree.head(wt)
if retry:
git(wt, "switch", "--detach", expected)
real_lock = worktree._lock_verified_ref
advanced = git(wt, "commit-tree", f"{expected}^{{tree}}", "-p", expected, "-m", "concurrent").strip()

def lock(cwd, ref, sha):
if ref == "HEAD":
git(wt, "update-ref", "--no-deref", "HEAD", advanced, expected)
return real_lock(cwd, ref, sha)

monkeypatch.setattr(worktree, "_lock_verified_ref", lock)
with pytest.raises(worktree.WorktreeError):
worktree.cleanup(wt, expected, "lz/concurrent")
assert worktree.head(wt) == advanced and git(repo, "branch", "--list", "lz/concurrent").strip()


@pytest.mark.parametrize("file", ["scratch.txt", "local.env", ".loopzero/user-notes.md"])
def test_cleanup_preserves_user_files(repo: Path, file: str) -> None:
(repo / ".git/info/exclude").write_text("local.env\n")
Expand Down
Loading