From 1f09c75f32b2b308341b1284ffa04abae55686fe Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:05:26 +0100 Subject: [PATCH 1/2] Pin local merge cleanup to the verified PR head Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 3 ++- src/loopzero/cli.py | 4 +--- src/loopzero/worktree.py | 49 +++++++++++++++++++++++++++++++++++----- tests/test_cli.py | 38 +++++++++++++++---------------- tests/test_worktree.py | 6 ++--- 5 files changed, 68 insertions(+), 32 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1d67cb81..66cf42c1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -269,7 +269,8 @@ 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 at the merged PR head. +holds a Git ref lock to keep the clean worktree at the merged PR head during +removal, then deletes the branch only if it still points at that head. 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 b4c64c5f..e28d41da 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1166,10 +1166,8 @@ def _cleanup(wt: Path, pr: github.PR) -> None: name = None try: _repo_root(wt) - if worktree.head(wt) != pr.head_sha: - raise worktree.WorktreeError("local HEAD differs from merged PR head") name = worktree.branch(wt) - worktree.cleanup(wt) + worktree.cleanup(wt, pr.head_sha) except (worktree.WorktreeError, OSError) as exc: retry = CLEANUP_RETRY if wt.exists() else "" if not retry and name is not None: diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 008a7cde..7f1b6b70 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -5,11 +5,15 @@ import errno import re import stat +import subprocess import tempfile +from collections.abc import Iterator +from contextlib import contextmanager from pathlib import Path +from select import select from uuid import uuid4 -from loopzero._proc import run +from loopzero._proc import build_env, run GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK") EXCLUDES = (".worktrees/", ".loopzero/") @@ -259,17 +263,50 @@ def merges_since(wt: Path, sha: str) -> list[str]: return _git(Path(wt), "rev-list", "--first-parent", "--reverse", "--merges", f"{sha}..HEAD").split() -def cleanup(wt: Path) -> None: +@contextmanager +def _lock_verified_ref(wt: Path, ref: str, expected_head: str) -> Iterator[None]: + argv = ("git", "update-ref", "--stdin") + with subprocess.Popen( + argv, cwd=wt, env=build_env(GIT_ENV), stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="surrogateescape", + ) as transaction: + assert transaction.stdin is not None and transaction.stdout is not None + try: + transaction.stdin.write(f"option no-deref\nverify {ref} {expected_head}\nprepare\n") + transaction.stdin.flush() + if not select([transaction.stdout], [], [], 30)[0]: + raise GitError(argv, "timed out verifying the merged branch") + response = transaction.stdout.readline() + if response != "prepare: ok\n": + raise GitError(argv, response) + yield + finally: + try: + transaction.communicate("abort\n", timeout=5) + except subprocess.TimeoutExpired: + transaction.terminate() + + +def cleanup(wt: Path, expected_head: str) -> None: """Remove the worktree and its branch. Refuses when the worktree is dirty.""" wt = Path(wt).absolute() if not wt.exists(): raise WorktreeError(f"no such worktree: {wt}") - if is_dirty(wt): - raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") + if head(wt) != expected_head: + raise WorktreeError("local HEAD differs from merged PR head") name, gd = branch(wt), (wt / _git(wt, "rev-parse", "--git-common-dir")).resolve() - _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout + 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}") + _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout + 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") try: - _git(gd, f"--git-dir={gd}", "branch", "-D", name) + _git(gd, f"--git-dir={gd}", "update-ref", "--no-deref", "-d", ref, expected_head) except GitError: if _git(gd, f"--git-dir={gd}", "branch", "--list", "--", name): raise diff --git a/tests/test_cli.py b/tests/test_cli.py index fda149c0..7cd149ca 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3494,7 +3494,7 @@ def test_merge_warns_when_cleanup_fails(wt, gh, capsys, monkeypatch, head, remov arm_squash_merge(gh, head, wt, merge_json(state="MERGED", head=head, sha="d" * 40)) gh.respond("api -X", "") - def fail_cleanup(path): + def fail_cleanup(path, _expected_head): if removed: shutil.rmtree(path) raise cli.worktree.WorktreeError(error) @@ -3513,11 +3513,9 @@ def test_cleanup_hints_name_branch_and_configured_repo_without_commands( branch = "lz/fix$version" monkeypatch.setattr(cli, "_repo_root", lambda _wt: tmp_path) monkeypatch.setattr(cli.worktree, "branch", lambda _wt: branch) - gone = tmp_path / "gone" monkeypatch.setattr(cli.worktree, "cleanup", lambda *_: (_ for _ in ()).throw( cli.worktree.WorktreeError("cannot lock ref"))) - monkeypatch.setattr(cli.worktree, "head", lambda _wt: "a" * 40) - cli._cleanup(gone, SimpleNamespace(head_sha="a" * 40)) + 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") @@ -4648,17 +4646,19 @@ def test_dirty_check_does_not_claim_committed_receipt(wt, capsys): assert "receipt produced:" not in out -@pytest.mark.parametrize("case", ["dirty", "unpushed"]) -def test_cleanup_preserves_local_work(wt, case, capsys): +@pytest.mark.parametrize("case", ["dirty", "unpushed", "after-head-read"]) +def test_cleanup_preserves_local_work(wt, case, capsys, monkeypatch): pr = SimpleNamespace(head_sha=cli.worktree.head(wt)) if case == "dirty": (wt / "untracked").write_text("keep me") else: git(wt, "commit", "--allow-empty", "-m", "local after merge") + if case == "after-head-read": + monkeypatch.setattr(cli.worktree, "head", lambda _wt: pr.head_sha) cli._cleanup(wt, pr) assert wt.exists() - err = capsys.readouterr().err - assert ("worktree is dirty" if case == "dirty" else "local HEAD differs") in err + diagnostic = {"dirty": "worktree is dirty", "unpushed": "local HEAD differs", "after-head-read": "but expected"} + assert diagnostic[case] in capsys.readouterr().err def _closed_unmerged_wait(monkeypatch, reads, steps=0): @@ -4714,26 +4714,26 @@ def interrupt(staged, dest): assert list(path.parent.iterdir()) == [path] -def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head): +@pytest.mark.parametrize("moved", [False, True]) +def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head, moved): (wt / ".loopzero" / "review-existing.json").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)) - ref = f"api repos/{REPO}/git/ref/heads/lz/t1" - gh.fail(ref, "gh: Not Found (HTTP 404)") - + gh.fail(f"api repos/{REPO}/git/ref/heads/lz/t1", "gh: Not Found (HTTP 404)") original = cli.worktree._git + advanced = git(wt, "commit-tree", f"{head}^{{tree}}", "-p", head, "-m", "newer").strip() def cleanup_git(cwd, *args, **kwargs): - result = original(cwd, *args, **kwargs) - if args[1:3] == ("worktree", "remove"): - git(repo, "branch", "-D", "lz/t1") - return result + if args[1:3] == ("update-ref", "--no-deref"): + update = ("update-ref", "refs/heads/lz/t1", advanced) if moved else ("branch", "-D", "lz/t1") + git(repo, *update) + 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 err == "" - assert not wt.exists() - assert not git(repo, "branch", "--list", "lz/t1") + 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 "") assert not any(call["argv"][:2] == ["api", "-X"] for call in gh.calls) diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 230adc02..43a6e477 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -233,7 +233,7 @@ 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) # #439: no cleanup git runs in (or -C) the primary checkout + worktree.cleanup(wt, worktree.head(wt)) # #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") @@ -242,13 +242,13 @@ def test_cleanup_refuses_dirty(repo: Path) -> None: wt = worktree.start(repo, "dirty", "main") (wt / "scratch.txt").write_text("x") with pytest.raises(worktree.WorktreeError, match="dirty"): - worktree.cleanup(wt) + worktree.cleanup(wt, worktree.head(wt)) assert wt.exists() and "lz/dirty" in git(repo, "branch", "--list", "lz/dirty") def test_cleanup_missing_worktree(repo: Path) -> None: with pytest.raises(worktree.WorktreeError, match="no such worktree"): - worktree.cleanup(repo / ".worktrees" / "ghost") + worktree.cleanup(repo / ".worktrees" / "ghost", worktree.head(repo)) @pytest.mark.parametrize("state", ["clean", "dirty", "divergent", "unpublished", "remote-moved", "stash"]) From 3769eb2858507c843d7d7879606940812053f375 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:17:53 +0100 Subject: [PATCH 2/2] Use the missing worktree path in both cleanup warning checks Co-Authored-By: Codex --- tests/test_cli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 3985a627..f1bc6ff4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3520,7 +3520,7 @@ def test_cleanup_hints_name_branch_and_configured_repo_without_commands( monkeypatch.setattr(cli.github, "delete_remote_branch", lambda *_: (_ for _ in ()).throw( cli.github.GhError(("gh", "api"), "HTTP 500"))) - cli._cleanup_remote_refs(gone, SimpleNamespace(repo="acme/widgets"), branch, "a" * 40) + cli._cleanup_remote_refs(tmp_path / "gone", SimpleNamespace(repo="acme/widgets"), branch, "a" * 40) assert capsys.readouterr().err.rstrip().endswith( "delete 'lz/fix$version' in acme/widgets if it still points at the merged head")