Skip to content
Closed
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
7 changes: 4 additions & 3 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def _pr_markers(reviews: list[dict], head: str,
if not eligibility.review_projection(review, head, repo, number)[0] and any(
runners.codex_fatal_startup(item) for item in eligibility.review_envelopes(body)[1]):
continue
match = REVIEW_MARKER_RE.search(body)
match = eligibility.leading_marker(body)
if not match or review.get("commit_id") != match.group(1):
continue
if not trusted:
Expand Down Expand Up @@ -894,8 +894,9 @@ def _confirm_review(wt: Path, config: Config, pr: github.PR, result: ReviewResul
publisher: str, reviews: list[dict]) -> bool:
"""Confirm an exact live publication; absence authorizes no automatic write."""
trusted = config.review_publishers or (publisher,)
evidence = [r for r in reviews if "loopzero:review" in (r.get("body") or "") and (r.get("commit_id") == result.head or any(
m.group(1) == result.head for m in REVIEW_MARKER_RE.finditer(r["body"])))]
evidence = [r for r in reviews if "loopzero:review" in (r.get("body") or "") and (
r.get("commit_id") == result.head
or ((marker := eligibility.leading_marker(r["body"])) and marker.group(1) == result.head))]
fresh = github.pr_view(config.repo, pr.number)
if fresh.head_sha != result.head or fresh.state != "OPEN" or fresh.base_ref != pr.base_ref:
raise CliError("PR changed during publication recovery")
Expand Down
16 changes: 12 additions & 4 deletions src/loopzero/eligibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@
CONTEXT = "Loop-zero Eligibility"


def leading_marker(body: str) -> re.Match[str] | None:
"""The review marker opening the publisher's leading machine block; prose never counts."""
block, span = runners.leading_review_block(body if isinstance(body, str) else "")
if not block or len(REVIEW_MARKER_RE.findall(span)) != 1:
return None
return REVIEW_MARKER_RE.fullmatch(block[0])


def review_envelopes(body: str) -> tuple[str, list[dict]]:
"""Decode only the publisher's raw-output block, not quoted findings/prose."""
if not isinstance(body, str):
Expand All @@ -40,7 +48,7 @@ def review_projection(review: dict, head: str, repo: str, number: int):
block, span = runners.leading_review_block(body)
positions = [i for i, line in enumerate(block) if line.lstrip().startswith("<!-- loopzero:codex-evidence")]
# Retired pair markers must never fall back to ordinary review evidence.
if any("source=pair" in marker[0] for marker in REVIEW_MARKER_RE.finditer(body)):
if any("source=pair" in marker[0] for marker in REVIEW_MARKER_RE.finditer(span)):
return True, None
if not positions:
return False, None
Expand Down Expand Up @@ -72,8 +80,8 @@ def eligible_review(reviews: list[dict], head: str, publishers: tuple[str, ...],
if latest is None or latest.get("state") not in {"APPROVED", "COMMENTED", "CHANGES_REQUESTED"}:
return None
body = latest.get("body") or ""
matches = list(REVIEW_MARKER_RE.finditer(body))
if len(matches) != 1 or matches[0].group(1) != head or not re.fullmatch(r"[0-9a-f]{40}", head):
marker = leading_marker(body)
if not marker or marker.group(1) != head or not re.fullmatch(r"[0-9a-f]{40}", head):
return None
verdict = latest.get("state") in {"APPROVED", "CHANGES_REQUESTED"} or any(
f"**{value}**" in body for value in ("approve", "request_changes")
Expand Down Expand Up @@ -126,7 +134,7 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...]
if not marked or any(r.get("commit_id") == head for r in marked):
return eligible_review(marked, head, publishers, repo=repo, number=number)
latest = marked[-1]
marker = REVIEW_MARKER_RE.search(latest["body"])
marker = leading_marker(latest["body"])
if not marker or marker[2] not in {"primary", "delta"}:
return None
reviewed = marker[1]
Expand Down
40 changes: 39 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

from loopzero import cli, config, github, mergify
from loopzero._proc import Completed, build_env
from loopzero.types import CheckReport, CheckResult, ReviewResult
from loopzero.types import CheckReport, CheckResult, Finding, ReviewResult
from tests.conftest import git, init_git_repo
from tests.fake_gh import replay
from tests.test_github import (
Expand Down Expand Up @@ -198,6 +198,44 @@ def test_review_marker_parser_accepts_old_and_v1_forms() -> None:
assert cli.REVIEW_MARKER_RE.search(new).groups() == ("b" * 40, "delta")


@pytest.mark.parametrize("source", ["model", "pair"])
def test_review_marker_quoted_in_prose_neither_voids_nor_hides_a_review(gh: FakeGh, source: str) -> None:
head = "a" * 40
quote = cli.review_marker("b" * 40, "primary", source)
result = ReviewResult("claude", head, "primary", "approve",
(Finding("suggestion", None, None, "Fixture", f"The fixture quotes {quote}."),),
"raw", provenance={"session_ids": ["s"]})
gh.respond(f"api repos/{REPO}/pulls/7/files", [])
(payload,) = github.review_payloads(REPO, 7, head, result, [(marker(head, "primary"), "current", False)])
review = {"body": payload["body"], "state": "COMMENTED", "commit_id": head, "user": {"login": LOGIN}}
assert quote in review["body"]

assert cli.eligibility.eligible_review([review], head, (LOGIN,)) is review
assert cli.eligibility.readiness_review(
[review], head, (LOGIN,), repo=REPO, number=7, base_branch="main") is review
assert cli._pr_markers([review], head, (LOGIN,)) == [cli.Marker(head, "primary", "COMMENTED")]


def test_second_review_marker_in_the_leading_block_voids_the_review() -> None:
head = "a" * 40
body = f"{marker(head, 'primary')}\n{marker('b' * 40, 'primary')}\nreview: **approve**"
review = {"body": body, "state": "APPROVED", "commit_id": head, "user": {"login": LOGIN}}
assert cli.eligibility.eligible_review([review], head, (LOGIN,)) is None
assert cli.eligibility.readiness_review(
[review], head, (LOGIN,), repo=REPO, number=7, base_branch="main") is None
assert cli._pr_markers([review], head, (LOGIN,)) == []


def test_publication_recovery_ignores_markers_quoted_on_other_commits(wt: Path, gh: FakeGh, head) -> None:
config = cli.config_mod.load(wt / "workflow.toml")
result = ReviewResult("claude", head, "primary", "approve", (), "raw", provenance={"session_ids": ["s"]})
other = rev("f" * 40, "primary")
other["body"] += f"\nA finding quotes {marker(head, 'primary')}"
gh.respond_pr_view(pr_json(headRefOid=head))
pr = github.PR(7, URL, head, "main", False, "OPEN", "MERGEABLE")
assert cli._confirm_review(wt, config, pr, result, LOGIN, [other]) is False


def rev(head: str, kind: str, *, state: str = "APPROVED", commit: str | None = None,
login: str = LOGIN, verdict: str = "approve") -> dict:
"""A review object as `gh api .../reviews` returns it, carrying a loopzero marker."""
Expand Down
Loading