Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(review_hog): add a pr_status lookup so agents know when a request is done (#114909)

Julian Bezf6537cd57bf3
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index 34755514b3eb..009fe5b5fbc5 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -23,6 +23,7 @@ from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.pr_status import PRStatus, PRStatusLookup, ReviewPRState, ReviewRequestOutcomeStatus
from products.review_hog.backend.preferences import UrgencyThreshold
from products.review_hog.backend.requested_reviews import (
RUN_MODE_FLASH,
@@ -386,7 +387,9 @@ class ReviewTriggerResponseSerializer(serializers.Serializer):
)
requested_at = serializers.DateTimeField(help_text="Server time when the request was accepted.")
resolve_will_run = serializers.BooleanField(
- help_text="Whether this request runs the resolution stage, which can push fix commits to the pull request."
+ help_text="Whether this request plans to run the resolution stage, which can push fix commits to the pull "
+ "request. It is the plan at request time: a request queued behind a running turn on the same head can be "
+ "skipped as already published. `review-hog-reviews-pr-status` reports what actually ran."
)
resolve_skip_reason = serializers.ChoiceField(
choices=ResolveSkipReason.choices,
@@ -408,6 +411,91 @@ class ReviewTriggerErrorSerializer(serializers.Serializer):
)
+class ReviewPRStatusParamsSerializer(serializers.Serializer):
+ pr_url = serializers.CharField(
+ help_text="GitHub pull request URL to look up, e.g. 'https://github.com/PostHog/posthog/pull/123'.",
+ )
+ requested_at = serializers.DateTimeField(
+ required=False,
+ help_text="The `requested_at` the trigger returned. When set, the response carries `request_outcome` "
+ "for that request.",
+ )
+ run_mode = serializers.ChoiceField(
+ required=False,
+ default=ReviewTriggerRequestRunMode.REVIEW,
+ choices=ReviewTriggerRequestRunMode.choices,
+ help_text="The `run_mode` the trigger was called with (default 'review'). Only used with `requested_at`.",
+ )
+
+
+class ReviewPRStatusLatestReviewSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="The review's id, for `review-hog-reviews-get`.")
+ review_mode = serializers.ChoiceField(
+ choices=ReviewTriggerReviewMode.choices,
+ allow_null=True,
+ help_text="What the turn ran: 'full' (Deep) or 'flash' (Standard). Null when the turn did not record it.",
+ )
+ head_sha = serializers.CharField(allow_null=True, help_text="The PR head commit the turn reviewed.")
+ run_index = serializers.IntegerField(help_text="The turn's index, for `review-hog-reviews-get`.")
+ completed_at = serializers.DateTimeField(allow_null=True, help_text="When the turn completed.")
+ must_fix_count = serializers.IntegerField(help_text="The turn's valid findings at must_fix priority.")
+ should_fix_count = serializers.IntegerField(help_text="The turn's valid findings at should_fix priority.")
+ consider_count = serializers.IntegerField(help_text="The turn's valid findings at consider priority.")
+ turn_published = serializers.BooleanField(help_text="Whether the turn was published to GitHub.")
+ status_comment_url = serializers.CharField(
+ allow_null=True, help_text="Link to the review's status comment on the pull request; null when there is none."
+ )
+
+
+class ReviewPRStatusRequestOutcomeSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=ReviewRequestOutcomeStatus.choices,
+ help_text="How the request ended: 'pending' while a run for it is queued or running, 'completed' when a "
+ "turn of the requested mode or deeper finished after `requested_at` (Deep covers Standard), 'skipped' "
+ "when the run ended without doing the work, 'failed' when the run died or no run answered the request, "
+ "'unknown' when the run state could not be read (retry later).",
+ )
+ reason = serializers.CharField(
+ allow_null=True,
+ help_text="Why it was skipped or failed: 'flash_after_full' (Standard dropped after a Deep review), "
+ "'review_failed', 'stopped' (Resolve died partway), 'no_matching_run' (nothing ran for the request and "
+ "nothing is queued, for example when the queue replaced it), or a Resolve skip reason such as "
+ "'pr_not_open', 'resolution_not_opted_in', 'no_unresolved_threads', 'pr_in_merge_queue'. Null otherwise.",
+ )
+ review_id = serializers.UUIDField(
+ allow_null=True, help_text="The review to read with `review-hog-reviews-get`; null before the PR has one."
+ )
+ run_index = serializers.IntegerField(
+ allow_null=True,
+ help_text="The review turn that answered or failed the request, for `review-hog-reviews-get`. Null for "
+ "'resolve_only' and while pending.",
+ )
+
+
+class ReviewPRStatusSerializer(serializers.Serializer):
+ repository = serializers.CharField(help_text="The pull request's repository as 'owner/repo'.")
+ pr_number = serializers.IntegerField(help_text="The pull request number.")
+ report_id = serializers.UUIDField(
+ allow_null=True, help_text="The PR's review id, for `review-hog-reviews-get`; null before its first run."
+ )
+ state = serializers.ChoiceField(
+ choices=ReviewPRState.choices,
+ help_text="Where the PR stands now: 'not_reviewed' (no completed review and nothing queued), 'queued' "
+ "(a run is queued or starting), 'reviewing' (a review turn is running), 'resolving' (Resolve is "
+ "running), 'idle' (nothing running), 'unknown' (the run state could not be read, retry later).",
+ )
+ latest_review = ReviewPRStatusLatestReviewSerializer(
+ allow_null=True, help_text="The latest completed review turn; null before the first one completes."
+ )
+ latest_resolution = ReviewLatestResolutionSerializer(
+ allow_null=True,
+ help_text="The latest Resolve run, finished ones too; null when no Resolve run has queued threads.",
+ )
+ request_outcome = ReviewPRStatusRequestOutcomeSerializer(
+ allow_null=True, help_text="How the request at `requested_at` ended; null without `requested_at`."
+ )
+
+
class ReviewFindingLineRangeSerializer(serializers.Serializer):
start = serializers.IntegerField(help_text="First affected line.")
end = serializers.IntegerField(allow_null=True, help_text="Last affected line; null for a single line.")
@@ -565,6 +653,40 @@ def _latest_resolution_payload(summary: ResolutionSummary | None) -> dict[str, A
}
+def _pr_status_payload(pr_status: PRStatus) -> dict[str, Any]:
+ latest = pr_status.latest_review
+ outcome = pr_status.request_outcome
+ return {
+ "repository": pr_status.repository,
+ "pr_number": pr_status.pr_number,
+ "report_id": pr_status.report_id,
+ "state": pr_status.state,
+ "latest_review": {
+ "id": latest.review_id,
+ "review_mode": latest.review_mode,
+ "head_sha": latest.head_sha,
+ "run_index": latest.run_index,
+ "completed_at": latest.completed_at,
+ "must_fix_count": latest.must_fix_count,
+ "should_fix_count": latest.should_fix_count,
+ "consider_count": latest.consider_count,
+ "turn_published": latest.turn_published,
+ "status_comment_url": latest.status_comment_url,
+ }
+ if latest is not None
+ else None,
+ "latest_resolution": _latest_resolution_payload(pr_status.latest_resolution),
+ "request_outcome": {
+ "status": outcome.status,
+ "reason": outcome.reason,
+ "review_id": outcome.review_id,
+ "run_index": outcome.run_index,
+ }
+ if outcome is not None
+ else None,
+ }
+
+
def _finding_payload(finding: ReviewIssueFinding, verdict: ValidationVerdict) -> dict[str, Any]:
return {
"title": finding.title,
@@ -961,6 +1083,38 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
else status.HTTP_202_ACCEPTED,
)
+ @extend_schema(
+ parameters=[ReviewPRStatusParamsSerializer],
+ responses={
+ 200: OpenApiResponse(response=ReviewPRStatusSerializer, description="The pull request's review status."),
+ 400: OpenApiResponse(description="Not a GitHub pull request URL, or an invalid parameter."),
+ },
+ summary="Look up a pull request's review status",
+ description="Where a pull request's ReviewHog runs stand: `state`, the latest completed review turn, and "
+ "the latest Resolve run. Works for any pull request on the project, also ones the caller did not "
+ "trigger. Pass the trigger's `requested_at` and `run_mode` to get `request_outcome`, which says when "
+ "that request is done.",
+ )
+ @action(methods=["GET"], detail=False, required_scopes=["review_hog:read"])
+ def pr_status(self, request: Request, **kwargs) -> Response:
+ team_id = resolve_effective_team_id(self.team_id)
+ params = ReviewPRStatusParamsSerializer(data=request.query_params)
+ params.is_valid(raise_exception=True)
+ try:
+ pr_info = PRParser().parse_github_pr_url(params.validated_data["pr_url"])
+ except ValueError:
+ return Response(
+ {
+ "error": "That doesn't look like a GitHub pull request URL (expected https://github.com/OWNER/REPO/pull/NUMBER)"
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ lookup = PRStatusLookup(
+ team_id, owner=str(pr_info["owner"]), repo=str(pr_info["repo"]), pr_number=int(pr_info["pr_number"])
+ )
+ pr_status = lookup.status(params.validated_data.get("requested_at"), params.validated_data["run_mode"])
+ return Response(ReviewPRStatusSerializer(_pr_status_payload(pr_status)).data)
+
@extend_schema(
parameters=[ReviewDetailParamsSerializer],
responses={
diff --git a/products/review_hog/backend/pr_status.py b/products/review_hog/backend/pr_status.py
new file mode 100644
index 000000000000..13a01456a461
--- /dev/null
+++ b/products/review_hog/backend/pr_status.py
@@ -0,0 +1,314 @@
+"""Where a pull request's ReviewHog runs stand, and how one trigger request ended.
+
+Agents poll this after `review-hog-reviews-trigger`. The database answers first: in-flight turns,
+resolution runs, completed turns (`turn_marker` rows) and the run outcome notes of failed or
+skipped runs. Temporal is asked only to tell `queued` from `idle` when the database shows nothing
+running, and a failed probe reads as `unknown`, never `idle`.
+"""
+
+from datetime import datetime, timedelta
+
+from django.db import models
+
+from posthog.dataclasses import frozen
+
+from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.requested_reviews import RUN_MODE_FLASH, RUN_MODE_RESOLVE_ONLY
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL, effective_priority
+from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
+from products.review_hog.backend.reviewer.persistence import load_findings_bundle
+from products.review_hog.backend.reviewer.progress import (
+ RESOLUTION_COMPLETED,
+ RESOLUTION_RESOLVING,
+ RESOLUTION_STOPPED,
+ RUN_OUTCOME_FAILED,
+ RUN_STAGE_RESOLUTION,
+ RUN_STAGE_REVIEW,
+ ResolutionSummary,
+ RunOutcomeMarker,
+ in_progress_report_ids,
+ latest_resolution_summaries,
+ resolution_states,
+ run_outcome_markers,
+ turn_markers,
+)
+from products.review_hog.backend.temporal.client import WorkflowProbe, probe_workflow
+from products.review_hog.backend.temporal.types import resolve_pr_workflow_id, review_pr_workflow_id
+
+
+class ReviewPRState(models.TextChoices):
+ NOT_REVIEWED = "not_reviewed", "Not reviewed"
+ QUEUED = "queued", "Queued"
+ REVIEWING = "reviewing", "Reviewing"
+ RESOLVING = "resolving", "Resolving"
+ IDLE = "idle", "Idle"
+ UNKNOWN = "unknown", "Unknown"
+
+
+class ReviewRequestOutcomeStatus(models.TextChoices):
+ PENDING = "pending", "Pending"
+ COMPLETED = "completed", "Completed"
+ SKIPPED = "skipped", "Skipped"
+ FAILED = "failed", "Failed"
+ UNKNOWN = "unknown", "Unknown"
+
+
+NO_MATCHING_RUN_REASON = "no_matching_run"
+STOPPED_REASON = "stopped"
+
+_RUNNING_STATES = (ReviewPRState.QUEUED, ReviewPRState.REVIEWING, ReviewPRState.RESOLVING)
+# Agents poll this endpoint, so a slow Temporal answer must not hold the request open.
+_PROBE_RPC_TIMEOUT = timedelta(seconds=2)
+
+
+@frozen
+class LatestReview:
+ review_id: str
+ review_mode: str | None
+ head_sha: str | None
+ run_index: int
+ completed_at: datetime | None
+ must_fix_count: int
+ should_fix_count: int
+ consider_count: int
+ turn_published: bool
+ status_comment_url: str | None
+
+
+@frozen
+class RequestOutcome:
+ status: ReviewRequestOutcomeStatus
+ reason: str | None = None
+ review_id: str | None = None
+ run_index: int | None = None
+
+
+@frozen
+class PRStatus:
+ repository: str
+ pr_number: int
+ report_id: str | None
+ state: ReviewPRState
+ latest_review: LatestReview | None
+ latest_resolution: ResolutionSummary | None
+ request_outcome: RequestOutcome | None
+
+
+def _covers(turn_mode: str, requested_mode: str) -> bool:
+ """A Deep turn answers a Standard request too, because no Standard review runs after a Deep one."""
+ return turn_mode == requested_mode or turn_mode == REVIEW_MODE_FULL
+
+
+def _resolution_answers(resolution: ResolutionSummary, requested_at: datetime) -> bool:
+ """Whether this resolution run can be the one the request started or joined.
+
+ A `resolve_only` request joins a resolution that already runs, so a run that started earlier
+ answers it while it still runs, or when it completed at or after the request.
+ """
+ if resolution.started_at >= requested_at or resolution.status == RESOLUTION_RESOLVING:
+ return True
+ return resolution.completed_at is not None and resolution.completed_at >= requested_at
+
+
+class PRStatusLookup:
+ """One pull request's status on the root team, read in one pass."""
+
+ def __init__(self, team_id: int, owner: str, repo: str, pr_number: int) -> None:
+ self.team_id = team_id
+ self.owner = owner
+ self.repo = repo
+ self.pr_number = pr_number
+ self.repository = f"{owner}/{repo}"
+ # Repository casing can differ per trigger, so match it the way the trigger does.
+ self.report = (
+ ReviewReport.objects.for_team(team_id, canonical=True)
+ .filter(repository__iexact=self.repository, pr_number=pr_number)
+ .first()
+ )
+ self.report_id = str(self.report.id) if self.report is not None else None
+
+ def _probe(self) -> WorkflowProbe:
+ review = probe_workflow(
+ review_pr_workflow_id(team_id=self.team_id, owner=self.owner, repo=self.repo, pr_number=self.pr_number),
+ rpc_timeout=_PROBE_RPC_TIMEOUT,
+ )
+ if review == WorkflowProbe.RUNNING:
+ return review
+ resolve = probe_workflow(
+ resolve_pr_workflow_id(team_id=self.team_id, owner=self.owner, repo=self.repo, pr_number=self.pr_number),
+ rpc_timeout=_PROBE_RPC_TIMEOUT,
+ )
+ if resolve == WorkflowProbe.RUNNING:
+ return resolve
+ if WorkflowProbe.UNKNOWN in (review, resolve):
+ return WorkflowProbe.UNKNOWN
+ return WorkflowProbe.NOT_RUNNING
+
+ def _state(self) -> ReviewPRState:
+ report = self.report
+ if report is not None and self.report_id is not None:
+ live_resolution = resolution_states(self.team_id, [report]).get(self.report_id)
+ if live_resolution is not None and live_resolution.status == RESOLUTION_RESOLVING:
+ return ReviewPRState.RESOLVING
+ if self.report_id in in_progress_report_ids(self.team_id, [report]):
+ return ReviewPRState.REVIEWING
+ probe = self._probe()
+ if probe == WorkflowProbe.RUNNING:
+ return ReviewPRState.QUEUED
+ if probe == WorkflowProbe.UNKNOWN:
+ return ReviewPRState.UNKNOWN
+ if report is None or report.run_count == 0:
+ return ReviewPRState.NOT_REVIEWED
+ return ReviewPRState.IDLE
+
+ def _latest_review(self) -> LatestReview | None:
+ report = self.report
+ if report is None or self.report_id is None or report.run_count == 0:
+ return None
+ report_id = self.report_id
+ pairs = load_findings_bundle(team_id=self.team_id, report_ids=[report_id]).turn(report_id, report.run_count)
+ counts = dict.fromkeys(IssuePriority, 0)
+ for finding, verdict in pairs:
+ if verdict is not None and verdict.is_valid:
+ counts[effective_priority(finding.priority, verdict.adjusted_priority)] += 1
+ marker = turn_markers(self.team_id, [report_id]).get((report_id, report.run_count))
+ return LatestReview(
+ review_id=report_id,
+ review_mode=marker.review_mode if marker else None,
+ head_sha=report.completed_head_sha or report.head_sha,
+ run_index=report.run_count,
+ completed_at=report.last_run_at,
+ must_fix_count=counts[IssuePriority.MUST_FIX],
+ should_fix_count=counts[IssuePriority.SHOULD_FIX],
+ consider_count=counts[IssuePriority.CONSIDER],
+ turn_published=str(report.run_count) in (report.published_head_shas or {}),
+ status_comment_url=f"{report.pr_url}#issuecomment-{report.status_comment_id}"
+ if report.pr_url and report.status_comment_id
+ else None,
+ )
+
+ def _completed_turn(self, requested_at: datetime, requested_mode: str) -> int | None:
+ """The newest completed turn that answers the request, if any."""
+ report = self.report
+ if report is None or self.report_id is None:
+ return None
+ markers = turn_markers(self.team_id, [self.report_id])
+ for run_index in range(report.run_count, 0, -1):
+ marker = markers.get((self.report_id, run_index))
+ if marker is None or not _covers(marker.review_mode, requested_mode):
+ continue
+ # The latest turn's finish time is `last_run_at`. Older turns store no finish time, but a
+ # turn whose marker was written after the request also finished after it.
+ if run_index == report.run_count and report.last_run_at is not None:
+ finished_after_request = report.last_run_at >= requested_at
+ else:
+ finished_after_request = marker.started_at >= requested_at
+ if finished_after_request:
+ return run_index
+ return None
+
+ def _ended_outcome(self, marker: RunOutcomeMarker, state: ReviewPRState) -> RequestOutcome:
+ """A failed or skipped run ends the request only when nothing runs, because the queue can retry it."""
+ if state in _RUNNING_STATES:
+ return RequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)
+ if state == ReviewPRState.UNKNOWN:
+ return RequestOutcome(status=ReviewRequestOutcomeStatus.UNKNOWN, review_id=self.report_id)
+ return RequestOutcome(
+ status=ReviewRequestOutcomeStatus(marker.outcome),
+ reason=marker.reason,
+ review_id=self.report_id,
+ run_index=marker.run_index,
+ )
+
+ def _review_outcome(
+ self, requested_at: datetime, requested_mode: str, state: ReviewPRState
+ ) -> RequestOutcome | None:
+ if self.report is None or self.report_id is None:
+ return None
+ review_markers = [
+ marker
+ for marker in run_outcome_markers(self.team_id, [self.report_id], since=requested_at)[self.report_id]
+ if marker.stage == RUN_STAGE_REVIEW
+ ]
+ run_index = self._completed_turn(requested_at, requested_mode)
+ if run_index is not None:
+ # Finalize counts the turn before it publishes, so a publish failure marks the same turn failed.
+ turn_failed = [
+ marker
+ for marker in review_markers
+ if marker.outcome == RUN_OUTCOME_FAILED and marker.run_index == run_index
+ ]
+ if turn_failed:
+ return self._ended_outcome(turn_failed[-1], state)
+ if run_index == self.report.run_count and state == ReviewPRState.REVIEWING:
+ return RequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)
+ return RequestOutcome(
+ status=ReviewRequestOutcomeStatus.COMPLETED, review_id=self.report_id, run_index=run_index
+ )
+ ended = [marker for marker in review_markers if marker.review_mode == requested_mode]
+ if not ended:
+ return None
+ return self._ended_outcome(ended[-1], state)
+
+ def _resolve_outcome(
+ self, requested_at: datetime, resolution: ResolutionSummary | None, state: ReviewPRState
+ ) -> RequestOutcome | None:
+ if self.report_id is None:
+ return None
+ if resolution is not None and _resolution_answers(resolution, requested_at):
+ if resolution.status == RESOLUTION_COMPLETED:
+ return RequestOutcome(status=ReviewRequestOutcomeStatus.COMPLETED, review_id=self.report_id)
+ if resolution.status == RESOLUTION_STOPPED:
+ # A run can go quiet in the database while its workflow still works through threads.
+ if state in _RUNNING_STATES:
+ return RequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)
+ if state == ReviewPRState.UNKNOWN:
+ return RequestOutcome(status=ReviewRequestOutcomeStatus.UNKNOWN, review_id=self.report_id)
+ return RequestOutcome(
+ status=ReviewRequestOutcomeStatus.FAILED, reason=STOPPED_REASON, review_id=self.report_id
+ )
+ return RequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)
+ skipped = [
+ marker
+ for marker in run_outcome_markers(self.team_id, [self.report_id], since=requested_at)[self.report_id]
+ if marker.stage == RUN_STAGE_RESOLUTION
+ ]
+ if not skipped:
+ return None
+ return self._ended_outcome(skipped[-1], state)
+
+ def _unmatched_outcome(self, state: ReviewPRState) -> RequestOutcome:
+ """No run answered the request yet: wait while anything runs, else the queue dropped or replaced it."""
+ if state in _RUNNING_STATES:
+ return RequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)
+ if state == ReviewPRState.UNKNOWN:
+ return RequestOutcome(status=ReviewRequestOutcomeStatus.UNKNOWN, review_id=self.report_id)
+ return RequestOutcome(
+ status=ReviewRequestOutcomeStatus.FAILED, reason=NO_MATCHING_RUN_REASON, review_id=self.report_id
+ )
+
+ def status(self, requested_at: datetime | None, run_mode: str) -> PRStatus:
+ state = self._state()
+ resolution = (
+ latest_resolution_summaries(self.team_id, [self.report]).get(self.report_id)
+ if self.report is not None and self.report_id is not None
+ else None
+ )
+ request_outcome: RequestOutcome | None = None
+ if requested_at is not None:
+ if run_mode == RUN_MODE_RESOLVE_ONLY:
+ request_outcome = self._resolve_outcome(requested_at, resolution, state)
+ else:
+ requested_mode = REVIEW_MODE_FLASH if run_mode == RUN_MODE_FLASH else REVIEW_MODE_FULL
+ request_outcome = self._review_outcome(requested_at, requested_mode, state)
+ if request_outcome is None:
+ request_outcome = self._unmatched_outcome(state)
+ return PRStatus(
+ repository=self.report.repository if self.report is not None else self.repository,
+ pr_number=self.pr_number,
+ report_id=self.report_id,
+ state=state,
+ latest_review=self._latest_review(),
+ latest_resolution=resolution,
+ request_outcome=request_outcome,
+ )
diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.py
index 19e88ed27da7..d82c826b870f 100644
--- a/products/review_hog/backend/reviewer/progress.py
+++ b/products/review_hog/backend/reviewer/progress.py
@@ -262,6 +262,8 @@ class TurnMarker:
review_mode: str
head_sha: str | None
+ # When the marker row was written, which is just before the turn's review sessions start.
+ started_at: datetime
def turn_markers(team_id: int, report_ids: list[str]) -> dict[tuple[str, int], TurnMarker]:
@@ -277,14 +279,14 @@ def turn_markers(team_id: int, report_ids: list[str]) -> dict[tuple[str, int], T
marker_review_mode=KeyTextTransform("review_mode", _content_json()),
)
.order_by("created_at", "id")
- .values("report_id", "head_sha", "marker_run_index", "marker_review_mode")
+ .values("report_id", "head_sha", "marker_run_index", "marker_review_mode", "created_at")
)
markers: dict[tuple[str, int], TurnMarker] = {}
for row in rows:
if row["marker_run_index"] is None or row["marker_review_mode"] is None:
continue
markers[(str(row["report_id"]), int(row["marker_run_index"]))] = TurnMarker(
- review_mode=row["marker_review_mode"], head_sha=row["head_sha"]
+ review_mode=row["marker_review_mode"], head_sha=row["head_sha"], started_at=row["created_at"]
)
return markers
diff --git a/products/review_hog/backend/temporal/client.py b/products/review_hog/backend/temporal/client.py
index 01eb2f81b4fb..0a0f963813f9 100644
--- a/products/review_hog/backend/temporal/client.py
+++ b/products/review_hog/backend/temporal/client.py
@@ -27,6 +27,8 @@ targets a PR (`pr_url`), validated in `_build_resolution_inputs`.
import asyncio
import logging
from collections.abc import Callable
+from datetime import timedelta
+from enum import StrEnum
from typing import Any, cast
from django.conf import settings
@@ -58,6 +60,34 @@ logger = logging.getLogger(__name__)
_RESOLUTION_RETRY = RetryPolicy(maximum_attempts=2)
+class WorkflowProbe(StrEnum):
+ RUNNING = "running"
+ NOT_RUNNING = "not_running"
+ UNKNOWN = "unknown"
+
+
+def probe_workflow(workflow_id: str, rpc_timeout: timedelta | None = None) -> WorkflowProbe:
+ """Whether `workflow_id` has a live execution, with probe errors kept apart as UNKNOWN.
+
+ A status reader must not report a PR as idle when Temporal did not answer. A missed
+ `rpc_timeout` deadline reads as UNKNOWN too.
+ """
+ try:
+ client = sync_connect()
+ description = async_to_sync(client.get_workflow_handle(workflow_id).describe)(rpc_timeout=rpc_timeout)
+ except RPCError as e:
+ if e.status == RPCStatusCode.NOT_FOUND:
+ return WorkflowProbe.NOT_RUNNING
+ logger.warning("Workflow describe failed for %s: %s", workflow_id, e)
+ return WorkflowProbe.UNKNOWN
+ except Exception:
+ logger.exception("Workflow describe failed for %s", workflow_id)
+ return WorkflowProbe.UNKNOWN
+ if description.status == WorkflowExecutionStatus.RUNNING:
+ return WorkflowProbe.RUNNING
+ return WorkflowProbe.NOT_RUNNING
+
+
def workflow_running(workflow_id: str) -> bool:
"""Whether `workflow_id` has a live execution — the busy-guard's probe (CONTEXT.md — "Busy-guard").
@@ -67,18 +97,7 @@ def workflow_running(workflow_id: str) -> bool:
trigger must not 500 over a flaky describe, and a real Temporal outage still surfaces on the
start call itself.
"""
- try:
- client = sync_connect()
- description = async_to_sync(client.get_workflow_handle(workflow_id).describe)()
- except RPCError as e:
- if e.status == RPCStatusCode.NOT_FOUND:
- return False
- logger.warning("Busy-guard describe failed for %s: %s", workflow_id, e)
- return False
- except Exception:
- logger.exception("Busy-guard describe failed for %s", workflow_id)
- return False
- return description.status == WorkflowExecutionStatus.RUNNING
+ return probe_workflow(workflow_id) == WorkflowProbe.RUNNING
def _build_inputs(
diff --git a/products/review_hog/backend/tests/test_pr_status_api.py b/products/review_hog/backend/tests/test_pr_status_api.py
new file mode 100644
index 000000000000..bd879a308f66
--- /dev/null
+++ b/products/review_hog/backend/tests/test_pr_status_api.py
@@ -0,0 +1,372 @@
+from datetime import UTC, datetime, timedelta
+
+import time_machine
+from posthog.test.base import APIBaseTest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+from temporalio.service import RPCError, RPCStatusCode
+
+from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
+from products.review_hog.backend.reviewer.artefact_content import (
+ ResolutionRunArtefact,
+ ReviewIssueFinding,
+ TurnMarkerArtefact,
+ ValidationVerdict,
+)
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
+from products.review_hog.backend.reviewer.models.issues_review import IssuePriority, LineRange
+from products.review_hog.backend.reviewer.progress import RESOLUTION_RUN_NOTE_AUTHOR, record_run_outcome
+from products.review_hog.backend.temporal.client import WorkflowProbe
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.artefact_schemas import NoteArtefact
+
+PR_URL = "https://github.com/PostHog/posthog/pull/5"
+REQUESTED_AT = datetime(2026, 7, 1, 12, 0, tzinfo=UTC)
+BEFORE = REQUESTED_AT - timedelta(hours=1)
+AFTER = REQUESTED_AT + timedelta(minutes=2)
+_PROBE = "products.review_hog.backend.pr_status.probe_workflow"
+
+
+class TestPRStatusAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(patch("posthoganalytics.feature_enabled", return_value=True))
+ self.url = f"/api/projects/{self.team.id}/review_hog/reviews/pr_status/"
+ # Staleness checks read the clock, so pin it a few minutes after the request.
+ self.enterContext(time_machine.travel(REQUESTED_AT + timedelta(minutes=5), tick=False))
+
+ def _report(self, *, run_count: int = 1, last_run_at: datetime | None = BEFORE, **kwargs) -> ReviewReport:
+ # Stored with other casing than the URL, because triggers store whatever casing they carried.
+ return ReviewReport.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ repository="posthog/PostHog",
+ pr_number=5,
+ pr_url=PR_URL,
+ head_branch="feat",
+ base_branch="main",
+ run_count=run_count,
+ last_run_at=last_run_at,
+ completed_head_sha="sha1" if run_count else None,
+ status=kwargs.pop("status", ReviewReport.Status.IDLE),
+ **kwargs,
+ )
+
+ def _turn(self, report: ReviewReport, run_index: int, review_mode: str, *, at: datetime) -> None:
+ with time_machine.travel(at, tick=False):
+ ReviewReportArtefact.add_turn_marker(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=TurnMarkerArtefact(
+ head_sha="sha1",
+ run_index=run_index,
+ review_mode=review_mode,
+ reviewhog_version="v",
+ reviewhog_fingerprint="f",
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ def _get(self, probe: WorkflowProbe, **params: str) -> tuple[dict, MagicMock]:
+ with patch(_PROBE, return_value=probe) as mock_probe:
+ res = self.client.get(self.url, {"pr_url": PR_URL, **params})
+ assert res.status_code == 200, res.json()
+ return res.json(), mock_probe
+
+ def _deep_turn_after_request(self) -> None:
+ report = self._report(last_run_at=AFTER + timedelta(minutes=1))
+ self._turn(report, 1, REVIEW_MODE_FULL, at=AFTER)
+
+ def _deep_turn_before_then_standard_dropped(self) -> None:
+ report = self._report()
+ self._turn(report, 1, REVIEW_MODE_FULL, at=BEFORE - timedelta(minutes=5))
+ with time_machine.travel(AFTER, tick=False):
+ record_run_outcome(
+ self.team.id,
+ str(report.id),
+ stage="review",
+ outcome="skipped",
+ reason="flash_after_full",
+ run_index=2,
+ review_mode=REVIEW_MODE_FLASH,
+ )
+
+ def _failed_first_turn(self) -> None:
+ report = self._report(run_count=0, last_run_at=None)
+ with time_machine.travel(AFTER, tick=False):
+ record_run_outcome(
+ self.team.id,
+ str(report.id),
+ stage="review",
+ outcome="failed",
+ reason="review_failed",
+ run_index=1,
+ review_mode=REVIEW_MODE_FULL,
+ )
+
+ def _deep_turn_before_request(self) -> None:
+ report = self._report()
+ self._turn(report, 1, REVIEW_MODE_FULL, at=BEFORE - timedelta(minutes=5))
+
+ def _completed_resolution_after_request(self) -> None:
+ report = self._report()
+ with time_machine.travel(AFTER, tick=False):
+ ReviewReportArtefact.append_resolution_run(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=ResolutionRunArtefact(total=1, thread_ids=["PRRT_1"]),
+ attribution=ArtefactAttribution.system(),
+ )
+ with time_machine.travel(AFTER + timedelta(minutes=1), tick=False):
+ ReviewReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=NoteArtefact(note="Resolution run on PR #5: done", author=RESOLUTION_RUN_NOTE_AUTHOR),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ def _deep_turn_publishing(self) -> None:
+ # Finalize already counted the turn, but the report stays ACTIVE until the publish lands.
+ report = self._report(last_run_at=AFTER + timedelta(minutes=1), status=ReviewReport.Status.ACTIVE)
+ self._turn(report, 1, REVIEW_MODE_FULL, at=AFTER)
+
+ def _deep_turn_publish_failed(self) -> None:
+ report = self._report(last_run_at=AFTER + timedelta(minutes=1))
+ self._turn(report, 1, REVIEW_MODE_FULL, at=AFTER)
+ with time_machine.travel(AFTER + timedelta(minutes=2), tick=False):
+ record_run_outcome(
+ self.team.id,
+ str(report.id),
+ stage="review",
+ outcome="failed",
+ reason="review_failed",
+ run_index=1,
+ review_mode=REVIEW_MODE_FULL,
+ )
+
+ def _joined_resolution_completed_after_request(self) -> None:
+ # A resolve_only trigger joins a resolution that started before the request.
+ report = self._report()
+ with time_machine.travel(BEFORE, tick=False):
+ ReviewReportArtefact.append_resolution_run(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=ResolutionRunArtefact(total=1, thread_ids=["PRRT_1"]),
+ attribution=ArtefactAttribution.system(),
+ )
+ with time_machine.travel(AFTER, tick=False):
+ ReviewReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=NoteArtefact(note="Resolution run on PR #5: done", author=RESOLUTION_RUN_NOTE_AUTHOR),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ def _resolution_skipped_after_request(self) -> None:
+ report = self._report()
+ with time_machine.travel(AFTER, tick=False):
+ record_run_outcome(
+ self.team.id, str(report.id), stage="resolution", outcome="skipped", reason="no_unresolved_threads"
+ )
+
+ @parameterized.expand(
+ [
+ ("completed_deep", "_deep_turn_after_request", "review", WorkflowProbe.NOT_RUNNING, ("completed", None, 1)),
+ (
+ "deep_covers_standard",
+ "_deep_turn_after_request",
+ "flash",
+ WorkflowProbe.NOT_RUNNING,
+ ("completed", None, 1),
+ ),
+ (
+ "standard_dropped_after_deep",
+ "_deep_turn_before_then_standard_dropped",
+ "flash",
+ WorkflowProbe.NOT_RUNNING,
+ ("skipped", "flash_after_full", 2),
+ ),
+ ("failed_turn", "_failed_first_turn", "review", WorkflowProbe.NOT_RUNNING, ("failed", "review_failed", 1)),
+ # The queue can retry a failed run, so a failure is final only once nothing runs.
+ ("failed_turn_retrying", "_failed_first_turn", "review", WorkflowProbe.RUNNING, ("pending", None, None)),
+ ("publishing", "_deep_turn_publishing", "review", WorkflowProbe.NOT_RUNNING, ("pending", None, None)),
+ (
+ "publish_failed",
+ "_deep_turn_publish_failed",
+ "review",
+ WorkflowProbe.NOT_RUNNING,
+ ("failed", "review_failed", 1),
+ ),
+ (
+ "nothing_ran_or_queued",
+ "_deep_turn_before_request",
+ "review",
+ WorkflowProbe.NOT_RUNNING,
+ ("failed", "no_matching_run", None),
+ ),
+ ("queued", "_deep_turn_before_request", "review", WorkflowProbe.RUNNING, ("pending", None, None)),
+ # A Temporal error must never read as "nothing runs", or a queued request would read as failed.
+ ("temporal_error", "_deep_turn_before_request", "review", WorkflowProbe.UNKNOWN, ("unknown", None, None)),
+ (
+ "resolve_only_completed",
+ "_completed_resolution_after_request",
+ "resolve_only",
+ WorkflowProbe.NOT_RUNNING,
+ ("completed", None, None),
+ ),
+ (
+ "resolve_only_joined_run_completed",
+ "_joined_resolution_completed_after_request",
+ "resolve_only",
+ WorkflowProbe.NOT_RUNNING,
+ ("completed", None, None),
+ ),
+ (
+ "resolve_only_skipped",
+ "_resolution_skipped_after_request",
+ "resolve_only",
+ WorkflowProbe.NOT_RUNNING,
+ ("skipped", "no_unresolved_threads", None),
+ ),
+ ]
+ )
+ def test_request_outcome(
+ self,
+ _name: str,
+ setup: str,
+ run_mode: str,
+ probe: WorkflowProbe,
+ expected: tuple[str, str | None, int | None],
+ ) -> None:
+ getattr(self, setup)()
+
+ body, _ = self._get(probe, requested_at=REQUESTED_AT.isoformat(), run_mode=run_mode)
+
+ outcome = body["request_outcome"]
+ assert (outcome["status"], outcome["reason"], outcome["run_index"]) == expected
+ assert outcome["review_id"] == body["report_id"]
+
+ @parameterized.expand(
+ [
+ ("workflow_still_running", WorkflowProbe.RUNNING, ("pending", None)),
+ ("workflow_ended", WorkflowProbe.NOT_RUNNING, ("failed", "stopped")),
+ ]
+ )
+ def test_quiet_resolution_waits_for_its_workflow(
+ self, _name: str, probe: WorkflowProbe, expected: tuple[str, str | None]
+ ) -> None:
+ # A resolution run that wrote nothing for a while reads as stopped in the database.
+ started = timezone.now() - timedelta(hours=2)
+ with time_machine.travel(started, tick=False):
+ report = self._report()
+ ReviewReportArtefact.append_resolution_run(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=ResolutionRunArtefact(total=1, thread_ids=["PRRT_1"]),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ body, _ = self._get(probe, requested_at=(started - timedelta(minutes=1)).isoformat(), run_mode="resolve_only")
+
+ assert (body["request_outcome"]["status"], body["request_outcome"]["reason"]) == expected
+
+ @parameterized.expand(
+ [
+ ("no_report", None, WorkflowProbe.NOT_RUNNING, "not_reviewed", True),
+ ("completed_review", ReviewReport.Status.IDLE, WorkflowProbe.NOT_RUNNING, "idle", True),
+ ("queued", ReviewReport.Status.IDLE, WorkflowProbe.RUNNING, "queued", True),
+ ("temporal_error", ReviewReport.Status.IDLE, WorkflowProbe.UNKNOWN, "unknown", True),
+ # The database already shows a running turn, so Temporal is not asked.
+ ("running_turn", ReviewReport.Status.ACTIVE, WorkflowProbe.UNKNOWN, "reviewing", False),
+ ]
+ )
+ def test_state(
+ self, _name: str, report_status: str | None, probe: WorkflowProbe, expected: str, probed: bool
+ ) -> None:
+ if report_status is not None:
+ self._report(status=report_status)
+
+ body, mock_probe = self._get(probe)
+
+ assert body["state"] == expected
+ assert body["request_outcome"] is None
+ assert mock_probe.called is probed
+ if probed:
+ # The probe asks for the root team's workflow, whatever casing the URL carries.
+ assert mock_probe.call_args_list[0].args[0] == f"review-pr:{self.team.id}:posthog/posthog:5"
+
+ def test_probes_temporal_with_a_short_deadline(self) -> None:
+ self._report()
+ handle = MagicMock()
+ handle.describe = AsyncMock(side_effect=RPCError("deadline", RPCStatusCode.DEADLINE_EXCEEDED, b""))
+
+ with patch("products.review_hog.backend.temporal.client.sync_connect") as mock_connect:
+ mock_connect.return_value.get_workflow_handle.return_value = handle
+ res = self.client.get(self.url, {"pr_url": PR_URL})
+
+ assert res.json()["state"] == "unknown"
+ assert [call.kwargs["rpc_timeout"] for call in handle.describe.call_args_list] == [timedelta(seconds=2)] * 2
+
+ def test_resolving_state_and_latest_review(self) -> None:
+ report = self._report(
+ status=ReviewReport.Status.ACTIVE, status_comment_id=77, published_head_shas={"1": "sha1"}
+ )
+ self._turn(report, 1, REVIEW_MODE_FULL, at=BEFORE - timedelta(minutes=5))
+ for key, priority, is_valid in [
+ ("1-a", IssuePriority.MUST_FIX, True),
+ ("1-b", IssuePriority.CONSIDER, True),
+ ("1-c", IssuePriority.MUST_FIX, False),
+ ]:
+ ReviewReportArtefact.append_finding(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=ReviewIssueFinding(
+ issue_key=key,
+ run_index=1,
+ title="t",
+ file="f.py",
+ lines=[LineRange(start=1)],
+ body="b",
+ suggestion="s",
+ priority=priority,
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+ ReviewReportArtefact.append_verdict(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=ValidationVerdict(issue_key=key, is_valid=is_valid, argumentation="a"),
+ attribution=ArtefactAttribution.system(),
+ )
+ ReviewReportArtefact.append_resolution_run(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=ResolutionRunArtefact(total=1, thread_ids=["PRRT_1"]),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ body, mock_probe = self._get(WorkflowProbe.NOT_RUNNING)
+
+ assert body["state"] == "resolving"
+ mock_probe.assert_not_called()
+ assert body["repository"] == "posthog/PostHog"
+ assert body["latest_review"] == {
+ "id": str(report.id),
+ "review_mode": "full",
+ "head_sha": "sha1",
+ "run_index": 1,
+ "completed_at": "2026-07-01T11:00:00Z",
+ "must_fix_count": 1,
+ "should_fix_count": 0,
+ "consider_count": 1,
+ "turn_published": True,
+ "status_comment_url": f"{PR_URL}#issuecomment-77",
+ }
+ assert body["latest_resolution"]["status"] == "resolving"
+
+ def test_rejects_a_url_that_is_not_a_pull_request(self) -> None:
+ res = self.client.get(self.url, {"pr_url": "https://github.com/PostHog/posthog/issues/5"})
+
+ assert res.status_code == 400
diff --git a/products/review_hog/backend/tests/test_repositories_api.py b/products/review_hog/backend/tests/test_repositories_api.py
index 2152bdc764d5..26a0c2c618ae 100644
--- a/products/review_hog/backend/tests/test_repositories_api.py
+++ b/products/review_hog/backend/tests/test_repositories_api.py
@@ -1,5 +1,5 @@
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -19,6 +19,7 @@ from products.review_hog.backend.models import (
ReviewUserRepositoryChoice,
ReviewUserSettings,
)
+from products.review_hog.backend.temporal.client import WorkflowProbe
INSTALLATION = "1001"
WEB = {"installation_id": INSTALLATION, "full_name": "example-org/web", "github_repo_id": 501}
@@ -104,12 +105,13 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):
@parameterized.expand(
[
- ("environment_only", False, (403, 403, 403)),
- ("environment_and_parent", True, (200, 200, 200)),
+ ("environment_only", False, (403, 403, 403, 403)),
+ ("environment_and_parent", True, (200, 200, 200, 200)),
]
)
+ @patch("products.review_hog.backend.pr_status.probe_workflow", return_value=WorkflowProbe.NOT_RUNNING)
def test_a_project_scoped_key_needs_the_parent_project(
- self, _name: str, include_parent: bool, expected: tuple[int, int, int]
+ self, _name: str, include_parent: bool, expected: tuple[int, int, int, int], _probe: MagicMock
) -> None:
environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Staging")
value = generate_random_token_personal()
@@ -126,8 +128,11 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):
read = self.client.get(self._url("repositories/", environment))
write = self.client.post(self._url("repositories/", environment), {**WEB, "selected": True})
reviews = self.client.get(self._url("reviews/", environment))
+ pr_status = self.client.get(
+ self._url("reviews/pr_status/", environment), {"pr_url": "https://github.com/PostHog/posthog/pull/5"}
+ )
- assert (read.status_code, write.status_code, reviews.status_code) == expected
+ assert (read.status_code, write.status_code, reviews.status_code, pr_status.status_code) == expected
def test_project_rule_stores_only_what_differs_and_is_logged(self) -> None:
res = self.client.patch(
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 049a35be7d3c..f226718fa555 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -1117,6 +1117,131 @@ export interface ReviewPerspectiveStatsApi {
perspectives: ReviewPerspectiveStatItemApi[]
}
+/**
+ * * `not_reviewed` - Not reviewed
+ * * `queued` - Queued
+ * * `reviewing` - Reviewing
+ * * `resolving` - Resolving
+ * * `idle` - Idle
+ * * `unknown` - Unknown
+ */
+export type ReviewPRStateEnumApi = (typeof ReviewPRStateEnumApi)[keyof typeof ReviewPRStateEnumApi]
+
+export const ReviewPRStateEnumApi = {
+ NotReviewed: 'not_reviewed',
+ Queued: 'queued',
+ Reviewing: 'reviewing',
+ Resolving: 'resolving',
+ Idle: 'idle',
+ Unknown: 'unknown',
+} as const
+
+export interface ReviewPRStatusLatestReviewApi {
+ /** The review's id, for `review-hog-reviews-get`. */
+ id: string
+ /** What the turn ran: 'full' (Deep) or 'flash' (Standard). Null when the turn did not record it.
+ *
+ * * `full` - Deep
+ * * `flash` - Standard */
+ review_mode: ReviewTriggerReviewModeEnumApi | null
+ /**
+ * The PR head commit the turn reviewed.
+ * @nullable
+ */
+ head_sha: string | null
+ /** The turn's index, for `review-hog-reviews-get`. */
+ run_index: number
+ /**
+ * When the turn completed.
+ * @nullable
+ */
+ completed_at: string | null
+ /** The turn's valid findings at must_fix priority. */
+ must_fix_count: number
+ /** The turn's valid findings at should_fix priority. */
+ should_fix_count: number
+ /** The turn's valid findings at consider priority. */
+ consider_count: number
+ /** Whether the turn was published to GitHub. */
+ turn_published: boolean
+ /**
+ * Link to the review's status comment on the pull request; null when there is none.
+ * @nullable
+ */
+ status_comment_url: string | null
+}
+
+/**
+ * * `pending` - Pending
+ * * `completed` - Completed
+ * * `skipped` - Skipped
+ * * `failed` - Failed
+ * * `unknown` - Unknown
+ */
+export type ReviewRequestOutcomeStatusEnumApi =
+ (typeof ReviewRequestOutcomeStatusEnumApi)[keyof typeof ReviewRequestOutcomeStatusEnumApi]
+
+export const ReviewRequestOutcomeStatusEnumApi = {
+ Pending: 'pending',
+ Completed: 'completed',
+ Skipped: 'skipped',
+ Failed: 'failed',
+ Unknown: 'unknown',
+} as const
+
+export interface ReviewPRStatusRequestOutcomeApi {
+ /** How the request ended: 'pending' while a run for it is queued or running, 'completed' when a turn of the requested mode or deeper finished after `requested_at` (Deep covers Standard), 'skipped' when the run ended without doing the work, 'failed' when the run died or no run answered the request, 'unknown' when the run state could not be read (retry later).
+ *
+ * * `pending` - Pending
+ * * `completed` - Completed
+ * * `skipped` - Skipped
+ * * `failed` - Failed
+ * * `unknown` - Unknown */
+ status: ReviewRequestOutcomeStatusEnumApi
+ /**
+ * Why it was skipped or failed: 'flash_after_full' (Standard dropped after a Deep review), 'review_failed', 'stopped' (Resolve died partway), 'no_matching_run' (nothing ran for the request and nothing is queued, for example when the queue replaced it), or a Resolve skip reason such as 'pr_not_open', 'resolution_not_opted_in', 'no_unresolved_threads', 'pr_in_merge_queue'. Null otherwise.
+ * @nullable
+ */
+ reason: string | null
+ /**
+ * The review to read with `review-hog-reviews-get`; null before the PR has one.
+ * @nullable
+ */
+ review_id: string | null
+ /**
+ * The review turn that answered or failed the request, for `review-hog-reviews-get`. Null for 'resolve_only' and while pending.
+ * @nullable
+ */
+ run_index: number | null
+}
+
+export interface ReviewPRStatusApi {
+ /** The pull request's repository as 'owner/repo'. */
+ repository: string
+ /** The pull request number. */
+ pr_number: number
+ /**
+ * The PR's review id, for `review-hog-reviews-get`; null before its first run.
+ * @nullable
+ */
+ report_id: string | null
+ /** Where the PR stands now: 'not_reviewed' (no completed review and nothing queued), 'queued' (a run is queued or starting), 'reviewing' (a review turn is running), 'resolving' (Resolve is running), 'idle' (nothing running), 'unknown' (the run state could not be read, retry later).
+ *
+ * * `not_reviewed` - Not reviewed
+ * * `queued` - Queued
+ * * `reviewing` - Reviewing
+ * * `resolving` - Resolving
+ * * `idle` - Idle
+ * * `unknown` - Unknown */
+ state: ReviewPRStateEnumApi
+ /** The latest completed review turn; null before the first one completes. */
+ latest_review: ReviewPRStatusLatestReviewApi | null
+ /** The latest Resolve run, finished ones too; null when no Resolve run has queued threads. */
+ latest_resolution: ReviewLatestResolutionApi | null
+ /** How the request at `requested_at` ended; null without `requested_at`. */
+ request_outcome: ReviewPRStatusRequestOutcomeApi | null
+}
+
/**
* * `review` - Review
* * `review_only` - Review only
@@ -1184,7 +1309,7 @@ export interface ReviewTriggerResponseApi {
report_id: string | null
/** Server time when the request was accepted. */
requested_at: string
- /** Whether this request runs the resolution stage, which can push fix commits to the pull request. */
+ /** Whether this request plans to run the resolution stage, which can push fix commits to the pull request. It is the plan at request time: a request queued behind a running turn on the same head can be skipped as already published. `review-hog-reviews-pr-status` reports what actually ran. */
resolve_will_run: boolean
/** Why the resolution stage does not run: 'run_mode_excludes_resolve' ('review_only' and 'flash' never resolve), 'owner_not_opted_in' (the pull request owner has not turned on resolving comments), 'already_reviewed' (no run starts). Null when it runs.
*
@@ -1460,3 +1585,35 @@ export const ReviewHogReviewsPerspectiveStatsRetrieveScope = {
Everyone: 'everyone',
OwnDeep: 'own_deep',
} as const
+
+export type ReviewHogReviewsPrStatusRetrieveParams = {
+ /**
+ * GitHub pull request URL to look up, e.g. 'https://github.com/PostHog/posthog/pull/123'.
+ * @minLength 1
+ */
+ pr_url: string
+ /**
+ * The `requested_at` the trigger returned. When set, the response carries `request_outcome` for that request.
+ */
+ requested_at?: string
+ /**
+ * The `run_mode` the trigger was called with (default 'review'). Only used with `requested_at`.
+ *
+ * * `review` - Review
+ * * `review_only` - Review only
+ * * `resolve_only` - Resolve only
+ * * `flash` - Standard
+ * @minLength 1
+ */
+ run_mode?: ReviewHogReviewsPrStatusRetrieveRunMode
+}
+
+export type ReviewHogReviewsPrStatusRetrieveRunMode =
+ (typeof ReviewHogReviewsPrStatusRetrieveRunMode)[keyof typeof ReviewHogReviewsPrStatusRetrieveRunMode]
+
+export const ReviewHogReviewsPrStatusRetrieveRunMode = {
+ Review: 'review',
+ ReviewOnly: 'review_only',
+ ResolveOnly: 'resolve_only',
+ Flash: 'flash',
+} as const
diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.ts
index 02ea5ad2fa46..721d507924c8 100644
--- a/products/review_hog/frontend/generated/api.ts
+++ b/products/review_hog/frontend/generated/api.ts
@@ -21,9 +21,11 @@ import type {
ReviewHogRepositoryOverviewRetrieveParams,
ReviewHogReviewsListParams,
ReviewHogReviewsPerspectiveStatsRetrieveParams,
+ ReviewHogReviewsPrStatusRetrieveParams,
ReviewHogReviewsRetrieveParams,
ReviewInstallationClaimApi,
ReviewInstallationClaimCreateApi,
+ ReviewPRStatusApi,
ReviewPerspectiveConfigApi,
ReviewPerspectiveStatsApi,
ReviewProjectSettingsApi,
@@ -639,6 +641,40 @@ export const reviewHogReviewsPerspectiveStatsRetrieve = async (
})
}
+export const getReviewHogReviewsPrStatusRetrieveUrl = (
+ projectId: string,
+ params: ReviewHogReviewsPrStatusRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/review_hog/reviews/pr_status/?${stringifiedParams}`
+ : `/api/projects/${projectId}/review_hog/reviews/pr_status/`
+}
+
+/**
+ * Where a pull request's ReviewHog runs stand: `state`, the latest completed review turn, and the latest Resolve run. Works for any pull request on the project, also ones the caller did not trigger. Pass the trigger's `requested_at` and `run_mode` to get `request_outcome`, which says when that request is done.
+ * @summary Look up a pull request's review status
+ */
+export const reviewHogReviewsPrStatusRetrieve = async (
+ projectId: string,
+ params: ReviewHogReviewsPrStatusRetrieveParams,
+ options?: RequestInit
+): Promise<ReviewPRStatusApi> => {
+ return apiMutator<ReviewPRStatusApi>(getReviewHogReviewsPrStatusRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getReviewHogReviewsTriggerCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/review_hog/reviews/trigger/`
}
diff --git a/products/review_hog/mcp/tools.yaml b/products/review_hog/mcp/tools.yaml
index 8aaa4ea27960..f53fd9757b25 100644
--- a/products/review_hog/mcp/tools.yaml
+++ b/products/review_hog/mcp/tools.yaml
@@ -43,6 +43,28 @@ tools:
review with `review-hog-reviews-get`. The default `scope=mine` covers reviews you ran plus reviews of pull
requests you authored. Pass `scope=everyone` for every review on the project, and `limit` to widen the page.
feature_flag: review-hog
+ review-hog-reviews-pr-status:
+ operation: review_hog_reviews_pr_status_retrieve
+ enabled: true
+ scopes:
+ - review_hog:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get a pull request's ReviewHog status
+ description: >
+ Look up where a pull request's ReviewHog runs stand, by `pr_url`. Works for any PR on the project, also ones
+ you did not trigger. `state` is `not_reviewed`, `queued`, `reviewing`, `resolving`, `idle`, or `unknown`.
+ `latest_review` sums up the latest completed turn (its `id`, `run_index`, `review_mode`, `head_sha` and
+ finding counts by priority), and `latest_resolution` the latest Resolve run. The loop for a run you started:
+ call `review-hog-reviews-trigger`, keep the `requested_at` it returns and the `run_mode` you sent, and poll
+ this tool with them (a minute apart is enough) until `request_outcome.status` is not `pending`. On
+ `completed`, call `review-hog-reviews-get` with `request_outcome.review_id` and `run_index` for the
+ findings; a Deep turn also answers a Standard request. `skipped` and `failed` carry a `reason`, for example
+ `flash_after_full`, `review_failed`, or `no_matching_run` (nothing ran for the request and nothing is
+ queued, so trigger again). `unknown` means the run state could not be read: retry later.
+ feature_flag: review-hog
review-hog-reviews-trigger:
operation: review_hog_reviews_trigger_create
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index fae4104331ef..8547b2f80f25 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -11004,6 +11004,21 @@
},
"feature_flag": "review-hog"
},
+ "review-hog-reviews-pr-status": {
+ "description": "Look up where a pull request's ReviewHog runs stand, by `pr_url`. Works for any PR on the project, also ones you did not trigger. `state` is `not_reviewed`, `queued`, `reviewing`, `resolving`, `idle`, or `unknown`. `latest_review` sums up the latest completed turn (its `id`, `run_index`, `review_mode`, `head_sha` and finding counts by priority), and `latest_resolution` the latest Resolve run. The loop for a run you started: call `review-hog-reviews-trigger`, keep the `requested_at` it returns and the `run_mode` you sent, and poll this tool with them (a minute apart is enough) until `request_outcome.status` is not `pending`. On `completed`, call `review-hog-reviews-get` with `request_outcome.review_id` and `run_index` for the findings; a Deep turn also answers a Standard request. `skipped` and `failed` carry a `reason`, for example `flash_after_full`, `review_failed`, or `no_matching_run` (nothing ran for the request and nothing is queued, so trigger again). `unknown` means the run state could not be read: retry later.",
+ "category": "ReviewHog",
+ "feature": "review_hog",
+ "summary": "Get a pull request's ReviewHog status",
+ "title": "Get a pull request's ReviewHog status",
+ "required_scopes": ["review_hog:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "review-hog"
+ },
"review-hog-reviews-trigger": {
"description": "Start a ReviewHog run on a pull request. Pass the PR as `pr_url` (e.g. `https://github.com/PostHog/posthog/pull/123`). The repository must be accessible to the project's GitHub App installation. `run_mode` picks the variant: `review` (the default) is a Deep review, published to the PR, followed by the Resolve stage; `review_only` is a Deep review without Resolve; `flash` is a Standard review on a lower-cost model that never resolves; `resolve_only` skips the review and only works the PR's existing unresolved review threads. Resolve runs only when the pull request owner opted in to resolving comments, not the requester. The owner is the PR author, or the Inbox reviewer for a PR the PostHog app opened. The response's `resolve_will_run` says whether Resolve will run, and `resolve_skip_reason` says why not. IMPORTANT: Resolve writes to the PR itself. It may push signed fix commits to the PR's branch, reply to review threads, and resolve bot-authored threads. Nothing is deleted and the commits are plain appends, but the actions are public to everyone on the PR. Non-blocking: returns `status` `started`, with `repository`, `pr_number`, the `head_sha` the request targets, `review_mode`, `requested_at`, and `report_id` (null on the PR's first run; find it later with `review-hog-reviews-list`). If the PR's current commit already has a published review in the requested mode, it returns `already_reviewed` without starting a run (`resolve_only` skips that check). A request while a review runs is queued on that PR's run and returns `joined_running_review`. Refusals: 409 with `code` `flash_after_full` (the PR has a Deep review, so ask for `review` instead) or `resolution_not_opted_in` (`resolve_only` on a PR whose owner did not opt in); 409 without a code while Resolve runs on the PR, or while a review runs for a `resolve_only` request. Poll progress with `review-hog-reviews-list` and read the findings with `review-hog-reviews-get`.",
"category": "ReviewHog",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index bad77113ddb4..981516dae4cb 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11609,6 +11609,21 @@
},
"feature_flag": "review-hog"
},
+ "review-hog-reviews-pr-status": {
+ "description": "Look up where a pull request's ReviewHog runs stand, by `pr_url`. Works for any PR on the project, also ones you did not trigger. `state` is `not_reviewed`, `queued`, `reviewing`, `resolving`, `idle`, or `unknown`. `latest_review` sums up the latest completed turn (its `id`, `run_index`, `review_mode`, `head_sha` and finding counts by priority), and `latest_resolution` the latest Resolve run. The loop for a run you started: call `review-hog-reviews-trigger`, keep the `requested_at` it returns and the `run_mode` you sent, and poll this tool with them (a minute apart is enough) until `request_outcome.status` is not `pending`. On `completed`, call `review-hog-reviews-get` with `request_outcome.review_id` and `run_index` for the findings; a Deep turn also answers a Standard request. `skipped` and `failed` carry a `reason`, for example `flash_after_full`, `review_failed`, or `no_matching_run` (nothing ran for the request and nothing is queued, so trigger again). `unknown` means the run state could not be read: retry later.",
+ "category": "ReviewHog",
+ "feature": "review_hog",
+ "summary": "Get a pull request's ReviewHog status",
+ "title": "Get a pull request's ReviewHog status",
+ "required_scopes": ["review_hog:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "review-hog"
+ },
"review-hog-reviews-trigger": {
"description": "Start a ReviewHog run on a pull request. Pass the PR as `pr_url` (e.g. `https://github.com/PostHog/posthog/pull/123`). The repository must be accessible to the project's GitHub App installation. `run_mode` picks the variant: `review` (the default) is a Deep review, published to the PR, followed by the Resolve stage; `review_only` is a Deep review without Resolve; `flash` is a Standard review on a lower-cost model that never resolves; `resolve_only` skips the review and only works the PR's existing unresolved review threads. Resolve runs only when the pull request owner opted in to resolving comments, not the requester. The owner is the PR author, or the Inbox reviewer for a PR the PostHog app opened. The response's `resolve_will_run` says whether Resolve will run, and `resolve_skip_reason` says why not. IMPORTANT: Resolve writes to the PR itself. It may push signed fix commits to the PR's branch, reply to review threads, and resolve bot-authored threads. Nothing is deleted and the commits are plain appends, but the actions are public to everyone on the PR. Non-blocking: returns `status` `started`, with `repository`, `pr_number`, the `head_sha` the request targets, `review_mode`, `requested_at`, and `report_id` (null on the PR's first run; find it later with `review-hog-reviews-list`). If the PR's current commit already has a published review in the requested mode, it returns `already_reviewed` without starting a run (`resolve_only` skips that check). A request while a review runs is queued on that PR's run and returns `joined_running_review`. Refusals: 409 with `code` `flash_after_full` (the PR has a Deep review, so ask for `review` instead) or `resolution_not_opted_in` (`resolve_only` on a PR whose owner did not opt in); 409 without a code while Resolve runs on the PR, or while a review runs for a `resolve_only` request. Poll progress with `review-hog-reviews-list` and read the findings with `review-hog-reviews-get`.",
"category": "ReviewHog",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 32b525c2ff33..5200aa8ddae5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -95602,6 +95602,132 @@ export namespace Schemas {
scope: ReviewInstallationClaimScopeEnum;
}
+ /**
+ * * `not_reviewed` - Not reviewed
+ * * `queued` - Queued
+ * * `reviewing` - Reviewing
+ * * `resolving` - Resolving
+ * * `idle` - Idle
+ * * `unknown` - Unknown
+ */
+ export type ReviewPRStateEnum = typeof ReviewPRStateEnum[keyof typeof ReviewPRStateEnum];
+
+
+ export const ReviewPRStateEnum = {
+ NotReviewed: 'not_reviewed',
+ Queued: 'queued',
+ Reviewing: 'reviewing',
+ Resolving: 'resolving',
+ Idle: 'idle',
+ Unknown: 'unknown',
+ } as const;
+
+ export interface ReviewPRStatusLatestReview {
+ /** The review's id, for `review-hog-reviews-get`. */
+ id: string;
+ /** What the turn ran: 'full' (Deep) or 'flash' (Standard). Null when the turn did not record it.
+ *
+ * * `full` - Deep
+ * * `flash` - Standard */
+ review_mode: ReviewTriggerReviewModeEnum | null;
+ /**
+ * The PR head commit the turn reviewed.
+ * @nullable
+ */
+ head_sha: string | null;
+ /** The turn's index, for `review-hog-reviews-get`. */
+ run_index: number;
+ /**
+ * When the turn completed.
+ * @nullable
+ */
+ completed_at: string | null;
+ /** The turn's valid findings at must_fix priority. */
+ must_fix_count: number;
+ /** The turn's valid findings at should_fix priority. */
+ should_fix_count: number;
+ /** The turn's valid findings at consider priority. */
+ consider_count: number;
+ /** Whether the turn was published to GitHub. */
+ turn_published: boolean;
+ /**
+ * Link to the review's status comment on the pull request; null when there is none.
+ * @nullable
+ */
+ status_comment_url: string | null;
+ }
+
+ /**
+ * * `pending` - Pending
+ * * `completed` - Completed
+ * * `skipped` - Skipped
+ * * `failed` - Failed
+ * * `unknown` - Unknown
+ */
+ export type ReviewRequestOutcomeStatusEnum = typeof ReviewRequestOutcomeStatusEnum[keyof typeof ReviewRequestOutcomeStatusEnum];
+
+
+ export const ReviewRequestOutcomeStatusEnum = {
+ Pending: 'pending',
+ Completed: 'completed',
+ Skipped: 'skipped',
+ Failed: 'failed',
+ Unknown: 'unknown',
+ } as const;
+
+ export interface ReviewPRStatusRequestOutcome {
+ /** How the request ended: 'pending' while a run for it is queued or running, 'completed' when a turn of the requested mode or deeper finished after `requested_at` (Deep covers Standard), 'skipped' when the run ended without doing the work, 'failed' when the run died or no run answered the request, 'unknown' when the run state could not be read (retry later).
+ *
+ * * `pending` - Pending
+ * * `completed` - Completed
+ * * `skipped` - Skipped
+ * * `failed` - Failed
+ * * `unknown` - Unknown */
+ status: ReviewRequestOutcomeStatusEnum;
+ /**
+ * Why it was skipped or failed: 'flash_after_full' (Standard dropped after a Deep review), 'review_failed', 'stopped' (Resolve died partway), 'no_matching_run' (nothing ran for the request and nothing is queued, for example when the queue replaced it), or a Resolve skip reason such as 'pr_not_open', 'resolution_not_opted_in', 'no_unresolved_threads', 'pr_in_merge_queue'. Null otherwise.
+ * @nullable
+ */
+ reason: string | null;
+ /**
+ * The review to read with `review-hog-reviews-get`; null before the PR has one.
+ * @nullable
+ */
+ review_id: string | null;
+ /**
+ * The review turn that answered or failed the request, for `review-hog-reviews-get`. Null for 'resolve_only' and while pending.
+ * @nullable
+ */
+ run_index: number | null;
+ }
+
+ export interface ReviewPRStatus {
+ /** The pull request's repository as 'owner/repo'. */
+ repository: string;
+ /** The pull request number. */
+ pr_number: number;
+ /**
+ * The PR's review id, for `review-hog-reviews-get`; null before its first run.
+ * @nullable
+ */
+ report_id: string | null;
+ /** Where the PR stands now: 'not_reviewed' (no completed review and nothing queued), 'queued' (a run is queued or starting), 'reviewing' (a review turn is running), 'resolving' (Resolve is running), 'idle' (nothing running), 'unknown' (the run state could not be read, retry later).
+ *
+ * * `not_reviewed` - Not reviewed
+ * * `queued` - Queued
+ * * `reviewing` - Reviewing
+ * * `resolving` - Resolving
+ * * `idle` - Idle
+ * * `unknown` - Unknown */
+ state: ReviewPRStateEnum;
+ /** The latest completed review turn; null before the first one completes. */
+ latest_review: ReviewPRStatusLatestReview | null;
+ /** The latest Resolve run, finished ones too; null when no Resolve run has queued threads. */
+ latest_resolution: ReviewLatestResolution | null;
+ /** How the request at `requested_at` ended; null without `requested_at`. */
+ request_outcome: ReviewPRStatusRequestOutcome | null;
+ }
+
export interface ReviewPerspectiveConfig {
/** Name of the `review-hog-perspective-*` skill this row toggles (the perspective's identity). */
skill_name: string;
@@ -96119,7 +96245,7 @@ export namespace Schemas {
report_id: string | null;
/** Server time when the request was accepted. */
requested_at: string;
- /** Whether this request runs the resolution stage, which can push fix commits to the pull request. */
+ /** Whether this request plans to run the resolution stage, which can push fix commits to the pull request. It is the plan at request time: a request queued behind a running turn on the same head can be skipped as already published. `review-hog-reviews-pr-status` reports what actually ran. */
resolve_will_run: boolean;
/** Why the resolution stage does not run: 'run_mode_excludes_resolve' ('review_only' and 'flash' never resolve), 'owner_not_opted_in' (the pull request owner has not turned on resolving comments), 'already_reviewed' (no run starts). Null when it runs.
*
@@ -126487,6 +126613,38 @@ export namespace Schemas {
OwnDeep: 'own_deep',
} as const;
+ export type ReviewHogReviewsPrStatusRetrieveParams = {
+ /**
+ * GitHub pull request URL to look up, e.g. 'https://github.com/PostHog/posthog/pull/123'.
+ * @minLength 1
+ */
+ pr_url: string;
+ /**
+ * The `requested_at` the trigger returned. When set, the response carries `request_outcome` for that request.
+ */
+ requested_at?: string;
+ /**
+ * The `run_mode` the trigger was called with (default 'review'). Only used with `requested_at`.
+ *
+ * * `review` - Review
+ * * `review_only` - Review only
+ * * `resolve_only` - Resolve only
+ * * `flash` - Standard
+ * @minLength 1
+ */
+ run_mode?: ReviewHogReviewsPrStatusRetrieveRunMode;
+ };
+
+ export type ReviewHogReviewsPrStatusRetrieveRunMode = typeof ReviewHogReviewsPrStatusRetrieveRunMode[keyof typeof ReviewHogReviewsPrStatusRetrieveRunMode];
+
+
+ export const ReviewHogReviewsPrStatusRetrieveRunMode = {
+ Review: 'review',
+ ReviewOnly: 'review_only',
+ ResolveOnly: 'resolve_only',
+ Flash: 'flash',
+ } as const;
+
export type SandboxCustomImagesListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/review_hog/api.ts b/services/mcp/src/generated/review_hog/api.ts
index ef8b859b58ab..ad1d3a561997 100644
--- a/services/mcp/src/generated/review_hog/api.ts
+++ b/services/mcp/src/generated/review_hog/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 3 enabled ops
+ * PostHog API - MCP 4 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -64,6 +64,39 @@ export const ReviewHogReviewsRetrieveQueryParams = () => zod.object({
),
})
+/**
+ * Where a pull request's ReviewHog runs stand: `state`, the latest completed review turn, and the latest Resolve run. Works for any pull request on the project, also ones the caller did not trigger. Pass the trigger's `requested_at` and `run_mode` to get `request_outcome`, which says when that request is done.
+ * @summary Look up a pull request's review status
+ */
+export const ReviewHogReviewsPrStatusRetrieveParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const reviewHogReviewsPrStatusRetrieveQueryRunModeDefault = `review`
+
+export const ReviewHogReviewsPrStatusRetrieveQueryParams = () => zod.object({
+ pr_url: zod
+ .string()
+ .min(1)
+ .describe("GitHub pull request URL to look up, e.g. 'https:\/\/github.com\/PostHog\/posthog\/pull\/123'."),
+ requested_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'The `requested_at` the trigger returned. When set, the response carries `request_outcome` for that request.'
+ ),
+ run_mode: zod
+ .enum(['review', 'review_only', 'resolve_only', 'flash'])
+ .default(reviewHogReviewsPrStatusRetrieveQueryRunModeDefault)
+ .describe(
+ "The `run_mode` the trigger was called with (default 'review'). Only used with `requested_at`.\n\n\* `review` - Review\n\* `review_only` - Review only\n\* `resolve_only` - Resolve only\n\* `flash` - Standard"
+ ),
+})
+
/**
* Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The run appears under the requesting user's recent reviews. A Deep review uses the requester's enabled perspectives, blind-spot check, validator, and urgency threshold; a Standard review uses none of them. Resolution writes to the branch only when the pull request owner opted in, whoever asks. `run_mode` picks the variant: 'review' is a Deep review that chains the resolution stage per the owner's resolve_comments setting, 'review_only' is a Deep review without resolving, 'resolve_only' runs resolution only, and 'flash' is a lower-cost Standard review that never resolves comments and is refused after a published Deep review. Nonexistent, closed, and fork PRs are rejected synchronously. A PR whose current commit already has a published review in the requested mode returns 'already_reviewed' without starting a run (resolve_only skips that check, because settling threads on a reviewed head is its whole point). A request while a review runs is queued on that PR's run. Otherwise non-blocking: returns immediately with the PR's head, the review's id when one exists, and whether resolution will run, while the run executes in the worker.
* @summary Start a review of a pull request
diff --git a/services/mcp/src/tools/generated/review_hog.ts b/services/mcp/src/tools/generated/review_hog.ts
index c0ab14d9eb0a..8c9ad5ec0942 100644
--- a/services/mcp/src/tools/generated/review_hog.ts
+++ b/services/mcp/src/tools/generated/review_hog.ts
@@ -53,6 +53,32 @@ const reviewHogReviewsList = (): ToolBase<
},
})
+const ReviewHogReviewsPrStatusSchema = () => {
+ const ReviewHogReviewsPrStatusRetrieveQueryParams = orvalSchemas.ReviewHogReviewsPrStatusRetrieveQueryParams()
+ return ReviewHogReviewsPrStatusRetrieveQueryParams
+}
+
+const reviewHogReviewsPrStatus = (): ToolBase<
+ ReturnType<typeof ReviewHogReviewsPrStatusSchema>,
+ Schemas.ReviewPRStatus
+> => ({
+ name: 'review-hog-reviews-pr-status',
+ schema: ReviewHogReviewsPrStatusSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof ReviewHogReviewsPrStatusSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ReviewPRStatus>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/review_hog/reviews/pr_status/`,
+ query: {
+ pr_url: params.pr_url,
+ requested_at: params.requested_at,
+ run_mode: params.run_mode,
+ },
+ })
+ return result
+ },
+})
+
const ReviewHogReviewsTriggerSchema = () => {
const ReviewHogReviewsTriggerCreateBody = orvalSchemas.ReviewHogReviewsTriggerCreateBody()
return ReviewHogReviewsTriggerCreateBody
@@ -85,5 +111,6 @@ const reviewHogReviewsTrigger = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'review-hog-reviews-get': reviewHogReviewsGet,
'review-hog-reviews-list': reviewHogReviewsList,
+ 'review-hog-reviews-pr-status': reviewHogReviewsPrStatus,
'review-hog-reviews-trigger': reviewHogReviewsTrigger,
}