diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 01f99ca4..db1218a3 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -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: `` - (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 bfe286f2..db875dcb 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -99,7 +99,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 46a93e29..92db6a6e 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -282,6 +282,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) @@ -1637,17 +1638,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, diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 4de8fb3d..89df5e8f 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -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 @@ -180,7 +180,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 e85f5300..83461121 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -28,9 +28,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 @@ -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 } + } } } } @@ -942,22 +943,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") @@ -975,12 +983,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)) ] @@ -1014,16 +1023,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"): @@ -1070,15 +1079,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)) ] @@ -1256,6 +1267,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] = [] @@ -1271,7 +1283,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 d86327d1..9eb27daa 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2159,7 +2159,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) @@ -2193,7 +2193,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") @@ -2978,8 +2978,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,)}) @@ -3122,7 +3122,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) @@ -3928,7 +3928,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"]) @@ -3947,7 +3947,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" @@ -3973,6 +3974,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"] = { @@ -4027,6 +4030,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": {}}}}, @@ -4094,7 +4129,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 fdcc7a71..afa311c7 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -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) diff --git a/tests/test_github.py b/tests/test_github.py index 14770538..69adb6c7 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -206,7 +206,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" @@ -667,35 +670,54 @@ 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"), + # 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"})) + 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", [ @@ -707,7 +729,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: @@ -805,15 +827,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"), } @@ -830,7 +849,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"), ] @@ -843,7 +862,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) @@ -852,7 +871,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) @@ -963,7 +982,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): @@ -1046,7 +1066,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}", @@ -1182,13 +1203,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"]] @@ -1506,7 +1528,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 == ( @@ -1536,7 +1558,7 @@ def test_readiness_requires_check_run_evidence_for_status_success_at_suite_cap( *({"check_runs": runs[i:i + 100]} for i in range(0, len(runs) + 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 result.ready == (reason is None) assert result.reasons == ((reason,) if reason else ()) 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]