From 21676967b8ce1806e84127d320eee8c81a8faba2 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:43:21 +0100 Subject: [PATCH] Review conflict resolutions in the available delta round Co-Authored-By: Codex --- core/CONTRACT.md | 8 ++-- docs/ARCHITECTURE.md | 5 +++ src/loopzero/candidate.py | 4 +- src/loopzero/cli.py | 49 ++++++++++---------- src/loopzero/eligibility.py | 53 ++++++++++++++-------- tests/test_cli.py | 90 +++++++++++++++++++++++++++++-------- 6 files changed, 145 insertions(+), 64 deletions(-) diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 3dac1a17..1d1066eb 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -206,9 +206,11 @@ version. Loop-zero serves internal projects only and does not target tamper resistance for outside users. Freeze new work on Codex evidence projections. Simplify or delete them when they break or obstruct delivery. -- One primary and at most one delta per PR. The delta reads only - changes since the primary; unresolved primary findings still count under - Blockers. +- One primary and at most one delta per PR. After a base merge, the delta + receives first-parent topic patches and the changes from each automatic + remerge to its recorded merge tree. Merged parents must come from the verified + base, and the reviewed commit must be on the first-parent history. Unresolved + primary findings still count under Blockers. - Default: one writing model family per PR, including delegates and repairs; another may advise read-only and review independently. Before committing imported work, record every actual writing delegate in truthful diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f5acbb17..c590a260 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -100,6 +100,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con the PR-wide cap of one primary and one delta across head rewrites, and the [owner-approved contributor-review exception](../core/CONTRACT.md#owner-approved-contributor-review-exception), which changes neither the selector nor the budget. + The delta requires the reviewed commit on the current head's first-parent + history and verifies merged parents against the live configured base. The + runner receives topic patches in first-parent order and the difference + between each automatic remerge and its recorded tree. Isolated Git verifies + the history and builds the patch, excluding unrelated base changes. 5. `ready` derives readiness from the current head, its check receipt, an eligible review at that head or an eligible review covering an ancestor, blocking findings (unresolved threads a review publisher opened with a head-bound marker line), diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index fed9dee8..775d29ad 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -324,7 +324,7 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: } deadline = time.monotonic() + _TREE_SECONDS - def git(*args: str, command_env: dict[str, str] = env) -> str: + def git(*args: str, command_env: dict[str, str] = env, preserve_newlines: bool = False) -> str: with (root / "output").open("w+b") as output: process = subprocess.Popen( [sys.executable, "-I", "-S", "-c", _LIMITED_GIT, str(_TREE_BYTES), @@ -353,6 +353,8 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish output.seek(0) result = output.read(_TREE_OUTPUT + 1) _require(len(result) <= _TREE_OUTPUT, "Git object/output bound exceeded") + if preserve_newlines: + return result.decode("utf-8", errors="surrogateescape") return result.decode().strip() finally: if process.poll() is None: diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 29829078..5aaacd8a 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -829,11 +829,12 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: candidates = [family for family in config.reviewers if family not in authors] if result.fallback and not _published_fallback(result.fallback, candidates, excluded): raise CliError("saved fallback note is not in the published form; run without --repost") - allowed, _ = _decide_kind( + allowed, reviewed = _decide_kind( _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head ) if allowed != kind: raise CliError("saved review kind differs from the remaining review budget") + _delta_patch(wt, config, reviewed, head, pr.number) else: try: result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort, @@ -984,12 +985,27 @@ def _confirm_review(wt: Path, config: Config, pr: github.PR, result: ReviewResul return True -def _delta_merge_recovery(wt: Path, reviewed: str, merge: str) -> str: - pre_merge = _git(wt, "rev-parse", f"{merge}^1") - if not _is_ancestor(wt, reviewed, pre_merge): - return f"replay the fixes on the reviewed head {reviewed[:12]}" - return (f"save the current tip on a backup branch, use `git reset --hard {pre_merge}`, " - "and cherry-pick any later fixes from the backup") +def _delta_patch(wt: Path, config: Config, since: str | None, head: str, number: int | None) -> bytes: + if since is None: + return b"" + if not _is_ancestor(wt, since, head): + raise CliError( + f"reviewed head {since[:12]} is not an ancestor of this branch. Find the original tip with `git reflog`. " + "Back up your branch, reset to that tip and replay later fixes. To publish the restored head, " + f"run `loopzero pr`, then `loopzero review` before merging {config.base_branch}, or open a new PR" + ) + if not worktree.merges_since(wt, since): + return worktree.diff_since(wt, since) + patch = (eligibility.base_merge_material(config.repo, number, since, head, config.base_branch, clean=False) + if number is not None else None) + if patch is None: + raise CliError( + f"could not verify merge history: {since[:12]} must be on the first-parent history and " + f"merged parents must come from {config.base_branch}. Save your work, then replay the fixes " + f"on the reviewed head {since[:12]}, including resolution edits. Push with `loopzero pr` " + "and run `loopzero review`, or open a new PR" + ) + return patch def _run_review( @@ -999,23 +1015,8 @@ def _run_review( ) -> ReviewResult: lineage_base = _primary_base(wt, config) since = reviewed if kind == "delta" else lineage_base - if kind == "delta" and not _is_ancestor(wt, since, head): - raise CliError( - f"reviewed head {since[:12]} is not an ancestor of this branch. Find the original " - "branch tip with `git reflog`. Save the current tip on a backup branch, then use " - "`git reset --hard ` and replay any later fixes. To publish the restored " - f"head, run `loopzero pr`, then `loopzero review` before merging {config.base_branch}, or open a new PR " - "from the current branch" - ) - if kind == "delta" and (merges := worktree.merges_since(wt, since)): - recovery = _delta_merge_recovery(wt, since, merges[0]) - raise CliError( - f"merge commit {merges[0][:12]} since the reviewed head {since[:12]} would put the " - f"merged-in changes in the delta material. To recover, {recovery}. " - f"To publish the recovered head, run `loopzero pr`, then `loopzero review` " - f"before merging {config.base_branch} again" - ) - patch = worktree.diff_since(wt, since) + patch = (_delta_patch(wt, config, since, head, publication[1] if publication else None) + if kind == "delta" else worktree.diff_since(wt, since)) diff = runners.render_patch(patch) task = worktree.task_text(wt) authors = runners.author_families(wt, head, lineage_base) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 965efd5d..671d4f38 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -9,6 +9,7 @@ import json import re import sys +from collections.abc import Callable from pathlib import Path from loopzero import candidate, config, github, runners @@ -95,36 +96,52 @@ def eligible_review(reviews: list[dict], head: str, publishers: tuple[str, ...], return latest if verdict else None -def _clean_base_merges(repo: str, number: int, reviewed: str, head: str, base_branch: str) -> bool: - """Prove each intervening first-parent commit is an unmodified merge from the base.""" +def _verified_merge(git: Callable[..., str], merge: str, first: str, second: str, + base: str, *, clean: bool) -> bool: + git("merge-base", "--is-ancestor", second, base) + merge_bases = git("merge-base", "--all", first, second).splitlines() + # A shallow root outside the known merge bases could hide another base. + if git("rev-list", "--max-parents=0", first, second, "--not", *merge_bases): + return False + return not clean or git("merge-tree", "--write-tree", first, second) == git("rev-parse", f"{merge}^{{tree}}") + + +def base_merge_material( + repo: str, number: int, reviewed: str, head: str, base_branch: str, *, clean: bool, +) -> bytes | None: + """Return a verified delta patch, or empty bytes for proven clean inheritance.""" try: pr = github.api_get(f"repos/{repo}/pulls/{number}") base = pr["base"]["sha"] if (pr["head"]["sha"] != head or pr["base"]["ref"] != base_branch or not re.fullmatch(r"[0-9a-f]{40}", base)): - return False + return None with candidate.fetched_git(repo, [reviewed, head, base]) as git: history = git("rev-list", "--first-parent", "--parents", f"{reviewed}..{head}") cursor = head + row_lengths = {3} if clean else {2, 3} for row in history.splitlines(): commits = row.split() - if len(commits) != 3 or commits[0] != cursor: - return False - merge, first, second = commits - git("merge-base", "--is-ancestor", second, base) - merge_bases = git("merge-base", "--all", first, second).splitlines() - # A shallow root outside the known merge bases could hide another base. - if git("rev-list", "--max-parents=0", first, second, "--not", *merge_bases): - return False - tree = git("merge-tree", "--write-tree", first, second) - if tree != git("rev-parse", f"{merge}^{{tree}}"): - return False - cursor = first - return cursor == reviewed + if len(commits) not in row_lengths or commits[0] != cursor: + return None + cursor = commits[1] + if len(commits) == 2: + continue + if not _verified_merge(git, *commits, base, clean=clean): + return None + if cursor != reviewed: + return None + if clean: + return b"" + patch = git("log", "--first-parent", "--reverse", "--remerge-diff", "-p", "--format=", + "--no-color", "--no-ext-diff", "--no-textconv", "--text", + "--ignore-submodules=none", "--submodule=short", + f"{reviewed}..{head}", preserve_newlines=True) + return patch.encode("utf-8", errors="surrogateescape") except github.GhUnavailable: raise except (candidate.CandidateError, github.GhError, KeyError, OSError, TypeError, ValueError): - return False + return None def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...], *, @@ -158,7 +175,7 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...] return None elif not (verdict.startswith("approve** (") and state in {"APPROVED", "COMMENTED"}): return None - if not _clean_base_merges(repo, number, reviewed, head, base_branch): + if base_merge_material(repo, number, reviewed, head, base_branch, clean=True) is None: return None return latest diff --git a/tests/test_cli.py b/tests/test_cli.py index 53b0e0ba..e2772b0a 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -186,6 +186,21 @@ def head_of(path: Path) -> str: return git(path, "rev-parse", "HEAD").strip() +@pytest.fixture +def isolated_git(wt, monkeypatch, fake_tool): + """Use real isolated Git fetches against the test worktree.""" + fake_tool("prlimit", "exit 127\n") + popen = subprocess.Popen + + def fetch_from_worktree(argv, **kwargs): + if "fetch" in argv: + argv = [wt.as_uri() if arg == f"https://github.com/{REPO}.git" else arg for arg in argv] + return popen(argv, **kwargs) + + monkeypatch.setenv("GH_TOKEN", "test-token") + monkeypatch.setattr(subprocess, "Popen", fetch_from_worktree) + + @pytest.fixture def head(wt: Path) -> str: return head_of(wt) @@ -1832,37 +1847,76 @@ def test_review_delta_diffs_since_primary(wt: Path, gh: FakeGh, fake_bin: Path, assert marker(head, "delta") in payload["body"] -def test_review_delta_refuses_base_merge_since_primary(wt, repo, gh, fake_bin, capsys) -> None: - reviewed = head_of(wt) # intelflo#8393: primary-reviewed head, a merge of main, the delta - (repo / "upstream.py").write_text("y = 1\n") - git(repo, "add", "upstream.py") - git(repo, "commit", "-q", "-m", "landed on main") - git(wt, "merge", "-q", "--no-edit", "main") - merge = head_of(wt) - git(wt, "commit", "-q", "--allow-empty", "-m", "fix after review") - prepare_review(wt, gh, fake_bin, history=[rev(reviewed, "primary", state="CHANGES_REQUESTED")]) - code, out, err = run(capsys, "review") - assert code != 0 and out == "" and not (fake_bin / "claude.stdin").exists() - assert f"merge commit {merge[:12]} since the reviewed head {reviewed[:12]}" in err - assert f"`git reset --hard {reviewed}`" in err - assert "cherry-pick any later fixes" in err - assert "run `loopzero pr`, then `loopzero review` before merging main again" in err +def conflict_merge(wt, repo): + (wt / "README.md").write_text("branch edit\n") + git(wt, "commit", "-qam", "edit on branch") + reviewed = head_of(wt) + (repo / "README.md").write_text("base edit\n") + (repo / "upstream.py").write_text("upstream = 1\n") + git(repo, "add", "README.md", "upstream.py") + git(repo, "commit", "-qm", "landed on main") + with pytest.raises(subprocess.CalledProcessError) as exc: + git(wt, "merge", "--no-edit", "main") + assert "CONFLICT" in exc.value.stdout + (wt / "README.md").write_text("distinct resolution\n") + git(wt, "commit", "-qam", "resolve base merge") + return reviewed + + +@pytest.mark.parametrize("verified", [True, False]) +def test_review_delta_after_conflict_merge(wt, repo, gh, fake_bin, capsys, isolated_git, verified): + reviewed = conflict_merge(wt, repo) + (wt / ".gitmodules").write_text('[submodule "dep"]\npath = dep\nurl = ../dep\nignore = all\n') + git(wt, "add", ".gitmodules") + git(wt, "update-index", "--add", "--cacheinfo", f"160000,{reviewed},dep") + commit_file(wt, "topic.py", "topic = 2\n", "topic repair") + history = [rev(reviewed, "primary")] + head = prepare_review(wt, gh, fake_bin, history=history) + detail = rest_pr_json(pr_json(headRefOid=head, isDraft=False)) + detail["base"]["sha"] = git(repo, "rev-parse", "main" if verified else "main^").strip() + gh.respond(f"api repos/{REPO}/pulls/7", detail) + + code, _, err = run(capsys, "review") + + if not verified: + assert code == 1 and not (fake_bin / "claude.stdin").exists() + assert "could not verify merge history" in err and "including resolution edits" in err + return + assert code == 0, err + header, diff = (fake_bin / "claude.stdin").read_bytes().split(b"\n", 1) + assert json.loads(header)["head"] == head + assert b"+distinct resolution" in diff and b"+topic = 2" in diff and b"upstream.py" not in diff + assert f"+Subproject commit {reviewed}".encode() in diff and diff.endswith(b"+topic = 2\n") + posted = posted_review(gh) + assert posted["commit_id"] == head and marker(head, "delta") in posted["body"] + + exact = rev(head, "delta") + exact["body"] = posted["body"] + for reviews, ready in ((history, False), ([*history, exact], True)): + arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=reviews, isDraft=False) + gh.respond(f"api repos/{REPO}/pulls/7", detail) + assert run(capsys, "ready")[0] == (0 if ready else 1) + assert cli.eligibility.evaluate(REPO, 7, head, "main", (LOGIN,)).ready is ready def test_review_delta_replays_fixes_when_reviewed_head_is_second_parent( - wt: Path, gh: FakeGh, fake_bin: Path, capsys + wt: Path, gh: FakeGh, fake_bin: Path, capsys, isolated_git ) -> None: reviewed = head_of(wt) git(wt, "reset", "--hard", "main") git(wt, "commit", "-q", "--allow-empty", "-m", "independent branch work") git(wt, "merge", "-q", "--no-edit", reviewed) - prepare_review(wt, gh, fake_bin, history=[rev(reviewed, "primary", state="CHANGES_REQUESTED")]) + head = prepare_review(wt, gh, fake_bin, history=[rev(reviewed, "primary", state="CHANGES_REQUESTED")]) + detail = rest_pr_json(pr_json(headRefOid=head)) + detail["base"]["sha"] = reviewed # Even a verified base parent cannot substitute for the first parent. + gh.respond(f"api repos/{REPO}/pulls/7", detail) _fake_codex(fake_bin, json.dumps(APPROVE)) code, _, err = run(capsys, "review") assert code == 1 - assert f"replay the fixes on the reviewed head {reviewed[:12]}" in err + assert f"{reviewed[:12]} must be on the first-parent history" in err + assert f"on the reviewed head {reviewed[:12]}, including resolution edits" in err assert "git reset --hard" not in err assert not (fake_bin / "claude.stdin").exists() assert not (fake_bin / "codex.stdin").exists()