Skip to content
4 changes: 2 additions & 2 deletions core/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,9 @@ version.

- Findings live only in PR review threads, expire at merge, and must not be
copied into files, issues or backlogs.
- Blocking marker:
- Blocking marker, as the first line of a thread a review publisher opened:
`<!-- loopzero:finding v=1 severity=critical head=<sha> id=<8-hex> -->`
(or `important`).
(or `important`). Other threads never block.
- `critical`: wrong or unsafe; must fix. `important`: ships a bug or breaks
acceptance; must fix. `suggestion`: never counted or blocking.
- Missing diff or required evidence: return one `critical` finding; never
Expand Down
3 changes: 2 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ The [CLI](../src/loopzero/cli.py) implements the contract's
[owner-approved contributor-review exception](../core/CONTRACT.md#owner-approved-contributor-review-exception),
which changes neither the selector nor the budget.
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,
head or an eligible review covering an ancestor, blocking findings
(unresolved threads a review publisher opened with a head-bound marker line),
target branch and required CI. The receipt must record a clean passing run
at that head with the current commands and check settings digest. A settings
change or an older receipt without the digest requires a fresh check. The
Expand Down
12 changes: 8 additions & 4 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ def _readiness(
workflow_wait and review_age is not None
and -MAX_REVIEW_CLOCK_SKEW <= review_age < STALE_VERDICT_GRACE
),
publishers=publishers,
)
report = _load_report(wt)
receipt_problem = _check_report_problem(report, wt, config, head)
Expand Down Expand Up @@ -1668,17 +1669,20 @@ def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None:

def cmd_resolve(args: argparse.Namespace) -> int:
"""List open blocking findings, or reply to one with what changed and resolve its thread."""
wt, config = _context(args)
wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR
pr = _require_pr(config, worktree.branch(wt))
if pr.base_ref != config.base_branch: # trusted publishers belong to the configured base
raise CliError(f"PR #{pr.number} targets {pr.base_ref}, configured base is {config.base_branch}")
publishers = config.review_publishers or (github.login(),)
if not args.finding:
for marker_id, _thread, f in github.open_findings(config.repo, pr.number):
for marker_id, _thread, f in github.open_findings(config.repo, pr.number, publishers):
print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}")
return 0
finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply)
finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply, publishers)
print(f"resolved {args.finding}: {finding.title}")
try:
with github.api_error_diagnostics():
remaining = github.open_blocking_findings(config.repo, pr.number)
remaining = github.open_blocking_findings(config.repo, pr.number, None, publishers)
except (github.GhError, _proc.ProcTimeout, OSError) as exc:
retry = shlex.join(("gh", *github.eligibility_dispatch_args(
config.repo, pr.number, config.base_branch,
Expand Down
5 changes: 3 additions & 2 deletions src/loopzero/eligibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...]
verdict = summary.partition(": **")[2]
state = latest.get("state")
if verdict.startswith("request_changes** (") and state in {"CHANGES_REQUESTED", "COMMENTED"}:
if github.open_blocking_findings(repo, number, reviewed):
if github.open_blocking_findings(repo, number, reviewed, publishers):
return None
elif not (verdict.startswith("approve** (") and state in {"APPROVED", "COMMENTED"}):
return None
Expand Down Expand Up @@ -182,7 +182,8 @@ def evaluate(repo: str, number: int, head: str, base: str,
page += 1
review = readiness_review(reviews, head, publishers, repo=repo, number=number, base_branch=base)
result = github.readiness(repo, pr, base, (), head if review else None, allow_behind=True,
ancestor_review=review is not None and review["commit_id"] != head)
ancestor_review=review is not None and review["commit_id"] != head,
publishers=publishers)
if github.pr_view(repo, number).head_sha != head:
return github.Readiness(False, ("source head changed during eligibility refresh",))
return result
Expand Down
67 changes: 40 additions & 27 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@
_app_token_cache = ("", 0.0)
MISSING_REVIEW_REASON = "no review recorded for the current head"
MARKER_RE = re.compile(
r"<!--\s*loopzero:finding\s+(?:v=(?P<version>1)\s+)?"
r"severity=(?P<severity>\w+)(?:\s+head=(?P<head>[0-9a-fA-F]+))?"
r"(?:\s+id=(?P<id>[0-9a-fA-F]{8}))?\s*-->"
r"<!-- loopzero:finding v=1 severity=(?P<severity>\w+) "
r"head=(?P<head>[0-9a-f]{40}) id=(?P<id>[0-9a-f]{8}) -->"
)
PAGE = 100
PR_FILE_LIMIT = 3_000
Expand All @@ -50,7 +49,9 @@
pageInfo { hasNextPage endCursor }
nodes {
id isResolved isOutdated path line
comments(first: 1) { nodes { body } pageInfo { hasNextPage endCursor } }
comments(first: 1) {
nodes { body author { __typename login } } pageInfo { hasNextPage endCursor }
}
}
}
}
Expand Down Expand Up @@ -965,22 +966,29 @@ def _title_of(text: str) -> str:
return re.sub(r"^\*\*\w+:\s*|\*\*$", "", title_line).strip()


def _parse_thread(node: dict, current_head: str | None) -> Finding | None:
def _thread_marker(node: dict, publishers: tuple[str, ...]) -> re.Match[str] | None:
"""The v=1 marker opening a thread's first comment, if a review publisher wrote it."""
comments = node.get("comments", {}).get("nodes") or []
if not comments:
return None
first = comments[0]
body = first.get("body") or ""
match = MARKER_RE.search(body)
author = comments[0].get("author") or {}
login = str(author.get("login") or "")
# GraphQL names an App's bot account without REST's "[bot]" suffix.
if author.get("__typename") == "Bot":
login += "[bot]"
if not login or login.casefold() not in {p.casefold() for p in publishers}:
return None
# The publisher writes the marker as the whole first line, exactly as finding_marker does.
return MARKER_RE.fullmatch((comments[0].get("body") or "").partition("\n")[0])


def _parse_thread(node: dict, current_head: str | None,
publishers: tuple[str, ...]) -> Finding | None:
match = _thread_marker(node, publishers)
if not match or match.group("severity") not in BLOCKING:
return None
version = match.group("version")
body = node["comments"]["nodes"][0]["body"]
marker_head = match.group("head")
marker_id = match.group("id")
if version and (not marker_head or not marker_id):
return None
if not version and marker_id:
return None
if current_head is not None and marker_head != current_head and node.get("isOutdated"):
return None
severity = match.group("severity")
Expand All @@ -998,12 +1006,13 @@ def _parse_thread(node: dict, current_head: str | None) -> Finding | None:
)


def open_findings(repo: str, number: int) -> list[tuple[str, str, Finding]]:
def open_findings(repo: str, number: int,
publishers: tuple[str, ...]) -> list[tuple[str, str, Finding]]:
"""(marker id, thread id, finding) for every unresolved blocking thread, any head."""
return [
(MARKER_RE.search(node["comments"]["nodes"][0]["body"]).group("id") or node["id"], node["id"], f)
(_thread_marker(node, publishers).group("id"), node["id"], f)

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: Reuse the marker ID from the validated match

Both open_findings and resolve_finding call _thread_marker again after _parse_thread has already validated the same comment. Returning the marker ID alongside the Finding would let both callers use the accepted match directly and avoid repeating the publisher lookup and regex match.

for node in _unresolved_threads(repo, number)
if (f := _parse_thread(node, None))
if (f := _parse_thread(node, None, publishers))
]


Expand Down Expand Up @@ -1037,16 +1046,16 @@ def _has_thread_reply(node: dict, reply: str) -> bool:
return False


def resolve_finding(repo: str, number: int, finding_id: str, reply: str) -> Finding:
def resolve_finding(repo: str, number: int, finding_id: str, reply: str,
publishers: tuple[str, ...]) -> Finding:
"""Reply to a blocking finding, or resume an identical resolution."""
threads = _review_threads(repo, number, include_resolved=True)
for node in sorted(threads, key=lambda node: bool(node.get("isResolved"))):
finding = _parse_thread(node, None)
finding = _parse_thread(node, None, publishers)
if finding is None:
continue
marker = MARKER_RE.search(node["comments"]["nodes"][0]["body"])
thread_id = node["id"]
if (marker.group("id") or thread_id) != finding_id:
if _thread_marker(node, publishers).group("id") != finding_id:
continue
confirmed = _has_thread_reply(node, reply)
if node.get("isResolved"):
Expand Down Expand Up @@ -1093,15 +1102,17 @@ def refresh_eligibility(repo: str, number: int, base: str) -> None:


def open_blocking_findings(
repo: str, number: int, current_head: str | None = None
repo: str, number: int, current_head: str | None, publishers: tuple[str, ...],
) -> list[Finding]:
"""Findings from unresolved review threads whose first comment carries a blocking marker.
"""Findings from unresolved review threads whose first comment opens with a blocking marker.

Only explicit critical and important markers block. When `current_head` is supplied, an
outdated thread is ignored unless its marker names that head.
Only critical and important v=1 markers on the first line of a comment written by a
review publisher block. When `current_head` is supplied, an outdated thread is ignored
unless its marker names that head.
"""
return [
f for node in _unresolved_threads(repo, number) if (f := _parse_thread(node, current_head))
f for node in _unresolved_threads(repo, number)
if (f := _parse_thread(node, current_head, publishers))
]


Expand Down Expand Up @@ -1289,6 +1300,7 @@ def readiness(
review_grace: bool = False,
workflow_wait: bool = False,
stale_verdict_grace: bool = False,
publishers: tuple[str, ...],
) -> Readiness:
"""Decide whether `pr` may be marked ready / merged. Never raises on policy failures."""
reasons: list[str] = []
Expand All @@ -1304,7 +1316,8 @@ def readiness(
reasons.append(MISSING_REVIEW_REASON)
elif pr.head_sha != reviewed_head:
reasons.append(f"head {pr.head_sha[:12]} differs from reviewed {reviewed_head[:12]}")
for f in open_blocking_findings(repo, pr.number, None if ancestor_review else pr.head_sha):
for f in open_blocking_findings(repo, pr.number, None if ancestor_review else pr.head_sha,
publishers):
where = f"{f.path}:{f.line}" if f.path else "(no location)"
reasons.append(f"open {f.severity} finding at {where}: {f.title}")
checks, stale, stale_verdicts, capped = (_check_signals(
Expand Down
52 changes: 44 additions & 8 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2185,7 +2185,7 @@ def test_ready_after_reviewed_head(
prefix = cli._repost_prefix(result) if reposted else marker(reviewed, kind)
review["body"] = github.review_payload(REPO, 7, reviewed, result, prefix)["body"]
thread = {"isResolved": resolved, "isOutdated": True, "path": "feature.py", "line": 1,
"comments": {"nodes": [{"body": f"<!-- loopzero:finding severity=important head={reviewed} -->"}]}}
"comments": {"nodes": [{"author": {"login": LOGIN}, "body": f"<!-- loopzero:finding v=1 severity=important head={reviewed} id=0b9b59e7 -->"}]}}
reviews = [rev("f" * 40, "primary"), review] if kind == "delta" else [review]
arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=reviews,
readiness={"threads": (thread,)}, isDraft=False)
Expand Down Expand Up @@ -2219,7 +2219,7 @@ def test_exact_head_delta_ignores_outdated_blocker(wt, gh, capsys, head):
previous = git(wt, "rev-parse", "HEAD^").strip()
history = [rev("f" * 40, "primary"), rev(head, "delta")]
thread = {"isResolved": False, "isOutdated": True, "path": "feature.py", "line": 1,
"comments": {"nodes": [{"body": f"<!-- loopzero:finding severity=critical head={previous} -->"}]}}
"comments": {"nodes": [{"author": {"login": LOGIN}, "body": f"<!-- loopzero:finding v=1 severity=critical head={previous} id=0b9b59e7 -->"}]}}
arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=history,
readiness={"threads": (thread,)}, isDraft=False)
code, _, _ = run(capsys, "ready")
Expand Down Expand Up @@ -2996,8 +2996,8 @@ def test_ready_draft_with_open_blocking_finding_does_not_mark_ready(
) -> None:
finding = {
"isResolved": False, "path": "feature.py", "line": 1,
"comments": {"nodes": [{"body":
f"<!-- loopzero:finding severity=important head={head} -->\n"
"comments": {"nodes": [{"author": {"login": LOGIN}, "body":
f"<!-- loopzero:finding v=1 severity=important head={head} id=0b9b59e7 -->\n"
"**important: Fix this**"}]},
}
arm_approved_pr_with_check_result(gh, head, wt, "skipped", readiness={"threads": (finding,)})
Expand Down Expand Up @@ -3199,7 +3199,7 @@ def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> Non
gh.respond(reviews_key(), [rev(head, "primary")])
arm_readiness(gh, head, wt, threads=(
{"isResolved": False, "isOutdated": False, "path": "feature.py", "line": 1,
"comments": {"nodes": [{"body": f"<!-- loopzero:finding severity=critical head={head} -->"
"comments": {"nodes": [{"author": {"login": LOGIN}, "body": f"<!-- loopzero:finding v=1 severity=critical head={head} id=0b9b59e7 -->"
"\n**critical: Bad**"}]}},))
code, out, err = run(capsys, "merge")
out = without_accepted_receipt(out)
Expand Down Expand Up @@ -4001,7 +4001,7 @@ def _finding_thread(marker_id: str, head: str) -> dict:
body = (f"<!-- loopzero:finding v=1 severity=important head={head} id={marker_id} -->\n"
"**important: Off by one**\n\nThe loop skips the last row.")
return {"id": "THREAD_1", "isResolved": False, "isOutdated": False, "path": "src/a.py",
"line": 3, "comments": {"nodes": [{"body": body}]}}
"line": 3, "comments": {"nodes": [{"author": {"login": LOGIN}, "body": body}]}}


@pytest.fixture
Expand All @@ -4027,7 +4027,8 @@ def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: Fak

code, out, err = run(capsys, "resolve", "0b9b59e7", "Fixed in abc1234: loop bound corrected.")
assert out.splitlines()[0] == "resolved 0b9b59e7: Off by one"
calls = [c["argv"] for c in gh.calls if c["argv"][:2] == ["api", "graphql"]][2:]
calls = [c["argv"] for c in gh.calls
if c["argv"][:2] == ["api", "graphql"] and "viewer {" not in c["argv"][3]][2:]
assert "addPullRequestReviewThreadReply" in calls[0][3] and "resolveReviewThread" in calls[1][3]
assert "body=Fixed in abc1234: loop bound corrected." in calls[0] and "thread=THREAD_1" in calls[1]
endpoint = f"repos/{REPO}/actions/workflows/eligibility.yml/dispatches"
Expand All @@ -4052,6 +4053,8 @@ def test_resolve_resumes_after_github_accepts_mutation(gh, finding_pr, capsys, m

def github_call(*args, **kwargs):
query = args[3]
if "viewer {" in query:
return {"data": {"viewer": {"login": LOGIN}}}
if "reviewThreads(" in query:
node["isResolved"] = bool(accepted["resolution"])
node["comments"]["pageInfo"] = {
Expand Down Expand Up @@ -4106,6 +4109,38 @@ def resolve_or_dispatch(*args, **kwargs):
assert run(capsys, "resolve") == (0, "", "")


def test_resolve_takes_review_publishers_from_the_base(wt: Path, gh: FakeGh, capsys, head) -> None:
(wt / "workflow.toml").write_text(WORKFLOW + '\nreview_publishers = ["outsider"]\n')
planted, genuine = _finding_thread("0b9b59e7", head), _finding_thread("1c2d3e4f", head)
planted["comments"]["nodes"][0]["author"] = {"__typename": "User", "login": "outsider"}
gh.respond_pr_list([pr_json(headRefOid=head)])
gh.respond("api graphql", threads_json(planted, genuine))
assert run(capsys, "resolve") == (0, "1c2d3e4f important src/a.py:3 Off by one\n", "")


@pytest.mark.parametrize("argv", [("resolve",), ("resolve", "0b9b59e7", "Fixed.")])
def test_resolve_refuses_a_pr_targeting_another_base(wt: Path, gh: FakeGh, capsys, head, argv) -> None:
gh.respond_pr_list([pr_json(headRefOid=head, baseRefName="release")])
code, out, err = run(capsys, *argv)
assert (code, out) == (1, "") and "PR #7 targets release, configured base is main" in err
assert not any("reviewThreads" in " ".join(c["argv"]) for c in gh.calls)


def test_resolve_and_ready_ignore_findings_from_non_publishers(wt: Path, gh: FakeGh, capsys, head) -> None:
planted = _finding_thread("0b9b59e7", head)
planted["comments"]["nodes"][0]["author"] = {"__typename": "User", "login": "outsider"}
gh.respond_pr_list([pr_json(headRefOid=head)])
gh.respond("api graphql", threads_json(planted))
assert run(capsys, "resolve") == (0, "", "")

arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=[rev(head, "primary")],
readiness={"threads": (planted,)}, isDraft=False)
code, out, _ = run(capsys, "ready")
gh.respond_pr_view(pr_json(headRefOid=head))
hosted = cli.eligibility.evaluate(REPO, 7, head, "main", (LOGIN,))
assert (code, hosted.ready) == (0, True), out


@pytest.mark.parametrize("response", [
{"data": {"resolveReviewThread": {"thread": {"isResolved": False}}}},
{"data": {"resolveReviewThread": {"thread": {}}}},
Expand Down Expand Up @@ -4165,7 +4200,8 @@ def test_resolve_retries_only_thread_resolution(finding_pr, gh: FakeGh, capsys,
assert code == 1
assert "reply posted to finding 0b9b59e7" in err
assert "Retry loopzero resolve with the same reply" in err
queries = [c["argv"][3] for c in gh.calls if c["argv"][:2] == ["api", "graphql"]]
queries = [c["argv"][3] for c in gh.calls
if c["argv"][:2] == ["api", "graphql"] and "viewer {" not in c["argv"][3]]
assert len(queries) == 2 + len(outcomes) + recovers
assert "addPullRequestReviewThreadReply" in queries[1]
assert all("resolveReviewThread" in query for query in queries[2:2 + len(outcomes)])
Expand Down
2 changes: 1 addition & 1 deletion tests/test_gh_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def captured_argv(tmp_path_factory: pytest.TempPathFactory) -> list[dict]:
result = ReviewResult("codex", HEAD, "primary", "request_changes",
(Finding("important", "src/a.py", 10, "Problem", "Details"),), "raw")
github.post_review(REPO, 7, HEAD, result)
github.open_blocking_findings(REPO, 7, HEAD)
github.open_blocking_findings(REPO, 7, HEAD, ("bot-user",))
github._check_signals(REPO, HEAD)
github.mark_ready(REPO, 7)
github.merge(REPO, 7, "squash", HEAD)
Expand Down
Loading
Loading