diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a967535a..5140e395 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -285,7 +285,9 @@ 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 with no ignored user files. +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. 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 3c3fac0e..f1ca4bd4 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1200,10 +1200,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 6a53d3e1..cd5c4ea3 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") _ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir") @@ -266,13 +270,31 @@ 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: - """Remove the worktree and branch if there are no local user files.""" - 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}") +@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 _require_no_ignored_user_files(wt: Path) -> None: ignored = _git( wt, "ls-files", "--others", "--ignored", "--exclude-standard", "-z", preserve_newlines=True ) @@ -284,10 +306,30 @@ def cleanup(wt: Path) -> None: ): continue raise WorktreeError(f"worktree contains ignored file {path!r}, refusing to remove: {wt}") - 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 + + +def cleanup(wt: Path, expected_head: str) -> None: + """Remove a clean merged worktree and its branch if it has no local user files.""" + 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) + 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}") + _require_no_ignored_user_files(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/conftest.py b/tests/conftest.py index 7fb3c9e8..a3e30c33 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,7 +9,7 @@ import pytest -from loopzero import github +from loopzero import _proc, github GIT_ENV = {"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"} @@ -30,16 +30,14 @@ def no_host_github_credentials(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) GIT_ENV |= {f"GIT_{_role}_NAME": "test", f"GIT_{_role}_EMAIL": "test@example.com"} +def git_environment() -> dict[str, str]: + return _proc.build_env(("PATH", "LANG", "LC_ALL"), GIT_ENV) + + def git(repo: Path, *args: str) -> str: """Run git in `repo` with a deterministic identity; return stdout.""" - env = {**os.environ, **GIT_ENV} - for key in os.environ: - if key in {"GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS"} or key.startswith( - ("GIT_CONFIG_KEY_", "GIT_CONFIG_VALUE_") - ): - env.pop(key) return subprocess.run( - ["git", *args], cwd=repo, env=env, capture_output=True, text=True, check=True + ["git", *args], cwd=repo, env=git_environment(), capture_output=True, text=True, check=True ).stdout diff --git a/tests/test_cli.py b/tests/test_cli.py index 4dcd0c99..ae3d8149 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3524,7 +3524,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) @@ -3543,17 +3543,15 @@ 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") 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") @@ -4717,17 +4715,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): @@ -4795,26 +4795,26 @@ def interrupt(staged, dest, *, src_dir_fd, dst_dir_fd): assert receipt.read_text() == "user file" and external.stat().st_mode & 0o777 == 0o755 -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): 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)) - 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_codex_transport.py b/tests/test_codex_transport.py index b954c896..57e66692 100644 --- a/tests/test_codex_transport.py +++ b/tests/test_codex_transport.py @@ -13,7 +13,7 @@ from loopzero import cli, eligibility, github, runners from loopzero.types import CheckReport, CheckResult, Config from tests import test_cli, test_runners -from tests.conftest import commit_file, git +from tests.conftest import commit_file, git, git_environment fake_bwrap = test_runners.fake_bwrap gh = test_cli.gh @@ -379,7 +379,7 @@ def test_large_publication_confirmation_and_hosted_agreement(native, gh, tmp_pat proof = runners.codex_evidence(result) assert proof["kind"] == "delta" and proof["calls"][0]["base"] == reviewed != merge_base argv = ["git", "diff", "--no-color", reviewed, head] - delta_diff = subprocess.check_output(argv, cwd=native[2]) + delta_diff = subprocess.check_output(argv, cwd=native[2], env=git_environment()) assert b"-hello\n+" + content in delta_diff if kind == "delta_legacy": assert "+caf\\xe9\r\n" in runners.render_patch(delta_diff) diff --git a/tests/test_worktree.py b/tests/test_worktree.py index b6db1e0e..8315f15e 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -8,7 +8,7 @@ import pytest from loopzero import worktree -from tests.conftest import commit_file, git +from tests.conftest import commit_file, git, git_environment, init_git_repo @pytest.fixture @@ -34,6 +34,13 @@ def commit_on_origin(repo: Path, name: str) -> str: return git(clone, "rev-parse", "HEAD").strip() +def test_git_fixture_ignores_inherited_directory(tmp_path, monkeypatch): + ambient = tmp_path / "ambient.git" + monkeypatch.setenv("GIT_DIR", str(ambient)) + checkout = init_git_repo(tmp_path / "checkout") + assert (checkout / ".git").is_dir() and not ambient.exists() + + def test_branch_preserves_unicode_whitespace(repo: Path) -> None: name = worktree.branch_name(repo, "zażółć\u00a0") git(repo, "switch", "-c", name) @@ -273,7 +280,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") @@ -284,13 +291,13 @@ def test_cleanup_preserves_user_files(repo: Path, file: str) -> None: wt = worktree.start(repo, "dirty", "main") (wt / file).write_text("x") with pytest.raises(worktree.WorktreeError, match="worktree is dirty" if file == "scratch.txt" else "ignored file"): - worktree.cleanup(wt) + worktree.cleanup(wt, worktree.head(wt)) assert (wt / file).read_text() == "x" 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"]) @@ -321,7 +328,7 @@ def test_abandoned_worktree_guide(repo: Path, tmp_path: Path, state: str) -> Non commands = section.split("```sh\n", 1)[1].split("```", 1)[0] result = subprocess.run( ["sh", "-c", commands, "cleanup-guide", str(wt), "abandoned", head], - cwd=caller, capture_output=True, text=True, check=False, + cwd=caller, env=git_environment(), capture_output=True, text=True, check=False, ) assert (result.returncode == 0) == (state == "clean"), result.stderr