Skip to content
Merged
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
6 changes: 3 additions & 3 deletions core/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,9 +206,9 @@ 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 covers first-parent topic changes and

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: Shortened wording drops what a remerge edit is measured against

The old text said the delta gets the changes from each automatic remerge to its recorded merge tree. The new text says only "edits to each automatic remerge", so it no longer says what those edits are compared with. A reader could take it to mean the whole merge diff against the first parent, which would pull in unrelated base changes. The task's acceptance criteria rule that out. If the size budget allows, a short fix is "edits from each automatic remerge to its recorded merge". The rewrapped lines are also about 115 characters wide, while the rest of this list wraps near 80. That passes the existing checks (tests/test_size_budget.py only limits core/CONTRACT.md's size), so it is only a style point.

edits to each automatic remerge. The reviewed commit must be on the first-parent history, and merged parents
must come from the verified base. 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
Expand Down
5 changes: 5 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,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),
Expand Down
4 changes: 3 additions & 1 deletion src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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:
Expand Down
49 changes: 25 additions & 24 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -848,11 +848,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,
Expand Down Expand Up @@ -1003,12 +1004,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)

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: Bound or fetch failures produce history-rewrite advice

base_merge_material returns None for two different cases. One is a proven bad history: the reviewed head is off the first-parent history, or a parent is not from the base. The other is any CandidateError: the 8 MiB _TREE_OUTPUT bound on the log --remerge-diff -p output, the shared 120 s _TREE_SECONDS deadline, a first-parent history deeper than _TREE_DEPTH=200, missing fetch auth, or a non-transient fetch error. _delta_patch treats both cases the same. It tells the user to save their work and replay fixes on the reviewed head, which is a history rewrite, even when the history is valid and only a resource bound or the fetch failed. A large but legitimate delta after a base merge would push the user into an unnecessary rewrite. Smallest fix: let CandidateError propagate (or return a separate sentinel) when the clean=False path is used, and report it as a verification or resource failure with retry advice. Keep the replay advice for the structural rejections only.

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(
Expand All @@ -1018,23 +1034,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 <original-tip>` 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)

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: publication[1] if publication else None adds an unreachable branch with a misleading result

The only caller of _run_review always passes publication. If a future caller omitted it, number=None would skip verification and raise the 'could not verify merge history … replay the fixes' error for a valid history. Prefer a subtractive fix: pass pr.number explicitly, or make publication required for delta reviews and drop the None handling in _delta_patch.

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)
Expand Down
53 changes: 35 additions & 18 deletions src/loopzero/eligibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",

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: Delta material relies on --remerge-diff overriding the diff-merges default that --first-parent sets

git log --first-parent defaults merge diffs to first-parent. Only the later explicit --remerge-diff keeps base changes out of the material. That is correct and the test asserts upstream.py is absent, but the behaviour is implicit and depends on option order and Git ≥ 2.36. Spelling it as --diff-merges=remerge makes the intent explicit and robust to option reordering.

"--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, ...], *,
Expand Down Expand Up @@ -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

Expand Down
90 changes: 72 additions & 18 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,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)
Expand Down Expand Up @@ -1791,35 +1806,74 @@ 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))

_, err = expect_cli(capsys, 1, "review")
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()
Expand Down
Loading