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.

refactor(review-hog): move the review trigger into a callable function (#114295)

Julian Bez004410cf68d9
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index 0897b771b709..f77045c8ed6e 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -16,27 +16,28 @@ from rest_framework.response import Response
from posthog.api.integration import github_rate_limited_response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.egress.github.transport import GitHubRateLimitError
-from posthog.models.integration import GitHubIntegration
from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission
-from products.review_hog.backend.api.settings import has_internal_features
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
+from products.review_hog.backend.requested_reviews import (
+ RUN_MODE_FLASH,
+ RUN_MODE_RESOLVE_ONLY,
+ RUN_MODE_REVIEW,
+ RUN_MODE_REVIEW_ONLY,
+ PRReviewRequestStatus,
+ request_pr_review,
+)
from products.review_hog.backend.reviewer.artefact_content import (
ReviewIssueCategory,
ReviewIssueFinding,
ValidationVerdict,
)
-from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL, effective_priority
+from products.review_hog.backend.reviewer.constants import effective_priority
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.models.split_pr_into_chunks import ChunksList
-from products.review_hog.backend.reviewer.persistence import (
- lift_review_tier_for_joined_trigger,
- load_chunk_set,
- load_findings_bundle,
- load_turn_findings,
-)
+from products.review_hog.backend.reviewer.persistence import load_chunk_set, load_findings_bundle, load_turn_findings
from products.review_hog.backend.reviewer.progress import (
IN_PROGRESS_STALE_AFTER,
RESOLUTION_RESOLVING,
@@ -50,15 +51,7 @@ from products.review_hog.backend.reviewer.progress import (
snapshot_stats,
turn_stats,
)
-from products.review_hog.backend.reviewer.review_state import review_already_published
-from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
-from products.review_hog.backend.reviewer.tools.github_meta import PRFetcher, PRMetadata, PRParser
-from products.review_hog.backend.temporal.client import (
- start_resolution_workflow,
- start_review_pr_workflow,
- workflow_running,
-)
-from products.review_hog.backend.temporal.types import TRIGGER_UI, resolve_pr_workflow_id, review_pr_workflow_id
+from products.review_hog.backend.reviewer.tools.github_meta import PRParser
logger = logging.getLogger(__name__)
@@ -249,13 +242,11 @@ class ReviewRecentReviewsPageSerializer(serializers.Serializer):
)
-# What the trigger runs. The default 'review' includes the resolution stage when the requesting
-# user's `resolve_comments` setting is on; the others are the split button's explicit variants.
-# Flash never resolves comments because it must not write code.
-RUN_MODE_REVIEW = "review"
-RUN_MODE_REVIEW_ONLY = "review_only"
-RUN_MODE_RESOLVE_ONLY = "resolve_only"
-RUN_MODE_FLASH = "flash"
+_TRIGGER_REFUSAL_STATUS = {
+ PRReviewRequestStatus.INVALID: status.HTTP_400_BAD_REQUEST,
+ PRReviewRequestStatus.NOT_ALLOWED: status.HTTP_403_FORBIDDEN,
+ PRReviewRequestStatus.BUSY: status.HTTP_409_CONFLICT,
+}
class ReviewTriggerRequestSerializer(serializers.Serializer):
@@ -386,22 +377,6 @@ class _PageEnvelopeSchema(AutoSchema):
return operation_id
-def _fetch_pr_metadata(github: GitHubIntegration, owner: str, repo: str, pr_number: int) -> PRMetadata:
- """One `GET /pulls/{n}` with the installation token — enough to answer the trigger honestly.
-
- Raises `GitHubAPIError` (404 for a nonexistent PR); the caller maps it to a clear response.
- """
- token, installation_id = github.get_access_token(), github.github_installation_id
- pr = github_api_request(
- "GET",
- f"/repos/{owner}/{repo}/pulls/{pr_number}",
- token=token,
- installation_id=installation_id,
- endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",
- ).json()
- return PRFetcher(owner=owner, repo=repo, pr_number=pr_number, token=token).fetch_pr_metadata(pr)
-
-
def _in_progress_report_ids(team_id: int, reports: list[ReviewReport]) -> set[str]:
"""Which ACTIVE reports are visibly running: artefact or report activity within the staleness window.
@@ -740,13 +715,6 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
team_id = resolve_effective_team_id(self.team_id)
serializer = ReviewTriggerRequestSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
- run_mode: str = serializer.validated_data["run_mode"]
- # The scene hides Flash outside the internal project; this also stops API and MCP callers there.
- if run_mode == RUN_MODE_FLASH and not has_internal_features(team_id):
- return Response(
- {"error": "Flash reviews aren't available in this project. Start a regular review instead."},
- status=status.HTTP_403_FORBIDDEN,
- )
try:
pr_info = PRParser().parse_github_pr_url(serializer.validated_data["pr_url"])
except ValueError:
@@ -756,137 +724,25 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
},
status=status.HTTP_400_BAD_REQUEST,
)
- repository = f"{pr_info['owner']}/{pr_info['repo']}"
- # Checked synchronously (one GitHub API call) so an inaccessible repo errors here, in the UI —
- # asynchronously the fetch activity would fail before the report row exists, showing nothing.
try:
- github = GitHubIntegration.first_for_team_repository(team_id, repository)
- except GitHubRateLimitError as e:
- return github_rate_limited_response(e)
- if github is None:
- return Response(
- {
- "error": f"PostHog Review's GitHub App can't access {repository}. It reviews repositories covered by this project's GitHub integration."
- },
- status=status.HTTP_400_BAD_REQUEST,
+ outcome = request_pr_review(
+ team_id=team_id,
+ # The route is authenticated, so never anonymous.
+ requester_id=cast(User, request.user).id,
+ owner=str(pr_info["owner"]),
+ repo=str(pr_info["repo"]),
+ pr_number=int(pr_info["pr_number"]),
+ run_mode=serializer.validated_data["run_mode"],
)
- pr_number = int(pr_info["pr_number"])
- # One PR fetch so the answer is honest: without it a typo'd number or fork dies async (before
- # the report row exists — nothing appears), and an already-reviewed head silently no-ops while
- # the response still claims "started". Fork/closed rejection here is UX; the fetch activity
- # keeps the authoritative fork gate.
- try:
- pr_meta = _fetch_pr_metadata(github, str(pr_info["owner"]), str(pr_info["repo"]), pr_number)
except GitHubRateLimitError as e:
return github_rate_limited_response(e)
- except GitHubAPIError as e:
- if e.status == 404:
- return Response(
- {"error": f"No pull request #{pr_number} found in {repository}"},
- status=status.HTTP_400_BAD_REQUEST,
- )
- raise
- if pr_meta.is_fork:
- return Response(
- {"error": "PostHog Review doesn't review fork pull requests (a fork's head can't be trusted)"},
- status=status.HTTP_400_BAD_REQUEST,
- )
- if pr_meta.state != "open":
- return Response(
- {
- "error": f"Pull request #{pr_number} is {pr_meta.state}; PostHog Review only reviews open pull requests"
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
- # The busy-guard (CONTEXT.md): Temporal joins same-id starts on its own, but a review and
- # this PR's resolution run under different workflow ids, so the cross-stage check is
- # explicit — and the answer is a refusal, not a queue.
- pr_owner, pr_repo = str(pr_info["owner"]), str(pr_info["repo"])
- if run_mode == RUN_MODE_RESOLVE_ONLY:
- if workflow_running(
- review_pr_workflow_id(team_id=team_id, owner=pr_owner, repo=pr_repo, pr_number=pr_number)
- ):
- return Response(
- {
- "error": "A review is already running on this pull request. It resolves comments when it finishes."
- },
- status=status.HTTP_409_CONFLICT,
- )
- elif workflow_running(
- resolve_pr_workflow_id(team_id=team_id, owner=pr_owner, repo=pr_repo, pr_number=pr_number)
- ):
- return Response(
- {"error": "Still resolving comments from the last review. Try again when it finishes."},
- status=status.HTTP_409_CONFLICT,
- )
- # Rebuilt canonical URL: the parser accepts trailing paths (e.g. …/pull/123/files).
- pr_url = f"https://github.com/{pr_info['owner']}/{pr_info['repo']}/pull/{pr_info['pr_number']}"
- # The requester is both the run user (sandbox identity) and the acting user (whose
- # perspectives/validator/threshold/criteria apply). The route is authenticated, so never anonymous.
- requester_id = cast(User, request.user).id
-
- if run_mode == RUN_MODE_RESOLVE_ONLY:
- # No already-reviewed early-return here: an already-reviewed head is exactly when a
- # standalone resolution run is useful (the threads exist, the review won't re-run).
- workflow_id = start_resolution_workflow(
- pr_url=pr_url,
- team_id=team_id,
- user_id=requester_id,
- acting_user_id=requester_id,
- trigger_source=TRIGGER_UI,
- )
- logger.info(f"ReviewHog UI trigger started resolution {workflow_id} for {pr_url} by user {requester_id}")
- return Response(
- ReviewTriggerResponseSerializer({"workflow_id": workflow_id, "status": "started"}).data,
- status=status.HTTP_202_ACCEPTED,
- )
-
- # Repository casing can differ per trigger (the report stores whatever its trigger carried).
- report = (
- ReviewReport.objects.for_team(team_id).filter(repository__iexact=repository, pr_number=pr_number).first()
- )
- review_mode = REVIEW_MODE_FLASH if run_mode == RUN_MODE_FLASH else REVIEW_MODE_FULL
- if report is not None and review_already_published(report, pr_meta.head_sha or "", review_mode):
- # The workflow would early-exit before resolving the acting user anyway — say so instead
- # of answering "started" for a run that will do nothing.
- return Response(
- ReviewTriggerResponseSerializer({"workflow_id": "", "status": "already_reviewed"}).data,
- status=status.HTTP_200_OK,
- )
- # Probed before the start: a same-id start joins the running turn, whose inputs keep the
- # original trigger, so the requester's tier lift has to be written here (see the helper).
- joins_running_review = workflow_running(
- review_pr_workflow_id(team_id=team_id, owner=pr_owner, repo=pr_repo, pr_number=pr_number)
- )
- workflow_id = start_review_pr_workflow(
- pr_url=pr_url,
- team_id=team_id,
- user_id=requester_id,
- publish=True,
- acting_user_id=requester_id,
- trigger_source=TRIGGER_UI,
- # None = the requester's resolve_comments setting decides; review_only and flash pin it off.
- resolve_comments=False if run_mode in (RUN_MODE_REVIEW_ONLY, RUN_MODE_FLASH) else None,
- review_mode=review_mode,
- requested_head_sha=pr_meta.head_sha,
- )
- if joins_running_review:
- # Flash is excluded for the same reason the fetch upsert excludes it: the lift rewrites
- # the persisted arm, so the cheapest request must not raise what later turns cost.
- lifted = run_mode != RUN_MODE_FLASH and lift_review_tier_for_joined_trigger(
- team_id=team_id, repository=repository, pr_number=pr_number
- )
- logger.info(
- f"ReviewHog UI trigger joined running workflow {workflow_id} for {pr_url} (tier lifted={lifted})"
- )
- return Response(
- ReviewTriggerResponseSerializer({"workflow_id": workflow_id, "status": "joined_running_review"}).data,
- status=status.HTTP_202_ACCEPTED,
- )
- logger.info(f"ReviewHog UI trigger started workflow {workflow_id} for {pr_url} by user {requester_id}")
+ if outcome.error:
+ return Response({"error": outcome.error}, status=_TRIGGER_REFUSAL_STATUS[outcome.status])
return Response(
- ReviewTriggerResponseSerializer({"workflow_id": workflow_id, "status": "started"}).data,
- status=status.HTTP_202_ACCEPTED,
+ ReviewTriggerResponseSerializer({"workflow_id": outcome.workflow_id, "status": outcome.status.value}).data,
+ status=status.HTTP_200_OK
+ if outcome.status == PRReviewRequestStatus.ALREADY_REVIEWED
+ else status.HTTP_202_ACCEPTED,
)
@extend_schema(
diff --git a/products/review_hog/backend/api/settings.py b/products/review_hog/backend/api/settings.py
index f680971fd67c..50fb0b041f08 100644
--- a/products/review_hog/backend/api/settings.py
+++ b/products/review_hog/backend/api/settings.py
@@ -1,7 +1,5 @@
import logging
-from django.conf import settings
-
from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
@@ -12,6 +10,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.permissions import PostHogFeatureFlagPermission
+from products.review_hog.backend.internal_features import has_internal_features
from products.review_hog.backend.models import ReviewUserSettings
from products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_authoring
from products.stamphog.backend.facade.api import has_reviewable_repo_config
@@ -19,11 +18,6 @@ from products.stamphog.backend.facade.api import has_reviewable_repo_config
logger = logging.getLogger(__name__)
-def has_internal_features(team_id: int) -> bool:
- """Whether a project gets Flash and the automation settings: only the first configured ReviewHog team."""
- return bool(settings.REVIEWHOG_TEAM_IDS and team_id == settings.REVIEWHOG_TEAM_IDS[0])
-
-
class ReviewUserSettingsSerializer(serializers.ModelSerializer):
review_inbox_prs = serializers.BooleanField(
required=False,
diff --git a/products/review_hog/backend/facade/reviews.py b/products/review_hog/backend/facade/reviews.py
new file mode 100644
index 000000000000..de2ad2cfb2ec
--- /dev/null
+++ b/products/review_hog/backend/facade/reviews.py
@@ -0,0 +1,71 @@
+"""Facade for starting a review a PostHog user asked for, from outside the review API.
+
+Lives apart from ``github.py`` because this path imports the Temporal client, which the webhook
+enqueue in ``github.py`` must not load.
+"""
+
+from posthog.models.scoping.manager import resolve_effective_team_id
+from posthog.models.team import Team
+from posthog.models.user import User
+from posthog.permissions import posthog_feature_flag_enabled
+
+from products.review_hog.backend.internal_features import has_internal_features
+from products.review_hog.backend.requested_reviews import (
+ RUN_MODE_FLASH,
+ RUN_MODE_REVIEW,
+ PRReviewRequestOutcome,
+ PRReviewRequestStatus,
+ request_pr_review as _request_pr_review,
+)
+from products.review_hog.backend.temporal.types import TRIGGER_COMMENT
+
+__all__ = [
+ "RUN_MODE_FLASH",
+ "RUN_MODE_REVIEW",
+ "PRReviewRequestOutcome",
+ "PRReviewRequestStatus",
+ "flash_available",
+ "request_pr_review",
+]
+
+_FEATURE_FLAG = "review-hog"
+
+
+def flash_available(team_id: int) -> bool:
+ """Flash is limited to the internal ReviewHog project until that gate becomes a flag."""
+ return has_internal_features(resolve_effective_team_id(team_id))
+
+
+def request_pr_review(
+ *, team_id: int, requester_id: int, repository: str, pr_number: int, run_mode: str
+) -> PRReviewRequestOutcome:
+ """Start the run, with the requester as both the run user and the acting user.
+
+ This is the pull request comment path. The run uses the commenter's settings, but the resolution
+ stage writes commits to the pull request's branch. Until the pull request owner's own opt-in
+ decides that, a comment must not write to anyone's branch, so resolution stays off.
+ Applies the `review-hog` flag, which the review API applies through its permission class.
+ The caller has already checked that the requester is a member of the project.
+ Raises `GitHubRateLimitError` when GitHub rate-limits the App's token.
+ """
+ requester = User.objects.get(id=requester_id)
+ organization_id = Team.objects.values_list("organization_id", flat=True).get(id=team_id)
+ # Access is gated per environment, like the review API's permission class, while review data
+ # is shared under the parent project.
+ if not posthog_feature_flag_enabled(
+ _FEATURE_FLAG, str(requester.distinct_id), organization_id=organization_id, team_id=team_id
+ ):
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.NOT_ALLOWED, error="PostHog Review isn't enabled for this project."
+ )
+ owner, _, repo = repository.partition("/")
+ return _request_pr_review(
+ team_id=resolve_effective_team_id(team_id),
+ requester_id=requester_id,
+ owner=owner,
+ repo=repo,
+ pr_number=pr_number,
+ run_mode=run_mode,
+ trigger_source=TRIGGER_COMMENT,
+ resolve_comments=False,
+ )
diff --git a/products/review_hog/backend/internal_features.py b/products/review_hog/backend/internal_features.py
new file mode 100644
index 000000000000..e554cdc58b29
--- /dev/null
+++ b/products/review_hog/backend/internal_features.py
@@ -0,0 +1,6 @@
+from django.conf import settings
+
+
+def has_internal_features(team_id: int) -> bool:
+ """Whether a project gets Flash and the automation settings: only the first configured ReviewHog team."""
+ return bool(settings.REVIEWHOG_TEAM_IDS and team_id == settings.REVIEWHOG_TEAM_IDS[0])
diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.py
index 5c83f6c69782..43d94cece9c7 100644
--- a/products/review_hog/backend/models.py
+++ b/products/review_hog/backend/models.py
@@ -107,7 +107,7 @@ class ReviewReport(UUIDModel, TeamScopedRootMixin):
# signals side (the signals-side `code_review` artefact is API-deletable; this row is the durable
# link). Filled once, never overwritten by later turns from another trigger.
signal_report_id = models.UUIDField(null=True, blank=True)
- # Which trigger created this report ("label" / "inbox" / "manual" / "ui"); stamped on create only.
+ # Which trigger created this report ("label" / "inbox" / "manual" / "ui" / "comment"); stamped on create only.
trigger_source = models.CharField(max_length=20, default="manual")
# The reviewer arm, chosen once at creation from the report's tier (see `REVIEW_ARMS_BY_TIER`)
# and sticky for the report's life. Adapter/model/effort/permission-mode persist as one bundle
diff --git a/products/review_hog/backend/requested_reviews.py b/products/review_hog/backend/requested_reviews.py
new file mode 100644
index 000000000000..715112d95c0a
--- /dev/null
+++ b/products/review_hog/backend/requested_reviews.py
@@ -0,0 +1,216 @@
+"""Start a review of a pull request because a PostHog user asked for it.
+
+The review trigger in the Code review UI and the `@posthog review` pull request command both come
+here, so one place decides which requests start a run. The caller has already authenticated the
+requester and checked their access to the project.
+"""
+
+import logging
+from enum import StrEnum
+from typing import Literal
+
+from posthog.dataclasses import frozen
+from posthog.models.integration import GitHubIntegration
+
+from products.review_hog.backend.internal_features import has_internal_features
+from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
+from products.review_hog.backend.reviewer.persistence import lift_review_tier_for_joined_trigger
+from products.review_hog.backend.reviewer.review_state import review_already_published
+from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
+from products.review_hog.backend.reviewer.tools.github_meta import PRFetcher, PRMetadata
+from products.review_hog.backend.temporal.client import (
+ start_resolution_workflow,
+ start_review_pr_workflow,
+ workflow_running,
+)
+from products.review_hog.backend.temporal.types import TRIGGER_UI, resolve_pr_workflow_id, review_pr_workflow_id
+
+logger = logging.getLogger(__name__)
+
+# What the trigger runs. The default 'review' includes the resolution stage when the requesting
+# user's `resolve_comments` setting is on; the others are the split button's explicit variants.
+# Flash never resolves comments because it must not write code.
+RUN_MODE_REVIEW = "review"
+RUN_MODE_REVIEW_ONLY = "review_only"
+RUN_MODE_RESOLVE_ONLY = "resolve_only"
+RUN_MODE_FLASH = "flash"
+RUN_MODES = (RUN_MODE_REVIEW, RUN_MODE_REVIEW_ONLY, RUN_MODE_RESOLVE_ONLY, RUN_MODE_FLASH)
+
+
+class PRReviewRequestStatus(StrEnum):
+ STARTED = "started"
+ JOINED_RUNNING_REVIEW = "joined_running_review"
+ ALREADY_REVIEWED = "already_reviewed"
+ # The request cannot start a run as asked: the repository, the pull request or its state.
+ INVALID = "invalid"
+ # The requested mode is not available in this project.
+ NOT_ALLOWED = "not_allowed"
+ # The pull request's review cycle is busy, so the request is refused rather than queued.
+ BUSY = "busy"
+
+
+@frozen
+class PRReviewRequestOutcome:
+ status: PRReviewRequestStatus
+ workflow_id: str = ""
+ # Written for the requester. Built from the repository name, the PR number and fixed text only.
+ error: str = ""
+
+ @property
+ def started(self) -> bool:
+ return self.status in (
+ PRReviewRequestStatus.STARTED,
+ PRReviewRequestStatus.JOINED_RUNNING_REVIEW,
+ PRReviewRequestStatus.ALREADY_REVIEWED,
+ )
+
+
+def fetch_pr_metadata(github: GitHubIntegration, owner: str, repo: str, pr_number: int) -> PRMetadata:
+ """One `GET /pulls/{n}` with the installation token — enough to answer the trigger honestly.
+
+ Raises `GitHubAPIError` (404 for a nonexistent PR); the caller maps it to a clear response.
+ """
+ token, installation_id = github.get_access_token(), github.github_installation_id
+ pr = github_api_request(
+ "GET",
+ f"/repos/{owner}/{repo}/pulls/{pr_number}",
+ token=token,
+ installation_id=installation_id,
+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",
+ ).json()
+ return PRFetcher(owner=owner, repo=repo, pr_number=pr_number, token=token).fetch_pr_metadata(pr)
+
+
+def request_pr_review(
+ *,
+ team_id: int,
+ requester_id: int,
+ owner: str,
+ repo: str,
+ pr_number: int,
+ run_mode: str,
+ trigger_source: str = TRIGGER_UI,
+ resolve_comments: Literal[False] | None = None,
+) -> PRReviewRequestOutcome:
+ """Start the requested run, or say why not.
+
+ The requester is both the run user (sandbox identity) and the acting user, whose perspectives,
+ validator, threshold and resolution criteria apply. Raises `GitHubRateLimitError` when GitHub
+ rate-limits the App's token, so the caller can answer with the wait.
+
+ `resolve_comments=False` turns the resolution stage off in every mode. A caller cannot turn it
+ on: `None` lets the run mode and the requester's setting decide.
+ """
+ # The scene hides Flash outside the internal project; this also stops API and MCP callers there.
+ if run_mode == RUN_MODE_FLASH and not has_internal_features(team_id):
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.NOT_ALLOWED,
+ error="Flash reviews aren't available in this project. Start a regular review instead.",
+ )
+ if run_mode == RUN_MODE_RESOLVE_ONLY and resolve_comments is False:
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.NOT_ALLOWED,
+ error="This trigger can't resolve review comments. Start a review instead.",
+ )
+ repository = f"{owner}/{repo}"
+ # Checked synchronously (one GitHub API call) so an inaccessible repo errors here, in the UI —
+ # asynchronously the fetch activity would fail before the report row exists, showing nothing.
+ github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ if github is None:
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.INVALID,
+ error=f"PostHog Review's GitHub App can't access {repository}. It reviews repositories covered by this project's GitHub integration.",
+ )
+ # One PR fetch so the answer is honest: without it a typo'd number or fork dies async (before
+ # the report row exists — nothing appears), and an already-reviewed head silently no-ops while
+ # the response still claims "started". Fork/closed rejection here is UX; the fetch activity
+ # keeps the authoritative fork gate.
+ try:
+ pr_meta = fetch_pr_metadata(github, owner, repo, pr_number)
+ except GitHubAPIError as e:
+ if e.status == 404:
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.INVALID, error=f"No pull request #{pr_number} found in {repository}"
+ )
+ raise
+ if pr_meta.is_fork:
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.INVALID,
+ error="PostHog Review doesn't review fork pull requests (a fork's head can't be trusted)",
+ )
+ if pr_meta.state != "open":
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.INVALID,
+ error=f"Pull request #{pr_number} is {pr_meta.state}; PostHog Review only reviews open pull requests",
+ )
+ # The busy-guard (CONTEXT.md): Temporal joins same-id starts on its own, but a review and
+ # this PR's resolution run under different workflow ids, so the cross-stage check is
+ # explicit — and the answer is a refusal, not a queue.
+ if run_mode == RUN_MODE_RESOLVE_ONLY:
+ if workflow_running(review_pr_workflow_id(team_id=team_id, owner=owner, repo=repo, pr_number=pr_number)):
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.BUSY,
+ error="A review is already running on this pull request. It resolves comments when it finishes.",
+ )
+ elif workflow_running(resolve_pr_workflow_id(team_id=team_id, owner=owner, repo=repo, pr_number=pr_number)):
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.BUSY,
+ error="Still resolving comments from the last review. Try again when it finishes.",
+ )
+ # Rebuilt canonical URL: the parser accepts trailing paths (e.g. …/pull/123/files).
+ pr_url = f"https://github.com/{owner}/{repo}/pull/{pr_number}"
+
+ if run_mode == RUN_MODE_RESOLVE_ONLY:
+ # No already-reviewed early-return here: an already-reviewed head is exactly when a
+ # standalone resolution run is useful (the threads exist, the review won't re-run).
+ workflow_id = start_resolution_workflow(
+ pr_url=pr_url,
+ team_id=team_id,
+ user_id=requester_id,
+ acting_user_id=requester_id,
+ trigger_source=trigger_source,
+ )
+ logger.info(
+ f"ReviewHog {trigger_source} trigger started resolution {workflow_id} for {pr_url} by user {requester_id}"
+ )
+ return PRReviewRequestOutcome(status=PRReviewRequestStatus.STARTED, workflow_id=workflow_id)
+
+ # Repository casing can differ per trigger (the report stores whatever its trigger carried).
+ report = ReviewReport.objects.for_team(team_id).filter(repository__iexact=repository, pr_number=pr_number).first()
+ review_mode = REVIEW_MODE_FLASH if run_mode == RUN_MODE_FLASH else REVIEW_MODE_FULL
+ if report is not None and review_already_published(report, pr_meta.head_sha or "", review_mode):
+ # The workflow would early-exit before resolving the acting user anyway — say so instead
+ # of answering "started" for a run that will do nothing.
+ return PRReviewRequestOutcome(status=PRReviewRequestStatus.ALREADY_REVIEWED)
+ # Probed before the start: a same-id start joins the running turn, whose inputs keep the
+ # original trigger, so the requester's tier lift has to be written here (see the helper).
+ joins_running_review = workflow_running(
+ review_pr_workflow_id(team_id=team_id, owner=owner, repo=repo, pr_number=pr_number)
+ )
+ workflow_id = start_review_pr_workflow(
+ pr_url=pr_url,
+ team_id=team_id,
+ user_id=requester_id,
+ publish=True,
+ acting_user_id=requester_id,
+ trigger_source=trigger_source,
+ # None = the requester's setting decides; review_only, flash and a caller's False pin it off.
+ resolve_comments=False if run_mode in (RUN_MODE_REVIEW_ONLY, RUN_MODE_FLASH) else resolve_comments,
+ review_mode=review_mode,
+ requested_head_sha=pr_meta.head_sha,
+ )
+ if joins_running_review:
+ # Flash is excluded for the same reason the fetch upsert excludes it: the lift rewrites
+ # the persisted arm, so the cheapest request must not raise what later turns cost.
+ lifted = run_mode != RUN_MODE_FLASH and lift_review_tier_for_joined_trigger(
+ team_id=team_id, repository=repository, pr_number=pr_number
+ )
+ logger.info(
+ f"ReviewHog {trigger_source} trigger joined running workflow {workflow_id} for {pr_url} (tier lifted={lifted})"
+ )
+ return PRReviewRequestOutcome(status=PRReviewRequestStatus.JOINED_RUNNING_REVIEW, workflow_id=workflow_id)
+ logger.info(
+ f"ReviewHog {trigger_source} trigger started workflow {workflow_id} for {pr_url} by user {requester_id}"
+ )
+ return PRReviewRequestOutcome(status=PRReviewRequestStatus.STARTED, workflow_id=workflow_id)
diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.py
index a17f3d64ccb4..b7789539f74b 100644
--- a/products/review_hog/backend/reviewer/constants.py
+++ b/products/review_hog/backend/reviewer/constants.py
@@ -276,13 +276,13 @@ _TIER_BY_PRIORITY: dict[ReportPriority, ReviewTier] = {
# The trigger sources (`temporal/types.py`) that carry an explicit ask for a review: a label, the
-# CLI, or the Code review scene and its MCP tool (both stamped `ui`, so an agent driving the MCP
-# tool on someone's behalf counts as that person asking). Inbox and automatic authored-PR triggers
-# fire without a per-PR request. A trigger from this set on an inbox-created report lifts its tier
+# CLI, the Code review scene and its MCP tool (both stamped `ui`, so an agent driving the MCP
+# tool on someone's behalf counts as that person asking), or an `@posthog review` comment. Inbox
+# and automatic authored-PR triggers fire without a per-PR request. A trigger from this set on an inbox-created report lifts its tier
# (`upsert_review_report`). Spelled out here because persistence cannot import the temporal
# package (its `__init__` imports the activities, which import persistence); `test_constants.py`
# locks the set to the trigger constants.
-HUMAN_TRIGGER_SOURCES = frozenset({"label", "manual", "ui"})
+HUMAN_TRIGGER_SOURCES = frozenset({"label", "manual", "ui", "comment"})
def select_review_tier(*, agent_pr: bool, signal_priority: ReportPriority | None) -> ReviewTier:
diff --git a/products/review_hog/backend/temporal/types.py b/products/review_hog/backend/temporal/types.py
index b3ad67ecf3df..9d3ccfb1d0ca 100644
--- a/products/review_hog/backend/temporal/types.py
+++ b/products/review_hog/backend/temporal/types.py
@@ -9,13 +9,14 @@ from posthog.dataclasses import frozen
from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FULL
# How a review run was triggered. Gates are trigger-aware: label → `review_labeled_prs`,
-# inbox → `review_inbox_prs`, manual (CLI/eval) and ui (an explicit human ask from the Code review
-# scene) → ungated. Plain strings (not an Enum) so Temporal payloads stay forward/backward-compatible
-# across deploys.
+# inbox → `review_inbox_prs`, manual (CLI/eval), ui (an explicit human ask from the Code review
+# scene) and comment (an `@posthog review` pull request comment) → ungated. Plain strings (not an
+# Enum) so Temporal payloads stay forward/backward-compatible across deploys.
TRIGGER_LABEL = "label"
TRIGGER_INBOX = "inbox"
TRIGGER_MANUAL = "manual"
TRIGGER_UI = "ui"
+TRIGGER_COMMENT = "comment"
TRIGGER_AUTOMATIC = "automatic"
diff --git a/products/review_hog/backend/tests/test_ui_trigger_api.py b/products/review_hog/backend/tests/test_ui_trigger_api.py
index 1d98bfe9ef66..61e38012661f 100644
--- a/products/review_hog/backend/tests/test_ui_trigger_api.py
+++ b/products/review_hog/backend/tests/test_ui_trigger_api.py
@@ -9,19 +9,23 @@ from parameterized import parameterized
from rest_framework import status
from posthog.egress.github.transport import GitHubRateLimitError
-from posthog.models import User
+from posthog.models import Team, User
+from products.review_hog.backend.facade.reviews import (
+ PRReviewRequestStatus,
+ request_pr_review as request_pr_review_from_comment,
+)
from products.review_hog.backend.models import ReviewReport, ReviewSkillConfig, ReviewUserSettings
from products.review_hog.backend.reviewer.constants import REVIEW_ARMS_BY_TIER, ReviewTier
from products.review_hog.backend.reviewer.persistence import load_review_arm
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
from products.skills.backend.models.skills import LLMSkill
-_START = "products.review_hog.backend.api.reviews.start_review_pr_workflow"
-_START_RESOLUTION = "products.review_hog.backend.api.reviews.start_resolution_workflow"
-_ACCESS = "products.review_hog.backend.api.reviews.GitHubIntegration.first_for_team_repository"
-_META = "products.review_hog.backend.api.reviews._fetch_pr_metadata"
-_BUSY = "products.review_hog.backend.api.reviews.workflow_running"
+_START = "products.review_hog.backend.requested_reviews.start_review_pr_workflow"
+_START_RESOLUTION = "products.review_hog.backend.requested_reviews.start_resolution_workflow"
+_ACCESS = "products.review_hog.backend.requested_reviews.GitHubIntegration.first_for_team_repository"
+_META = "products.review_hog.backend.requested_reviews.fetch_pr_metadata"
+_BUSY = "products.review_hog.backend.requested_reviews.workflow_running"
def _pr_meta(**overrides: object) -> MagicMock:
@@ -103,6 +107,42 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
self.assertEqual(mock_start.call_args.kwargs["review_mode"], expected_review_mode)
mock_start_resolution.assert_not_called()
+ @patch(_META, return_value=_pr_meta())
+ @patch(_ACCESS, return_value=object())
+ @patch(_START, return_value="wf-comment-1")
+ def test_comment_facade_never_resolves_comments(self, mock_start, _mock_access, _mock_meta):
+ # A comment run acts with the commenter's settings, so an unpinned None would let the
+ # commenter's resolve_comments setting write commits to someone else's branch.
+ outcome = request_pr_review_from_comment(
+ team_id=self.team.id,
+ requester_id=self.user.id,
+ repository="PostHog/posthog.com",
+ pr_number=123,
+ run_mode="review",
+ )
+
+ self.assertEqual(outcome.workflow_id, "wf-comment-1")
+ self.assertEqual(mock_start.call_args.kwargs["trigger_source"], "comment")
+ self.assertIs(mock_start.call_args.kwargs["resolve_comments"], False)
+
+ @patch(_START, return_value="wf-comment-1")
+ def test_comment_facade_gates_on_the_commented_environment_not_its_parent(self, mock_start):
+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment")
+ with patch(
+ "products.review_hog.backend.facade.reviews.posthog_feature_flag_enabled",
+ side_effect=lambda *_args, team_id, **_kwargs: team_id == self.team.id,
+ ):
+ outcome = request_pr_review_from_comment(
+ team_id=environment.id,
+ requester_id=self.user.id,
+ repository="PostHog/posthog.com",
+ pr_number=123,
+ run_mode="review",
+ )
+
+ self.assertEqual(outcome.status, PRReviewRequestStatus.NOT_ALLOWED)
+ mock_start.assert_not_called()
+
@patch(_META, return_value=_pr_meta())
@patch(_ACCESS, return_value=object())
@patch(_START, return_value="wf-ui-1")