From 36995ce9a4ebfed6f903486c741a1dc5e6ab0d32 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:46:57 +0100 Subject: [PATCH 1/2] Keep merged task cleanup recoverable until the branch is gone Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 11 ++++--- src/loopzero/cli.py | 31 +++++++++++------- src/loopzero/github.py | 17 ++++++++-- src/loopzero/worktree.py | 37 +++++++++++++++++---- tests/test_cli.py | 71 +++++++++++++++++++--------------------- 5 files changed, 106 insertions(+), 61 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..b9449e45 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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/` 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 diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f1645fb8..e0c6b417 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1200,16 +1200,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) @@ -1630,21 +1626,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) + return branch, pr, readiness + + 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. @@ -1693,7 +1702,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 diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 26e0e00c..00873bef 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -628,8 +628,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 "", [] @@ -653,6 +654,18 @@ 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) + for row in matches: + if row["state"] == "closed" and row["head"].get("sha") == sha: + pr, detail = _pr_detail(repo, row["number"]) + if (pr.state == "MERGED" and pr.head_sha == sha + and _matches_branch(detail["head"], repo, branch)): + return pr + return None + + 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") diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 444c8d5e..2f8dd364 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -10,7 +10,7 @@ import sys import tempfile from collections.abc import Iterator -from contextlib import contextmanager, suppress +from contextlib import contextmanager, nullcontext, suppress from pathlib import Path from select import select @@ -309,23 +309,46 @@ 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 + message = _git(wt, "reflog", "-1", "--format=%gs", "HEAD", preserve_whitespace=True) + match = re.fullmatch(rf"checkout: moving from (.+) to {head(wt)}", message) + return match[1] if match else 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) + current = _git(wt, "branch", "--show-current", preserve_whitespace=True) + name = name if name is not None else branch(wt) gd = Path(_git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)) + if Path(_git(wt, "rev-parse", "--absolute-git-dir", preserve_whitespace=True)) == gd: + raise WorktreeError("refusing cleanup from the primary checkout") + if current and current != name: + raise WorktreeError("local branch changed during merge cleanup") ref = f"refs/heads/{name}" - with _lock_verified_ref(wt, ref, expected_head): - if branch(wt) != name: + lock = _lock_verified_ref(wt, ref, expected_head) if current else nullcontext() + with lock: + if _git(wt, "branch", "--show-current", preserve_whitespace=True) != current: raise WorktreeError("local branch changed during merge cleanup") if is_dirty(wt): raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") _require_no_ignored_user_files(wt) - _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout + if current: + _git(wt, "-c", "core.logAllRefUpdates=true", "switch", "--quiet", "--detach", expected_head) + _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 + + +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") diff --git a/tests/test_cli.py b/tests/test_cli.py index fea79806..2f818218 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3496,41 +3496,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) @@ -4769,26 +4749,43 @@ 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]) + if event == "no-proof": + 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") + 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) From c87e64b9523bb840e5d9a6ab6ea80dc9414d7a71 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:22:30 +0100 Subject: [PATCH 2/2] Guard merged cleanup against concurrent detached commits Architecture-Review: unchanged; detached recovery still requires exact merged PR proof and now guards the local HEAD until removal. Co-Authored-By: Codex --- src/loopzero/cli.py | 8 +++--- src/loopzero/github.py | 32 +++++++++++++++++++----- src/loopzero/worktree.py | 53 ++++++++++++++++++++++++++-------------- tests/test_cli.py | 6 +++++ tests/test_worktree.py | 35 ++++++++++++++++++++++++-- 5 files changed, 105 insertions(+), 29 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e0c6b417..0cbb8299 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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) @@ -1637,7 +1639,7 @@ def _merge_pr_readiness( 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) + pr, readiness = _pr_readiness(wt, config, allow_merged=True, workflow_wait=workflow_wait, branch=branch) return branch, pr, readiness diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 00873bef..cb2e9547 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -657,15 +657,35 @@ def _commit_branch_prs(repo: str, branch: str, sha: str | None = None) -> tuple[ 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) - for row in matches: - if row["state"] == "closed" and row["head"].get("sha") == sha: - pr, detail = _pr_detail(repo, row["number"]) - if (pr.state == "MERGED" and pr.head_sha == sha - and _matches_branch(detail["head"], repo, branch)): - return pr + 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") diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 2f8dd364..7cc625e0 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -10,7 +10,8 @@ import sys import tempfile from collections.abc import Iterator -from contextlib import contextmanager, nullcontext, suppress +from contextlib import contextmanager, suppress +from itertools import pairwise from pathlib import Path from select import select @@ -313,9 +314,15 @@ 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 - message = _git(wt, "reflog", "-1", "--format=%gs", "HEAD", preserve_whitespace=True) - match = re.fullmatch(rf"checkout: moving from (.+) to {head(wt)}", message) - return match[1] if match else 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: @@ -325,26 +332,36 @@ def cleanup(wt: Path, expected_head: str, name: str | None = None) -> None: raise WorktreeError(f"no such worktree: {wt}") if head(wt) != expected_head: raise WorktreeError("local HEAD differs from merged PR head") - current = _git(wt, "branch", "--show-current", preserve_whitespace=True) name = name if name is not None else branch(wt) gd = Path(_git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)) if Path(_git(wt, "rev-parse", "--absolute-git-dir", preserve_whitespace=True)) == gd: raise WorktreeError("refusing cleanup from the primary checkout") - if current and current != name: - raise WorktreeError("local branch changed during merge cleanup") - ref = f"refs/heads/{name}" - lock = _lock_verified_ref(wt, ref, expected_head) if current else nullcontext() - with lock: - if _git(wt, "branch", "--show-current", preserve_whitespace=True) != current: - raise WorktreeError("local branch changed during merge cleanup") - if is_dirty(wt): - raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") - _require_no_ignored_user_files(wt) + current = _git(wt, "branch", "--show-current", preserve_whitespace=True) if current: - _git(wt, "-c", "core.logAllRefUpdates=true", "switch", "--quiet", "--detach", expected_head) - _delete_merged_branch(gd, name, expected_head) + _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)) + + +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) - _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout + + +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: diff --git a/tests/test_cli.py b/tests/test_cli.py index 2f818218..13473aa7 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4757,7 +4757,9 @@ def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypat 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 @@ -4782,6 +4784,10 @@ def cleanup_git(cwd, *args, **kwargs): 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 == "" diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 838ea563..ef593da7 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -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")