From c105fb1748ad9f2b3fd363bd568360f93e4931fa Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:41:10 +0100 Subject: [PATCH 1/3] Count review-thread findings only from review publishers Readiness, hosted eligibility and loopzero resolve now count an unresolved review thread as a blocking finding only when a configured review publisher wrote its first comment and that comment opens with a head-bound v=1 finding marker. Threads from other commenters, quoted markers and unversioned markers no longer block or reach the resolve flow. Closes #1100 Co-Authored-By: Claude Opus 5.5 --- core/CONTRACT.md | 4 +-- docs/ARCHITECTURE.md | 3 +- src/loopzero/cli.py | 8 +++-- src/loopzero/eligibility.py | 5 +-- src/loopzero/github.py | 64 ++++++++++++++++++++++-------------- tests/test_cli.py | 35 +++++++++++++++----- tests/test_gh_contract.py | 2 +- tests/test_github.py | 65 ++++++++++++++++++++++++------------- tests/test_hosted.py | 3 +- 9 files changed, 125 insertions(+), 64 deletions(-) diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 7c1616ed..16e84b0c 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -186,9 +186,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: `` - (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 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c4d03052..df343d3f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -92,7 +92,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 diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 140c24a9..86865d16 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -309,6 +309,7 @@ def _readiness( workflow_wait and review_age is not None and -MAX_REVIEW_CLOCK_SKEW <= review_age < STALE_VERDICT_GRACE ), + publishers=publishers, ) report = _current_check_report(wt, config, head) if report is None: @@ -1579,15 +1580,16 @@ 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) pr = _require_pr(config, worktree.branch(wt)) + 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, diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 981c0bed..160be706 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -144,7 +144,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 @@ -172,7 +172,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 diff --git a/src/loopzero/github.py b/src/loopzero/github.py index a6d23fb3..3f13d470 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -49,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 } + } } } } @@ -872,22 +874,31 @@ 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) - if not match or match.group("severity") not in BLOCKING: + 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 - version = match.group("version") - marker_head = match.group("head") - marker_id = match.group("id") - if version and (not marker_head or not marker_id): + match = MARKER_RE.match(comments[0].get("body") or "") + if not match or not (match.group("version") and match.group("head") and match.group("id")): return None - if not version and marker_id: + return match + + +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 + body = node["comments"]["nodes"][0]["body"] + marker_head = match.group("head") if current_head is not None and marker_head != current_head and node.get("isOutdated"): return None severity = match.group("severity") @@ -905,12 +916,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) for node in _unresolved_threads(repo, number) - if (f := _parse_thread(node, None)) + if (f := _parse_thread(node, None, publishers)) ] @@ -944,16 +956,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"): @@ -1000,15 +1012,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)) ] @@ -1172,6 +1186,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] = [] @@ -1187,7 +1202,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( diff --git a/tests/test_cli.py b/tests/test_cli.py index e1cbdf4b..cf9c8cc4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1918,7 +1918,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""}]}} + "comments": {"nodes": [{"author": {"login": LOGIN}, "body": f""}]}} 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) @@ -1952,7 +1952,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""}]}} + "comments": {"nodes": [{"author": {"login": LOGIN}, "body": f""}]}} arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=history, readiness={"threads": (thread,)}, isDraft=False) code, _, _ = run(capsys, "ready") @@ -2586,8 +2586,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"\n" + "comments": {"nodes": [{"author": {"login": LOGIN}, "body": + f"\n" "**important: Fix this**"}]}, } arm_approved_pr_with_check_result(gh, head, wt, "skipped", readiness={"threads": (finding,)}) @@ -2704,7 +2704,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"" + "comments": {"nodes": [{"author": {"login": LOGIN}, "body": f"" "\n**critical: Bad**"}]}},)) code, out, err = run(capsys, "merge") out = without_accepted_receipt(out) @@ -3447,7 +3447,7 @@ def _finding_thread(marker_id: str, head: str) -> dict: body = (f"\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.mark.parametrize("outcome", ["refreshed", "remaining", "dispatch failed"]) @@ -3466,7 +3466,8 @@ def test_resolve_lists_then_replies_and_resolves_one_finding(wt: Path, gh: FakeG 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" @@ -3492,6 +3493,8 @@ def test_resolve_resumes_after_github_accepts_mutation(gh, wt, capsys, monkeypat 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"] = { @@ -3546,6 +3549,21 @@ def resolve_or_dispatch(*args, **kwargs): assert run(capsys, "resolve") == (0, "", "") +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": {}}}}, @@ -3613,7 +3631,8 @@ def test_resolve_retries_only_thread_resolution(wt: Path, gh: FakeGh, capsys, mo 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)]) diff --git a/tests/test_gh_contract.py b/tests/test_gh_contract.py index f9d8b19b..9e2fdb47 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -60,7 +60,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) diff --git a/tests/test_github.py b/tests/test_github.py index c7b1a3b4..48a5b1ae 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -204,7 +204,10 @@ def thread(body: str, resolved: bool = False, path: str = "src/a.py", line: int def marker(sev: str, head: str = HEAD) -> str: - return f"" + return f"" + + +PUBLISHERS = ("bot-user",) FILES_KEY = f"api repos/{REPO}/pulls/7/files" @@ -641,35 +644,50 @@ def test_open_blocking_findings_filters_and_parses(gh: FakeGh) -> None: versioned = github.finding_marker( "critical", HEAD, Finding("critical", "src/a.py", 3, "Null deref", "x may be None") ) - gh.respond("api graphql viewer", {"data": {"viewer": {"login": "bot-user"}}}) + app = thread(f"{marker('important')}\n**important: From the App**", path="src/c.py") + app["comments"]["nodes"][0]["author"] = {"__typename": "Bot", "login": "loopzero-app"} gh.respond("api graphql", threads_json( thread(f"{versioned}\n**critical: Null deref**\n\nx may be None"), thread(f"{marker('important')}\nplain title", resolved=True), thread(f"{marker('suggestion')}\n**suggestion: Rename**"), - thread("human intro\n" + marker("critical") + "\n**critical: Human marker**"), - thread("\nheadless", path="h.py", line=9), thread(f"{marker('important')}\n**important: Missing check**\n\nvalidate", path="src/b.py", line=2), + app, )) - found = github.open_blocking_findings(REPO, 7, HEAD) + found = github.open_blocking_findings(REPO, 7, HEAD, ("BOT-user", "loopzero-app[bot]")) assert found == [ Finding("critical", "src/a.py", 3, "Null deref", "**critical: Null deref**\n\nx may be None"), - Finding("critical", "src/a.py", 3, "Human marker", "**critical: Human marker**"), - Finding("important", "h.py", 9, "headless", "headless"), Finding("important", "src/b.py", 2, "Missing check", "**important: Missing check**\n\nvalidate"), + Finding("important", "src/c.py", 3, "From the App", "**important: From the App**"), ] argv = gh.argv(0) assert argv[:2] == ["api", "graphql"] assert "-F" in argv and "owner=acme" in argv and "name=widgets" in argv and "number=7" in argv - assert any(a.startswith("query=") and "lastEditedAt" not in a and "author" not in a for a in argv) + assert any(a.startswith("query=") and "author { __typename login }" in a for a in argv) + + +@pytest.mark.parametrize("body, author", [ + # A valid marker written by someone who is not a review publisher. + (f"{marker('critical')}\n**critical: Planted**", "outsider"), + # The App user name without the Bot type is a different (user) account. + (f"{marker('critical')}\n**critical: Lookalike**", "loopzero-app"), + # A publisher comment that only quotes a marker below its first line. + (f"**suggestion: Quote**\n\n{marker('critical')}", "bot-user"), + (f" {marker('critical')}\n**critical: Indented**", "bot-user"), + # Markers without a head and id are not tied to a reviewed head. + ("\nheadless", "bot-user"), + (f"\nunversioned", "bot-user"), +]) +def test_open_findings_ignore_untrusted_or_quoted_markers(gh: FakeGh, body: str, author: str) -> None: + gh.respond("api graphql", threads_json({**thread(body, author=author), "id": "T_1"})) + assert github.open_blocking_findings(REPO, 7, HEAD, ("bot-user", "loopzero-app[bot]")) == [] + assert github.open_findings(REPO, 7, ("bot-user", "loopzero-app[bot]")) == [] -def test_markers_without_id_are_resolvable_by_thread_id(gh: FakeGh) -> None: - legacy = {**thread("\nheadless"), "id": "T_1"} - gh.respond("api graphql viewer", {"data": {"viewer": {"login": "bot-user"}}}) - gh.respond("api graphql", threads_json(legacy)) - assert [(m, t) for m, t, _ in github.open_findings(REPO, 7)] == [("T_1", "T_1")] +def test_open_findings_without_publishers_block_nothing(gh: FakeGh) -> None: + gh.respond("api graphql", threads_json(thread(f"{marker('critical')}\n**critical: X**"))) + assert github.open_blocking_findings(REPO, 7, HEAD, ()) == [] @pytest.mark.parametrize("data", [ @@ -681,7 +699,7 @@ def test_markers_without_id_are_resolvable_by_thread_id(gh: FakeGh) -> None: def test_open_blocking_findings_missing_pr_is_gh_error(gh: FakeGh, data: dict) -> None: gh.respond("api graphql", data) with pytest.raises(github.GhError, match="PR #7 not found or not accessible"): - github.open_blocking_findings(REPO, 7, HEAD) + github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) def test_pr_for_branch_missing_key_is_gh_error(gh: FakeGh) -> None: @@ -804,7 +822,7 @@ def test_open_blocking_findings_counts_only_explicit_blocking_markers(gh: FakeGh thread(f"{marker('suggestion')}\n**suggestion: nit**", edited="2026-09-18T01:00:00Z"), thread(f"{marker('critical')}\nX", edited="2026-09-18T01:00:00Z", path="e.py", line=4), )) - found = github.open_blocking_findings(REPO, 7, HEAD) + found = github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) assert [(f.severity, f.path, f.line, f.title) for f in found] == [ ("critical", "e.py", 4, "X"), ] @@ -817,7 +835,7 @@ def test_open_blocking_findings_does_not_guess_from_body_or_author(gh: FakeGh) - thread("mentions loopzero but a human wrote it", author="human"), thread("bot-user wrote this but it is unrelated", author="bot-user"), )) - found = github.open_blocking_findings(REPO, 7, HEAD) + found = github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) assert found == [] assert all(c["argv"] != ["api", "user"] for c in gh.calls) @@ -826,7 +844,7 @@ def test_open_blocking_findings_paginates(gh: FakeGh) -> None: gh.respond("api graphql", threads_json(thread(f"{marker('critical')}\nA"), has_next=True, cursor="C1"), threads_json(thread(f"{marker('important')}\nB"))) - found = github.open_blocking_findings(REPO, 7, HEAD) + found = github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) assert [f.title for f in found] == ["A", "B"] assert "after=C1" not in gh.argv(0) and "after=C1" in gh.argv(1) @@ -937,7 +955,8 @@ def arm_workflow_check(gh: FakeGh, check: dict, statuses: list[dict] | None = No def readiness(*, reviewed=HEAD, workflow_wait=False): pr = github._pr_from_rest(rest_pr_json(pr_json())) - return github.readiness(REPO, pr, "main", ("checks",), reviewed, workflow_wait=workflow_wait) + return github.readiness(REPO, pr, "main", ("checks",), reviewed, workflow_wait=workflow_wait, + publishers=PUBLISHERS) def failed_check(conclusion="failure", **fields): @@ -1020,7 +1039,8 @@ def test_readiness_uses_head_or_non_outdated_rule_and_resolved_never_blocks( def test_readiness_missing_and_failed_checks(gh: FakeGh, failure, wait, grace) -> None: arm_readiness(gh, runs={"checks": failure}) r = github.readiness( - REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", ("checks", "e2e"), HEAD, workflow_wait=wait, review_grace=grace + REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", ("checks", "e2e"), HEAD, workflow_wait=wait, review_grace=grace, + publishers=PUBLISHERS, ) assert r.reasons == ( f"required check 'checks' is {failure}", @@ -1132,13 +1152,14 @@ def test_readiness_rerun_attempt_requires_start_after_old_failure( def test_readiness_metadata_blocker(gh: FakeGh, metadata: dict, reason: str) -> None: arm_readiness(gh) pr = github._pr_from_rest(rest_pr_json(pr_json(**metadata))) - r = github.readiness(REPO, pr, "main", ("checks",), HEAD) + r = github.readiness(REPO, pr, "main", ("checks",), HEAD, publishers=PUBLISHERS) assert r.reasons == (reason,) def test_readiness_without_required_ci_skips_check_lookup(gh: FakeGh) -> None: gh.respond("api graphql", threads_json()) - assert github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", (), HEAD).ready + assert github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", (), HEAD, + publishers=PUBLISHERS).ready assert [c["argv"][:2] for c in gh.calls] == [["api", "graphql"]] @@ -1450,7 +1471,7 @@ def test_readiness_distinguishes_capped_check_suites_from_missing_check(gh: Fake *({"check_runs": visible[i:i + 100]} for i in range(0, len(visible) + 1, 100))) result = github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())), - "main", ("required-ci",), HEAD) + "main", ("required-ci",), HEAD, publishers=PUBLISHERS) assert not result.ready assert result.reasons == ( diff --git a/tests/test_hosted.py b/tests/test_hosted.py index e15e7912..bda4f301 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -89,7 +89,8 @@ def test_source_publication_is_bound_to_live_review(publisher, case, blocker, st if blocker == "conflict": publisher.respond(f"api repos/{REPO}/pulls/7", fixtures.rest_pr_json(pr_json(mergeable="CONFLICTING"))) if blocker == "important": - publisher.respond("api graphql", threads_json(fixtures.thread(fixtures.marker("important") + "\nFinding"))) + publisher.respond("api graphql", threads_json(fixtures.thread(fixtures.marker("important") + "\nFinding", + author="trusted-publisher"))) assert hosted.main() == (1 if status == "failure" else 0) statuses = [json.loads(c["--input"]) for c in publisher.calls if "--input" in c] assert ([s["state"] for s in statuses] == ["pending", status] From f65764ab3e2f065145a1e210987440a5c2bcdcde Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:05:35 +0100 Subject: [PATCH 2/3] Pin resolve publishers to the base and require the exact marker line loopzero resolve now loads review publishers from the pinned base configuration, like ready and merge, so a PR's own workflow.toml cannot add a publisher. A finding marker counts only as the exact emitted first line with a full head and id. Refs #1100 Co-Authored-By: Claude Opus 5.5 --- src/loopzero/cli.py | 2 +- src/loopzero/github.py | 11 ++++------- tests/test_cli.py | 9 +++++++++ tests/test_github.py | 15 ++++++++------- 4 files changed, 22 insertions(+), 15 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 86865d16..08280eef 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1578,7 +1578,7 @@ 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)) publishers = config.review_publishers or (github.login(),) if not args.finding: diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 3f13d470..bd4b3729 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -27,9 +27,8 @@ _app_token_cache = ("", 0.0) MISSING_REVIEW_REASON = "no review recorded for the current head" MARKER_RE = re.compile( - r"" + r"" ) PAGE = 100 PR_FILE_LIMIT = 3_000 @@ -886,10 +885,8 @@ def _thread_marker(node: dict, publishers: tuple[str, ...]) -> re.Match[str] | N login += "[bot]" if not login or login.casefold() not in {p.casefold() for p in publishers}: return None - match = MARKER_RE.match(comments[0].get("body") or "") - if not match or not (match.group("version") and match.group("head") and match.group("id")): - return None - return match + # 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, diff --git a/tests/test_cli.py b/tests/test_cli.py index cf9c8cc4..e0bcfbe5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3549,6 +3549,15 @@ 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", "") + + 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"} diff --git a/tests/test_github.py b/tests/test_github.py index 48a5b1ae..3e93fdd3 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -678,6 +678,10 @@ def test_open_blocking_findings_filters_and_parses(gh: FakeGh) -> None: # Markers without a head and id are not tied to a reviewed head. ("\nheadless", "bot-user"), (f"\nunversioned", "bot-user"), + # Only the exact emitted line counts: not split, trailed by prose or truncated. + (marker("critical").replace(" head=", "\nhead=") + "\n**critical: Split**", "bot-user"), + (marker("critical") + " trailing prose\n**critical: Trailed**", "bot-user"), + (marker("critical", head=HEAD[:7]) + "\n**critical: Short head**", "bot-user"), ]) def test_open_findings_ignore_untrusted_or_quoted_markers(gh: FakeGh, body: str, author: str) -> None: gh.respond("api graphql", threads_json({**thread(body, author=author), "id": "T_1"})) @@ -797,15 +801,12 @@ def test_app_review_is_comment_with_inline_findings(gh: FakeGh, tmp_path: Path, assert payload["event"] == "COMMENT" and payload["comments"] -def test_marker_parser_accepts_old_and_v1_forms() -> None: - old = github.MARKER_RE.search("") - assert old and old.groupdict() == { - "version": None, "severity": "critical", "head": None, "id": None, - } +def test_marker_parser_accepts_only_the_emitted_v1_line() -> None: + assert github.MARKER_RE.fullmatch("") is None finding = Finding("important", "src/b.py", 2, "Missing check", "validate") - new = github.MARKER_RE.search(github.finding_marker("important", HEAD, finding)) + new = github.MARKER_RE.fullmatch(github.finding_marker("important", HEAD, finding)) assert new and new.groupdict() == { - "version": "1", "severity": "important", "head": HEAD, + "severity": "important", "head": HEAD, "id": github.finding_id(HEAD, "src/b.py", 2, "Missing check"), } From 5e6c40a8ff7fdeff052f660c2cf5da8f545bd0ce Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:40:01 +0100 Subject: [PATCH 3/3] Refuse resolve on a mismatched base and ignore PR-only publishers loopzero resolve now refuses a PR whose GitHub base differs from the configured base before reading findings, and pinned configuration never takes review publishers from the PR when the base has no workflow.toml; the current-login fallback applies instead. Refs #1100 Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 4 +++- src/loopzero/cli.py | 5 ++++- tests/test_cli.py | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index df343d3f..72fd3816 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -154,7 +154,9 @@ At native review launch the CLI pins checks, publishers and `delivery.reviewer_ro_paths` to one remote PR-base revision. A missing remote ref or workflow blocks launch. Bootstrap requires an explicit `--config`, which still undergoes validation. Reposts and other commands retain their fallback -policy. Runners validate the complete mount plan against private review state and +policy, except that review publishers never come from the PR's own workflow: +without a base workflow they are empty and the current login applies, and +`resolve` refuses a PR whose GitHub base differs from the configured base. Runners validate the complete mount plan against private review state and known standard/custom native state roots. Existing file-backed auth mounts remain explicit exceptions. Claude's environment routes are `ANTHROPIC_API_KEY` and `CLAUDE_CODE_OAUTH_TOKEN`: a nonempty value (whitespace included) is forwarded diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 08280eef..4d28eccc 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -112,7 +112,8 @@ def _load_config(args: argparse.Namespace, root: Path, *, pin_checks: bool = Fal config = config_mod.load(path, checks={}) base, revision = config_mod.load_base(root, config.base_branch) if base is None: - return config_mod.load(path) + # Never trust publishers the PR itself adds; the current-login fallback applies. + return dataclasses.replace(config_mod.load(path), review_publishers=()) base_checks = config_mod.base_section(base, config.base_branch, "checks") config = config_mod.load( path, checks=base_checks, validation_source=f"origin/{config.base_branch}:workflow.toml", @@ -1580,6 +1581,8 @@ 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, 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: + 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, publishers): diff --git a/tests/test_cli.py b/tests/test_cli.py index e0bcfbe5..5bea3cf8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3558,6 +3558,25 @@ def test_resolve_takes_review_publishers_from_the_base(wt: Path, gh: FakeGh, cap assert run(capsys, "resolve") == (0, "1c2d3e4f important src/a.py:3 Off by one\n", "") +def test_resolve_refuses_a_pr_whose_base_differs_from_the_configured_base( + wt: Path, gh: FakeGh, capsys, head, +) -> None: + (wt / "workflow.toml").write_text(WORKFLOW.replace('base = "main"', 'base = "trusting"') + + '\nreview_publishers = ["outsider"]\n') + gh.respond_pr_list([pr_json(headRefOid=head)]) + code, out, err = run(capsys, "resolve") + assert (code, out) == (1, "") and "PR #7 targets main, configured base is trusting" in err + assert not any(c["argv"][:2] == ["api", "graphql"] and "reviewThreads" in " ".join(c["argv"]) + for c in gh.calls) + + +def test_pinned_config_ignores_pr_publishers_when_the_base_has_no_workflow(wt: Path, monkeypatch) -> None: + (wt / "workflow.toml").write_text(WORKFLOW + '\nreview_publishers = ["outsider"]\n') + monkeypatch.setattr(cli.config_mod, "load_base", lambda *_: (None, None)) + args = SimpleNamespace(config=None, command="resolve") + assert cli._load_config(args, wt, pin_checks=True).review_publishers == () + + 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"}