diff --git a/loopx/capabilities/pr_review_queue/github_source.py b/loopx/capabilities/pr_review_queue/github_source.py index f1dfcd7ecd..e0aba8edec 100644 --- a/loopx/capabilities/pr_review_queue/github_source.py +++ b/loopx/capabilities/pr_review_queue/github_source.py @@ -9,7 +9,8 @@ import re import subprocess from concurrent.futures import ThreadPoolExecutor -from collections.abc import Sequence +from collections.abc import Mapping, Sequence +from datetime import datetime, timezone from pathlib import Path from .selection_execution import normalize_fresh_audit_exact_heads @@ -242,6 +243,156 @@ def fetch_complete_pr_reviews(*, repository: str, number: str, cwd: Path | None, return reviews +def fetch_complete_pr_review_comments(*, repository: str, number: str, cwd: Path | None, + run_gh_json: GitHubJsonRunner) -> list[dict[str, Any]] | None: + """Read completely paginated PR inline comments; return None when incomplete.""" + try: + pages = run_gh_json(["api", "--paginate", "--slurp", + f"repos/{repository}/pulls/{number}/comments?per_page=100"], + **({"cwd": cwd} if cwd is not None else {})) + except Exception: + return None + if not isinstance(pages, list) or not pages or any(not isinstance(page, list) for page in pages): + return None + comments = [row for page in pages for row in page] + if any(not isinstance(row, dict) for row in comments): + return None + return comments + + +def _parse_review_epoch_ms(value: object) -> int | None: + if not isinstance(value, str) or not value.strip(): + return None + text = value.strip() + if text.endswith(("Z", "z")): + text = text[:-1] + "+00:00" + try: + parsed = datetime.fromisoformat(text) + except ValueError: + return None + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return int(round(parsed.timestamp() * 1000)) + + +def _empty_commented_non_author_review_ids( + reviews: Sequence[Mapping[str, Any]], *, author: str, head_oid: object, +) -> set[int]: + if not isinstance(head_oid, str) or not head_oid.strip(): + return set() + expected_head = head_oid.strip().casefold() + author_key = author.strip().casefold() + min_head_sort_key: dict[str, tuple[int, int]] = {} + unbounded_head_actors: set[str] = set() + for review in reviews: + review_id = review.get("id") + user = review.get("user") + login = user.get("login") if isinstance(user, Mapping) else None + commit_id = review.get("commit_id") + state = str(review.get("state") or "").strip().upper() + if ( + type(review_id) is int and review_id > 0 + and isinstance(login, str) and login.strip() + and login.strip().casefold() != author_key + and isinstance(commit_id, str) and commit_id.strip().casefold() == expected_head + and state not in {"PENDING", "DISMISSED"} + ): + actor_key = login.strip().casefold() + epoch_ms = _parse_review_epoch_ms(review.get("submitted_at")) + if epoch_ms is None: + unbounded_head_actors.add(actor_key) + else: + sort_key = (epoch_ms, review_id) + existing = min_head_sort_key.get(actor_key) + if existing is None or sort_key < existing: + min_head_sort_key[actor_key] = sort_key + + candidate_ids: set[int] = set() + for review in reviews: + review_id = review.get("id") + user = review.get("user") + login = user.get("login") if isinstance(user, Mapping) else None + commit_id = review.get("commit_id") + state = str(review.get("state") or "").strip().upper() + body = review.get("body") + body_text = body if isinstance(body, str) else str(body or "") + if not ( + type(review_id) is int and review_id > 0 + and isinstance(login, str) and login.strip() + and login.strip().casefold() != author_key + and isinstance(commit_id, str) and commit_id.strip() + and state == "COMMENTED" and not body_text.strip() + ): + continue + if commit_id.strip().casefold() == expected_head: + candidate_ids.add(review_id) + continue + # Only inspect older-head empty COMMENTED wrappers when the same reviewer + # has current-head activity that this later/tied review could displace. + actor_key = login.strip().casefold() + if actor_key in unbounded_head_actors: + candidate_ids.add(review_id) + elif actor_key in min_head_sort_key: + epoch_ms = _parse_review_epoch_ms(review.get("submitted_at")) + if epoch_ms is None or (epoch_ms, review_id) > min_head_sort_key[actor_key]: + candidate_ids.add(review_id) + return candidate_ids + + +def _empty_commented_review_provenance( + reviews: Sequence[Mapping[str, Any]], *, author: str, head_oid: object, + repository: str, number: str, cwd: Path | None, run_gh_json: GitHubJsonRunner, +) -> dict[int, str]: + """Classify candidate empty non-author COMMENTED reviews into three states: + + - ``reply_only``: >=1 attributed inline comments, all valid positive-int ``in_reply_to_id``. + - ``inline_root``: >=1 attributed inline root comment (missing or ``None`` ``in_reply_to_id``). + - ``unknown``: inline comments fetch failed/empty/malformed, contained an unattributable + entry without a valid ``pull_request_review_id``, had malformed reply links, or yielded + 0 comments attributed to the candidate review. + """ + candidate_ids = _empty_commented_non_author_review_ids(reviews, author=author, head_oid=head_oid) + if not candidate_ids: + return {} + comments = fetch_complete_pr_review_comments( + repository=repository, number=number, cwd=cwd, run_gh_json=run_gh_json, + ) + if comments is None: + return {review_id: "unknown" for review_id in candidate_ids} + matched_counts: dict[int, int] = {} + root_ids: set[int] = set() + malformed_reply_ids: set[int] = set() + has_unattributable_comment = False + for comment in comments: + review_id = comment.get("pull_request_review_id") + if type(review_id) is not int or review_id <= 0: + has_unattributable_comment = True + continue + if review_id not in candidate_ids: + continue + matched_counts[review_id] = matched_counts.get(review_id, 0) + 1 + if "in_reply_to_id" not in comment or comment.get("in_reply_to_id") is None: + root_ids.add(review_id) + continue + parent_id = comment.get("in_reply_to_id") + if type(parent_id) is not int or parent_id <= 0: + malformed_reply_ids.add(review_id) + + provenance: dict[int, str] = {} + for review_id in candidate_ids: + if review_id in root_ids: + provenance[review_id] = "inline_root" + elif ( + has_unattributable_comment + or review_id in malformed_reply_ids + or matched_counts.get(review_id, 0) == 0 + ): + provenance[review_id] = "unknown" + else: + provenance[review_id] = "reply_only" + return provenance + + def _attach_review_provenance(row: dict[str, Any], details: dict[str, Any], *, repository: str, number: str, cwd: Path | None, run_gh_json: GitHubJsonRunner, @@ -276,6 +427,16 @@ def _attach_review_provenance(row: dict[str, Any], details: dict[str, Any], *, "authorAssociation": review.get("author_association"), "state": review.get("state"), "submittedAt": review.get("submitted_at"), "commit": {"oid": review.get("commit_id")}, "body": review.get("body")}) + provenance_by_id = _empty_commented_review_provenance( + reviews, author=author, head_oid=row.get("headRefOid"), + repository=repository, number=number, cwd=cwd, run_gh_json=run_gh_json, + ) + for item, review in zip(normalized, reviews, strict=True): + provenance = provenance_by_id.get(review["id"]) + if provenance is not None: + item["comment_provenance"] = provenance + if provenance == "reply_only": + item["thread_reply_only"] = True after = run_gh_json(["pr", "view", number, "--json", "headRefOid,baseRefOid", "--repo", repository], cwd=cwd) if not isinstance(after, dict) or any(after.get(key) != row.get(key) diff --git a/loopx/control_plane/capabilities/pr_review_approval_closeout.ts b/loopx/control_plane/capabilities/pr_review_approval_closeout.ts index 78340fe75c..cd32237c6e 100644 --- a/loopx/control_plane/capabilities/pr_review_approval_closeout.ts +++ b/loopx/control_plane/capabilities/pr_review_approval_closeout.ts @@ -7,10 +7,12 @@ import {parseIsoTimestamp} from "../runtime_timestamp.ts"; // GitHub owns these input states; closeout statuses are local to this read model. type ReviewState = "PENDING" | "COMMENTED" | "APPROVED" | "CHANGES_REQUESTED" | "DISMISSED"; +type CommentProvenance = "reply_only" | "inline_root" | "unknown"; type Opinion = {id: number; login: string; state: ReviewState; head: string; time: number}; type Review = Opinion & {submittedAt: string | null; url: string}; type ProviderOpinion = Opinion & {source: JsonObject; conclusion: JsonObject}; const states = new Set(["PENDING", "COMMENTED", "APPROVED", "CHANGES_REQUESTED", "DISMISSED"]); +const commentProvenances = new Set(["reply_only", "inline_root", "unknown"]); // GitHub associations, not a reviewer-name allowlist or evidence of approval. const repositoryReviewers = new Set(["OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR"]); function fail(message: string): never { throw new EffectRuntimeRequestError(message); } @@ -35,7 +37,8 @@ function effectiveOpinions(reviews: readonly T[], author: str /** Submitted review activity establishes account-level evidence. Model coverage * also requires a qualified conclusion. Comments here are formal review events; - * issue comments do not enter this history. Dismissal retires only that actor. */ + * inline thread replies and issue comments do not establish or retire activity. + * Dismissal retires only that actor. */ function independentReviewEvidence(reviews: readonly ProviderOpinion[], complete: boolean, author: string | null, head: string, includeCoverage: boolean): JsonObject { if (!complete || !author) return {}; @@ -51,6 +54,28 @@ function independentReviewEvidence(reviews: readonly ProviderOpinion[], if (row.state === "PENDING") continue; const submittedAt = typeof source.submitted_at === "string" ? parseIsoTimestamp(source.submitted_at) : null; if (!submittedAt || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(row.head)) return {}; + const rawProvenance = source.comment_provenance; + if (rawProvenance !== undefined + && (typeof rawProvenance !== "string" || !commentProvenances.has(rawProvenance as CommentProvenance))) { + return {}; + } + const provenance = rawProvenance as CommentProvenance | undefined; + if (provenance === "inline_root" && source.thread_reply_only === true) return {}; + if (provenance === "reply_only" && source.thread_reply_only === false) return {}; + // GraphQL thread-reply wrappers have no verified formal or inline-root review activity + // and must never establish or retire coverage. Unknown provenance on the current head + // cannot certify coverage; unknown provenance on an older head fails closed if newer. + if ( + row.state === "COMMENTED" + && row.conclusion.valid !== true + && ( + provenance === "reply_only" + || (provenance === undefined && source.thread_reply_only === true) + || (provenance === "unknown" && row.head === head) + ) + ) { + continue; + } const candidate = {...row, id, time: submittedAt.getTime()}; submitted?.push(candidate); const previous = latest.get(row.login); diff --git a/loopx/pr_review.py b/loopx/pr_review.py index d97d2abb51..4407bd3672 100644 --- a/loopx/pr_review.py +++ b/loopx/pr_review.py @@ -873,6 +873,9 @@ def evaluate(review: Mapping[str, Any]) -> tuple[dict[str, Any], bool]: "is_bot": _as_dict(review.get("author")).get("is_bot"), "submitted_at": review.get("submittedAt"), "conclusion": conclusion, + **({"comment_provenance": review["comment_provenance"]} + if isinstance(review.get("comment_provenance"), str) else {}), + **({"thread_reply_only": True} if review.get("thread_reply_only") is True else {}), **({"review_body_valid": body_valid} if include_model_coverage else {})} for review, (conclusion, body_valid) in zip(reviews, evaluations, strict=True) ] diff --git a/tests/capabilities/test_pr_review_independent_review.py b/tests/capabilities/test_pr_review_independent_review.py index f2dabe02db..b89497e261 100644 --- a/tests/capabilities/test_pr_review_independent_review.py +++ b/tests/capabilities/test_pr_review_independent_review.py @@ -225,3 +225,293 @@ def test_malformed_provider_history_retains_ordinary_review(pages): def test_inline_only_submitted_review_does_not_need_an_agent_body(): row = packet([review() | {"body": ""}])["pull_requests"][0] assert row["review_action_kind"] is None and not row["review_conclusion"]["valid"] + + +def _provider_with_comments( + review_pages, comment_pages, *, pr_author="cocolord", current_head=HEAD, +): + snapshot = deepcopy(review_pages[0][0]) + pr = raw_pr([{ + "id": snapshot["id"], "url": snapshot["html_url"], + "author": {"login": snapshot["user"]["login"]}, + "authorAssociation": snapshot["author_association"], + "state": snapshot["state"], "commit": {"oid": snapshot["commit_id"]}, + "body": snapshot["body"], "submittedAt": snapshot["submitted_at"], + }], head=current_head) + pr["author"] = {"login": pr_author} + pr.pop("reviews_complete") + calls = [] + + def run(args, *, cwd=None): + del cwd + calls.append(args) + if args[:2] == ["pr", "view"]: + if args[args.index("--json") + 1] == "headRefOid,baseRefOid": + return {"headRefOid": current_head, "baseRefOid": pr["baseRefOid"]} + return deepcopy(pr) + if args[:4] == ["api", "--paginate", "--slurp", "repos/owner/repo/pulls/42/reviews?per_page=100"]: + return deepcopy(review_pages) + if args[:4] == ["api", "--paginate", "--slurp", "repos/owner/repo/pulls/42/comments?per_page=100"]: + if isinstance(comment_pages, Exception): + raise comment_pages + return deepcopy(comment_pages) + raise AssertionError(f"unexpected gh args: {args}") + + return run, calls + + +def test_thread_reply_only_empty_commented_review_does_not_conclude_current_head(): + # Shape of GitHub GraphQL addPullRequestReviewThreadReply on cocolord PR: + # prior CHANGES_REQUESTED on OLD head, plus empty-body COMMENTED wrapper on HEAD. + old_req = rest_review(review(1, login="loopx-agent", state="CHANGES_REQUESTED", head=OLD, association="MEMBER")) + reply_wrapper = rest_review(review(2, login="loopx-agent", state="COMMENTED", head=HEAD, association="MEMBER")) | {"body": ""} + comments = [[{ + "id": 4713426271, + "pull_request_review_id": 2, + "in_reply_to_id": 4713301777, + }]] + run, calls = _provider_with_comments([[old_req, reply_wrapper]], comments, pr_author="cocolord") + from loopx.capabilities.pr_review_queue.github_source import scan_github_pull_request_targets + + scan = scan_github_pull_request_targets(repository="owner/repo", exact_heads=[f"42@{HEAD}"], wait_for_ci=False, run_gh_json=run) + annotated = {r["id"]: r for r in scan["pull_requests"][0]["reviews"]} + assert annotated[2]["comment_provenance"] == "reply_only" + assert annotated[2]["thread_reply_only"] is True + row = source_packet(run)["pull_requests"][0] + assert row["review_action_kind"] == "rereview_pull_request_exact_head" + assert row["scheduling_lane"] != "current_head_concluded" + assert "independent_review" not in row + assert any("pulls/42/comments" in " ".join(call) for call in calls) + + +@pytest.mark.parametrize("comments", [ + [[{"id": 99, "pull_request_review_id": 1}]], + [[{"id": 99, "pull_request_review_id": 1, "in_reply_to_id": None}]], + [[{"id": 99, "pull_request_review_id": 1}, {"id": 100, "pull_request_review_id": 1, "in_reply_to_id": 88}]], + [[{"id": 100, "pull_request_review_id": 1, "in_reply_to_id": 88}], [{"id": 99, "pull_request_review_id": 1, "in_reply_to_id": None}]], + [[{"id": 99, "pull_request_review_id": 1, "in_reply_to_id": None}], [{"id": 101}]], +]) +def test_inline_root_empty_commented_review_still_establishes_independent_review(comments): + from loopx.capabilities.pr_review_queue.github_source import scan_github_pull_request_targets + + root_inline = rest_review(review(1, login="contributor", state="COMMENTED", head=HEAD)) | {"body": " "} + run, _ = _provider_with_comments([[root_inline]], comments, pr_author="author") + scan = scan_github_pull_request_targets(repository="owner/repo", exact_heads=[f"42@{HEAD}"], wait_for_ci=False, run_gh_json=run) + assert scan["pull_requests"][0]["reviews"][0]["comment_provenance"] == "inline_root" + assert "thread_reply_only" not in scan["pull_requests"][0]["reviews"][0] + row = source_packet(run)["pull_requests"][0] + assert row["review_action_kind"] is None + assert row["independent_review"]["review_id"] == 1 + assert row["independent_review"]["source_complete"] is True + + +def test_thread_reply_wrapper_preserves_earlier_current_head_formal_opinion(): + formal = rest_review(review(10, login="loopx-agent", state="CHANGES_REQUESTED", head=HEAD, association="MEMBER")) + reply_wrapper = rest_review(review(11, login="loopx-agent", state="COMMENTED", head=HEAD, association="MEMBER")) | {"body": ""} + comments = [[{ + "id": 4713426271, + "pull_request_review_id": 11, + "in_reply_to_id": 4713301777, + }]] + for ordered in ([formal, reply_wrapper], [reply_wrapper, formal]): + for bad_or_good in (comments, OSError("comments unavailable"), [[comments[0][0]], [{"id": 999}]]): + run, _ = _provider_with_comments([ordered], bad_or_good, pr_author="cocolord") + row = source_packet(run)["pull_requests"][0] + assert row["review_action_kind"] is None + assert row["independent_review"]["review_id"] == 10 + assert row["independent_review"]["state"] == "CHANGES_REQUESTED" + assert row["independent_review"]["source_complete"] is True + + +@pytest.mark.parametrize("bad_comments", [ + OSError("comments unavailable"), + [], + [[]], + {}, + [[123]], + [[{"id": 100, "pull_request_review_id": 2, "in_reply_to_id": 88}], [{"id": 101}]], + [[{"id": 100, "pull_request_review_id": 2, "in_reply_to_id": 88}], [{"id": 101, "pull_request_review_id": None}]], + [[{"id": 100, "pull_request_review_id": 2, "in_reply_to_id": 88}], [{"id": 101, "pull_request_review_id": "2"}]], + [[{"id": 100, "pull_request_review_id": 999, "in_reply_to_id": 88}], [{"id": 101, "pull_request_review_id": 888, "in_reply_to_id": None}]], + [[{"id": 100, "pull_request_review_id": 2, "in_reply_to_id": 0}]], +]) +def test_unknown_comment_provenance_retains_rereview_and_never_claims_source_complete(bad_comments): + from loopx.capabilities.pr_review_queue.github_source import scan_github_pull_request_targets + + old_req = rest_review(review(1, login="loopx-agent", state="CHANGES_REQUESTED", head=OLD, association="MEMBER")) + reply_wrapper = rest_review(review(2, login="loopx-agent", state="COMMENTED", head=HEAD, association="MEMBER")) | {"body": ""} + run, _ = _provider_with_comments([[old_req, reply_wrapper]], bad_comments, pr_author="cocolord") + scan = scan_github_pull_request_targets(repository="owner/repo", exact_heads=[f"42@{HEAD}"], wait_for_ci=False, run_gh_json=run) + annotated = {r["id"]: r for r in scan["pull_requests"][0]["reviews"]} + assert annotated[2]["comment_provenance"] == "unknown" + assert "thread_reply_only" not in annotated[2] + row = source_packet(run)["pull_requests"][0] + assert row["review_action_kind"] == "rereview_pull_request_exact_head" + assert row["scheduling_lane"] != "current_head_concluded" + assert "independent_review" not in row + + +def test_cross_model_coverage_ignores_thread_reply_only_commented_review(): + reply_wrapper = review(2, login="loopx-agent", state="COMMENTED", head=HEAD, association="MEMBER") | { + "body": "", "thread_reply_only": True, + } + pr = raw_pr([reply_wrapper], complete=True, head=HEAD) | {"author": {"login": "cocolord"}} + data = build_pr_review_packet( + pull_requests=[pr], repository="owner/repo", source="fixture", limit=10, + state_filter="all", reviewer_login="loopx-agent", wait_for_ci=False, + reviewer_model_family="gpt", + ) + row = data["pull_requests"][0] + assert row["review_action_kind"] == "rereview_pull_request_exact_head" + assert "independent_review" not in row + + +def test_old_head_reply_wrapper_preserves_current_head_formal_opinion_across_queues(): + from loopx.capabilities.pr_review_queue.github_source import scan_github_pull_request_targets + + formal_body = ( + "Reviewer: model_agent · GPT-6 · OpenAI · runtime_reported · effort_unavailable\n\n" + "Looks solid overall.\n\n" + "Verdict: APPROVE" + ) + head_formal = rest_review( + review(10, login="peer", state="APPROVED", head=HEAD, association="MEMBER") + | {"body": formal_body, "submittedAt": "2026-10-01T10:00:00Z"} + ) + old_reply = rest_review( + review(11, login="peer", state="COMMENTED", head=OLD, association="MEMBER") + | {"body": "", "submittedAt": "2026-10-01T11:00:00Z"} + ) + reply_comments = [[{ + "id": 4713500001, + "pull_request_review_id": 11, + "in_reply_to_id": 4713400001, + }]] + + for ordered in ([head_formal, old_reply], [old_reply, head_formal]): + for family in (None, "gpt"): + run, calls = _provider_with_comments([ordered], reply_comments, pr_author="cocolord") + scan = scan_github_pull_request_targets( + repository="owner/repo", + exact_heads=[f"42@{HEAD}"], + wait_for_ci=False, + run_gh_json=run, + ) + annotated = {r["id"]: r for r in scan["pull_requests"][0]["reviews"]} + assert annotated[11]["comment_provenance"] == "reply_only" + assert any("pulls/42/comments" in str(part) for args in calls for part in args) + + kwargs = {"reviewer_model_family": family} if family else {} + packet_data = build_pr_review_packet( + pull_requests=scan["pull_requests"], + source="github_cli_exact_targets", + source_scan=scan, + repository="owner/repo", + limit=10, + state_filter="all", + reviewer_login="loopx-agent", + wait_for_ci=False, + **kwargs, + ) + row = packet_data["pull_requests"][0] + assert row["review_action_kind"] is None + assert row["independent_review"]["review_id"] == 10 + assert row["independent_review"]["state"] == "APPROVED" + assert row["independent_review"]["source_complete"] is True + assert row.get("cross_model_review_needed") is not True + + +def test_old_head_inline_root_dismissed_and_unknown_still_retire_current_head_coverage(): + from loopx.capabilities.pr_review_queue.github_source import scan_github_pull_request_targets + + formal_body = ( + "Reviewer: model_agent · GPT-6 · OpenAI · runtime_reported · effort_unavailable\n\n" + "Looks solid overall.\n\n" + "Verdict: APPROVE" + ) + head_formal = rest_review( + review(10, login="peer", state="APPROVED", head=HEAD, association="MEMBER") + | {"body": formal_body, "submittedAt": "2026-10-01T10:00:00Z"} + ) + old_empty = rest_review( + review(11, login="peer", state="COMMENTED", head=OLD, association="MEMBER") + | {"body": "", "submittedAt": "2026-10-01T11:00:00Z"} + ) + old_dismissed = rest_review( + review(12, login="peer", state="DISMISSED", head=OLD, association="MEMBER") + | {"body": "", "submittedAt": "2026-10-01T11:00:00Z"} + ) + + root_comments = [[{"id": 4713500002, "pull_request_review_id": 11, "in_reply_to_id": None}]] + for page, bad_or_root, expected_prov in ( + ([head_formal, old_empty], root_comments, "inline_root"), + ([head_formal, old_empty], OSError("comments unavailable"), "unknown"), + ([head_formal, old_dismissed], OSError("should not fetch comments"), None), + ): + run, _ = _provider_with_comments([page], bad_or_root, pr_author="cocolord") + scan = scan_github_pull_request_targets( + repository="owner/repo", + exact_heads=[f"42@{HEAD}"], + wait_for_ci=False, + run_gh_json=run, + ) + if expected_prov is not None: + annotated = {r["id"]: r for r in scan["pull_requests"][0]["reviews"]} + assert annotated[11]["comment_provenance"] == expected_prov + + for family in (None, "gpt"): + kwargs = {"reviewer_model_family": family} if family else {} + packet_data = build_pr_review_packet( + pull_requests=scan["pull_requests"], + source="github_cli_exact_targets", + source_scan=scan, + repository="owner/repo", + limit=10, + state_filter="all", + reviewer_login="loopx-agent", + wait_for_ci=False, + **kwargs, + ) + row = packet_data["pull_requests"][0] + assert row["review_action_kind"] is not None + assert "independent_review" not in row + + +def test_earlier_or_unrelated_old_head_empty_commented_skips_comments_fetch(): + from loopx.capabilities.pr_review_queue.github_source import scan_github_pull_request_targets + + earlier_old = rest_review( + review(9, login="peer", state="COMMENTED", head=OLD, association="MEMBER") + | {"body": "", "submittedAt": "2026-10-01T09:00:00Z"} + ) + head_formal = rest_review( + review(10, login="peer", state="APPROVED", head=HEAD, association="MEMBER") + | {"body": "Looks good.", "submittedAt": "2026-10-01T10:00:00Z"} + ) + unrelated_old = rest_review( + review(8, login="other", state="COMMENTED", head=OLD, association="CONTRIBUTOR") + | {"body": "", "submittedAt": "2026-10-01T11:00:00Z"} + ) + + for page in ([head_formal], [earlier_old, head_formal], [earlier_old, head_formal, unrelated_old]): + run, calls = _provider_with_comments([page], OSError("unexpected comments call"), pr_author="cocolord") + scan = scan_github_pull_request_targets( + repository="owner/repo", + exact_heads=[f"42@{HEAD}"], + wait_for_ci=False, + run_gh_json=run, + ) + assert not any("pulls/42/comments" in str(part) for args in calls for part in args) + row = build_pr_review_packet( + pull_requests=scan["pull_requests"], + source="github_cli_exact_targets", + source_scan=scan, + repository="owner/repo", + limit=10, + state_filter="all", + reviewer_login="loopx-agent", + wait_for_ci=False, + )["pull_requests"][0] + assert row["review_action_kind"] is None + assert row["independent_review"]["review_id"] == 10 + assert row["independent_review"]["source_complete"] is True diff --git a/tests/control_plane_ts/pr_review_approval_closeout.test.ts b/tests/control_plane_ts/pr_review_approval_closeout.test.ts new file mode 100644 index 0000000000..45429c393e --- /dev/null +++ b/tests/control_plane_ts/pr_review_approval_closeout.test.ts @@ -0,0 +1,286 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import {selectPrReviewConclusion} from "../../loopx/control_plane/capabilities/pr_review_approval_closeout.ts"; + +const HEAD = "a".repeat(40); +const OLD = "b".repeat(40); + +function makeOpinion( + reviewId: number, + { + login = "loopx-agent", + state = "COMMENTED", + head = HEAD, + time = reviewId, + association = "MEMBER", + isBot = false, + valid = false, + verdict = "COMMENT", + commentProvenance = undefined as string | undefined, + threadReplyOnly = false, + family = null as string | null, + reviewBodyValid = false, + } = {}, +) { + return { + state, + login, + head, + time, + review_id: reviewId, + url: `https://github.com/loopx-project/loopx/pull/9038#pullrequestreview-${reviewId}`, + association, + is_bot: isBot, + submitted_at: `2026-11-26T21:16:${String(reviewId).padStart(2, "0")}Z`, + conclusion: {valid, verdict, reviewer: login, state}, + ...(commentProvenance !== undefined ? {comment_provenance: commentProvenance} : {}), + ...(threadReplyOnly ? {thread_reply_only: true} : {}), + ...(family !== null ? {review_model_family: family, review_body_valid: reviewBodyValid} : {}), + }; +} + +test("thread-reply-only COMMENTED wrapper on PR opened by another author does not establish independent_review", () => { + const result = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + include_independent_coverage: true, + reviews: [ + makeOpinion(6, {login: "loopx-agent", state: "COMMENTED", head: HEAD, threadReplyOnly: true}), + makeOpinion(4, {login: "loopx-agent", state: "CHANGES_REQUESTED", head: OLD, verdict: "REQUEST_CHANGES"}), + ], + }); + assert.equal(result.independent_review, undefined); + assert.deepEqual(result.independent_review_activity_ids, []); + assert.deepEqual(result.independent_coverage_review_ids, []); +}); + +test("later thread-reply-only COMMENTED wrapper does not overwrite earlier current-head opinion", () => { + const priorFormal = makeOpinion(10, { + login: "loopx-agent", + state: "CHANGES_REQUESTED", + head: HEAD, + valid: true, + verdict: "REQUEST_CHANGES", + family: "gpt", + reviewBodyValid: true, + }); + const replyWrapper = makeOpinion(12, { + login: "loopx-agent", + state: "COMMENTED", + head: HEAD, + threadReplyOnly: true, + }); + + for (const ordered of [[priorFormal, replyWrapper], [replyWrapper, priorFormal]]) { + const result = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + include_independent_coverage: true, + reviews: ordered, + }); + assert.deepEqual(result.independent_review, { + reviewer: "loopx-agent", + association: "MEMBER", + state: "CHANGES_REQUESTED", + head_oid: HEAD, + review_id: 10, + url: "https://github.com/loopx-project/loopx/pull/9038#pullrequestreview-10", + submitted_at: "2026-11-26T21:16:10Z", + source_complete: true, + grants_approval: false, + grants_merge_authority: false, + }); + assert.deepEqual(result.independent_review_activity_ids, [10]); + assert.deepEqual(result.independent_coverage_review_ids, [10]); + } +}); + +test("genuine inline-root COMMENTED review without thread_reply_only still establishes independent_review", () => { + const result = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + reviews: [ + makeOpinion(1, {login: "contributor", association: "CONTRIBUTOR", state: "COMMENTED", head: HEAD}), + ], + }); + assert.equal((result.independent_review as {review_id: number}).review_id, 1); + assert.equal((result.independent_review as {state: string}).state, "COMMENTED"); +}); + +test("qualified COMMENTED conclusion is preserved even if thread_reply_only flag is present", () => { + const result = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + reviews: [ + makeOpinion(7, { + login: "peer", + state: "COMMENTED", + head: HEAD, + valid: true, + verdict: "APPROVE", + threadReplyOnly: true, + }), + ], + }); + assert.equal((result.independent_review as {review_id: number}).review_id, 7); +}); + +test("unknown comment_provenance on same reply-only snapshot never certifies independent_review", () => { + const result = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + include_independent_coverage: true, + reviews: [ + makeOpinion(6, {login: "loopx-agent", state: "COMMENTED", head: HEAD, commentProvenance: "unknown"}), + makeOpinion(4, {login: "loopx-agent", state: "CHANGES_REQUESTED", head: OLD, verdict: "REQUEST_CHANGES"}), + ], + }); + assert.equal(result.independent_review, undefined); + assert.deepEqual(result.independent_review_activity_ids, []); + assert.deepEqual(result.independent_coverage_review_ids, []); +}); + +test("inline_root comment_provenance explicitly establishes independent_review while unknown preserves prior formal opinion", () => { + const rootResult = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + reviews: [ + makeOpinion(1, {login: "contributor", association: "CONTRIBUTOR", state: "COMMENTED", head: HEAD, commentProvenance: "inline_root"}), + ], + }); + assert.equal((rootResult.independent_review as {review_id: number}).review_id, 1); + assert.equal((rootResult.independent_review as {source_complete: boolean}).source_complete, true); + + const priorFormal = makeOpinion(10, { + login: "loopx-agent", + state: "CHANGES_REQUESTED", + head: HEAD, + valid: true, + verdict: "REQUEST_CHANGES", + family: "gpt", + reviewBodyValid: true, + }); + const unknownWrapper = makeOpinion(12, { + login: "loopx-agent", + state: "COMMENTED", + head: HEAD, + commentProvenance: "unknown", + }); + for (const ordered of [[priorFormal, unknownWrapper], [unknownWrapper, priorFormal]]) { + const result = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + include_independent_coverage: true, + reviews: ordered, + }); + assert.equal((result.independent_review as {review_id: number}).review_id, 10); + assert.equal((result.independent_review as {source_complete: boolean}).source_complete, true); + } +}); + +test("malformed or contradictory comment_provenance fails closed", () => { + const malformed = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + reviews: [ + makeOpinion(1, {login: "contributor", state: "COMMENTED", head: HEAD, commentProvenance: "bogus"}), + ], + }); + assert.equal(malformed.independent_review, undefined); + + const contradictory = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + reviews: [ + makeOpinion(1, { + login: "contributor", + state: "COMMENTED", + head: HEAD, + commentProvenance: "inline_root", + threadReplyOnly: true, + }), + ], + }); + assert.equal(contradictory.independent_review, undefined); +}); + +test("later OLD-head reply_only wrapper retains current-head formal opinion while inline_root and newer unknown retire it", () => { + const headFormal = makeOpinion(10, { + login: "peer", + state: "APPROVED", + head: HEAD, + valid: true, + verdict: "APPROVE", + family: "gpt", + reviewBodyValid: true, + }); + + const oldReplyOnly = makeOpinion(11, { + login: "peer", + state: "COMMENTED", + head: OLD, + commentProvenance: "reply_only", + }); + for (const ordered of [[headFormal, oldReplyOnly], [oldReplyOnly, headFormal]]) { + const result = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + include_independent_coverage: true, + reviews: ordered, + }); + assert.equal((result.independent_review as {review_id: number}).review_id, 10); + assert.equal((result.independent_review as {source_complete: boolean}).source_complete, true); + assert.deepEqual(result.independent_coverage_review_ids, [10]); + assert.deepEqual(result.independent_review_activity_ids, [10]); + } + + for (const provenance of ["inline_root", "unknown"] as const) { + const oldDisplacement = makeOpinion(11, { + login: "peer", + state: "COMMENTED", + head: OLD, + commentProvenance: provenance, + }); + for (const ordered of [[headFormal, oldDisplacement], [oldDisplacement, headFormal]]) { + const result = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + include_independent_coverage: true, + reviews: ordered, + }); + assert.equal(result.independent_review, undefined); + assert.deepEqual(result.independent_coverage_review_ids, []); + } + } + + const earlierOldUnknown = makeOpinion(9, { + login: "peer", + state: "COMMENTED", + head: OLD, + commentProvenance: "unknown", + }); + for (const ordered of [[earlierOldUnknown, headFormal], [headFormal, earlierOldUnknown]]) { + const result = selectPrReviewConclusion({ + author: "cocolord", + head: HEAD, + reviews_complete: true, + include_independent_coverage: true, + reviews: ordered, + }); + assert.equal((result.independent_review as {review_id: number}).review_id, 10); + assert.equal((result.independent_review as {source_complete: boolean}).source_complete, true); + assert.deepEqual(result.independent_coverage_review_ids, [10]); + } +}); diff --git a/tsconfig.control-plane.json b/tsconfig.control-plane.json index 45cf9059b5..2b0d425d2f 100644 --- a/tsconfig.control-plane.json +++ b/tsconfig.control-plane.json @@ -132,6 +132,7 @@ "tests/control_plane_ts/direction_baseline.test.ts", "tests/control_plane_ts/material_wave_ranking.test.ts", "tests/control_plane_ts/session_quota_fabric.test.ts", + "tests/control_plane_ts/pr_review_approval_closeout.test.ts", "tests/control_plane_ts/zcode*.test.ts" ] }