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 @@ -294,10 +294,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
44 changes: 30 additions & 14 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1250,16 +1250,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 @@ -1728,10 +1724,32 @@ def _merge_with_mergify(
return None


def _detached_merge_pr(wt: Path, config: Config) -> tuple[str, github.PR] | None:
if not (previous := worktree.detached_from(wt)):
return None
_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


def _already_merged_sha(config: Config, pr: github.PR) -> str:
sha = github.merged_sha(config.repo, pr.number, expected_head=pr.head_sha)
if sha is None:
raise CliError(f"PR #{pr.number} reports MERGED but has no merge commit yet; rerun")
print(f"PR #{pr.number} was already merged as {sha[:12]}; cleaning up")
return sha


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)
if not args.cancel and (detached := _detached_merge_pr(wt, config)):
branch, pr = detached
return _finish_merge(wt, config, branch, pr, _already_merged_sha(config, pr))
branch = worktree.branch(wt)
if args.cancel:
if config.merge_strategy != "mergify":
Expand All @@ -1756,13 +1774,7 @@ def cmd_merge(args: argparse.Namespace) -> int:
return 3
pr, readiness, _ = waited
if readiness is None:
sha = github.merged_sha(
config.repo, pr.number,
expected_head=pr.head_sha,
)
if sha is None:
raise CliError(f"PR #{pr.number} reports MERGED but has no merge commit yet; rerun")
print(f"PR #{pr.number} was already merged as {sha[:12]}; cleaning up")
sha = _already_merged_sha(config, pr)
elif config.merge_strategy == "mergify":
try:
sha = _merge_with_mergify(wt, config, pr, readiness, deadline, admit_by)
Expand Down Expand Up @@ -1790,8 +1802,12 @@ def cmd_merge(args: argparse.Namespace) -> int:
"next: loopzero merge --wait follows the queue, verifies and cleans up"
)
return 0
return _finish_merge(wt, config, branch, pr, sha)


def _finish_merge(wt: Path, config: Config, branch: str, pr: github.PR, sha: str) -> int:
_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."""
_, 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Closed-PR history paging duplicates merged_pr_for_branch with weaker validation

_merged_pr_from_history reimplements the pulls?state=closed&head=owner:branch paging loop that merged_pr_for_branch (github.py:750) already has. The new copy is missing some of the original's checks. It does not reject pages with more than PAGE rows, it does not dedupe repeated PR numbers, and it skips the row validation in _closed_history_number. Also, _matching_merged_pr raises a generic ("gh","api") error that does not name the endpoint. Because _pr_detail and the exact head/branch match recheck every candidate, this does not create a safety hole. It does mean two history readers can drift apart. Smallest fix: run the closed-history walk through the existing validation (_closed_history_number plus the page-size check), or add an optional exact-sha filter to merged_pr_for_branch instead of keeping a parallel loop.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Ignored-file scan runs twice under the HEAD lock

_require_clean_worktree(wt) at line 345 already calls _require_no_ignored_user_files. Line 347 then runs the same scan again with nothing in between except the branch-ref deletion, which does not touch the working tree. Drop line 347, or keep it and add a comment explaining why the second scan is needed.

_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 @@ -3494,41 +3494,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 @@ -4739,26 +4719,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 @@ -275,12 +275,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