: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(review-hog): route the reviews views through the facade and isolate (#115720)
Julian Bezd6ef1c88715e
diff --git a/products/isolation_baseline.txt b/products/isolation_baseline.txtindex eb654a741656..515edf12f74e 100644--- a/products/isolation_baseline.txt+++ b/products/isolation_baseline.txt@@ -64,7 +64,6 @@ remindersreplayreplay_visionrevenue_analytics-review_hogsignalsskillsslack_appdiff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 1e3c4e2977ea..9c1f46c2a65b 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -678,7 +678,6 @@ surveys.Survey products.early_access_features.backend.management.commands.migrattasks.Channel products.tasks.backend.facade.api.create_task_without_run facade-accepts(channel) 1tasks.Task signals.SignalReportTask.task reverse-accessor(signal_report_tasks) 1tasks.Task slack_app.SlackThreadTaskMapping.task reverse-accessor(slack_thread_mappings) 1-tasks.TaskRun products.review_hog.backend.receivers get_model 1tasks.TaskRun products.tasks.backend.facade.api.post_artifact_thread_update facade-accepts(run) 1tasks.TaskRun products.tasks.backend.facade.api.post_commits_pushed_thread_update facade-accepts(run) 1tasks.TaskRun products.tasks.backend.facade.api.post_pr_created_thread_update facade-accepts(run) 1diff --git a/products/review_hog/backend/facade/api.py b/products/review_hog/backend/facade/api.pyindex be5488720af3..8b1b1e987479 100644--- a/products/review_hog/backend/facade/api.py+++ b/products/review_hog/backend/facade/api.py@@ -17,8 +17,10 @@ from products.review_hog.backend.automatic_review_rules import load_peoplefrom products.review_hog.backend.facade.contracts import (UNSET,RepositoryNotFoundError,+ ReviewDetail,ReviewInstallationClaimInfo,ReviewInstallationInfo,+ ReviewPerspectiveStats,ReviewProjectPreferenceDefaults,ReviewProjectSettingsInfo,ReviewRepositoryChoiceInfo,@@ -31,6 +33,8 @@ from products.review_hog.backend.facade.contracts import (ReviewRepositoryWriteOutcome,ReviewSkill,ReviewSkillChoice,+ ReviewSummaryPage,+ ReviewTablePage,ReviewUserPreferences,ReviewUserRef,Unset,@@ -38,8 +42,10 @@ from products.review_hog.backend.facade.contracts import (from products.review_hog.backend.facade.enums import (AutomaticFlashFor,RepositoryOverviewView,+ ReviewActivityFilter,ReviewInstallationClaimScope,ReviewProjectSettingsBotPullRequests,+ ReviewReportScope,ReviewRepositoryPersonKind,ReviewSkillKind,ReviewUserRepositoryChoiceMode,@@ -61,6 +67,7 @@ from products.review_hog.backend.repository_settings import (RepositoryChoices,RepositoryOverview,)+from products.review_hog.backend.review_listing import ReviewListingfrom products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_authoringfrom products.review_hog.backend.skill_configs import ReviewSkillMenufrom products.stamphog.backend.facade.api import has_reviewable_repo_config@@ -450,3 +457,53 @@ def get_review_repository_overview(total=total,my_choices_unlike_default=overview.choices_unlike_default(),)+++# Review reads. Each function takes the root project id, like the repository settings.+++def list_recent_reviews(team_id: int, user_id: int, scope: ReviewReportScope, limit: int) -> ReviewSummaryPage:+ """At most `limit` reviews: the visibly running ones first, then the completed ones, newest first."""+ return ReviewListing(team_id).recent(user_id, scope, limit)+++def list_reviews_table(+ team_id: int,+ user_id: int,+ scope: ReviewReportScope,+ *,+ repository: str | None,+ review_mode: str | None,+ activity: ReviewActivityFilter | None,+ published: bool | None,+ limit: int,+ offset: int,+) -> ReviewTablePage:+ """One page of the reviews with a completed turn or a running one, most recent activity first.++ A filter that is None does not filter.+ """+ return ReviewListing(team_id).table(+ user_id,+ scope,+ repository=repository,+ review_mode=review_mode,+ activity=activity,+ published=published,+ limit=limit,+ offset=offset,+ )+++def get_review_perspective_stats(team_id: int, user_id: int, scope: ReviewReportScope) -> ReviewPerspectiveStats:+ """How many findings each review skill raised across the recent completed reviews in scope, and how many stayed."""+ return ReviewListing(team_id).perspective_stats(user_id, scope)+++def get_review_detail(team_id: int, report_id: UUID, run_index: int | None) -> ReviewDetail:+ """One completed turn of a review, the latest when `run_index` is None.++ Raises `ReviewNotFoundError` when the project has no such review with a completed turn, and+ `ReviewTurnNotFoundError` when the review has no completed turn `run_index`.+ """+ return ReviewListing(team_id).detail(report_id, run_index)diff --git a/products/review_hog/backend/facade/contracts.py b/products/review_hog/backend/facade/contracts.pyindex d84252113e87..6326f4b96758 100644--- a/products/review_hog/backend/facade/contracts.py+++ b/products/review_hog/backend/facade/contracts.py@@ -2,6 +2,7 @@from collections.abc import Mapping, Sequencefrom datetime import datetime+from typing import Literalfrom uuid import UUIDfrom posthog.dataclasses import frozen@@ -16,7 +17,9 @@ from products.review_hog.backend.facade.enums import (ResolveSkipReason,ReviewInstallationClaimScope,ReviewProjectSettingsBotPullRequests,+ ReviewPRState,ReviewRepositoryPersonKind,+ ReviewRequestOutcomeStatus,ReviewRequestRefusal,ReviewUserRepositoryChoiceMode,UrgencyThreshold,@@ -30,6 +33,66 @@ RUN_MODE_REVIEW_ONLY = "review_only"RUN_MODE_RESOLVE_ONLY = "resolve_only"RUN_MODE_FLASH = "flash"+# REVIEW MODE+# What a single turn runs on, chosen per trigger and carried in the workflow input, never persisted on+# the report: a flash turn must not change what the PR's next normal review runs on. Plain strings so+# Temporal payloads stay forward/backward-compatible across deploys, like the trigger sources.+REVIEW_MODE_FULL = "full"+REVIEW_MODE_FLASH = "flash"++# How a turn finds its issues, decided per turn at fetch. Plain strings, like the review mode.+REVIEW_DESIGN_PIPELINE = "pipeline"+REVIEW_DESIGN_SINGLE_AGENT = "single_agent"++REVIEW_STAGES = [+ "fetching",+ "chunking",+ "selecting",+ "reviewing",+ "deduplicating",+ "validating",+ "finalizing",+ # The single-agent design writes no chunk, selection, or validator state, so it has its own shorter sequence.+ "single_agent_preparing",+ "single_agent_reviewing",+ "single_agent_finalizing",+]++RESOLUTION_RESOLVING = "resolving"+RESOLUTION_STOPPED = "stopped"+RESOLUTION_COMPLETED = "completed"++OWN_DEEP_STATS_REVIEW_LIMIT = 10++# Mirrors `IssueValidation.category` (the live LLM contract); redefined here so the durable+# artefact shape doesn't drift with the regenerated review-tool schema.+ReviewIssueCategory = Literal[+ "bug",+ "security",+ "performance",+ "code_quality",+ "best_practice",+ "documentation",+ "testing",+ "accessibility",+ "compatibility",+]++# Why a single-agent turn drops a finding. A `dedup_*` drop repeats an earlier turn's finding, a main+# finding (anchor), or a finding of its own session or lens (sibling). Only records from before Flash+# stopped reading PR comments carry `dedup_comment`. `cap` is the cut in `compose_flash_findings`, and+# `budget` the cut the pull request's finding budget adds on top (`finding_budget.py`).+# `old_code` is a follow-up turn's P3 finding on code that did not change since the last reviewed head.+DropDisposition = Literal[+ "old_code",+ "dedup_prior",+ "dedup_comment",+ "dedup_anchor",+ "dedup_sibling",+ "cap",+ "budget",+]+@frozenclass PRReviewRequestOutcome:@@ -303,3 +366,213 @@ class ReviewRepositoryOverviewPage:# Entries that match the search and the view, on every page.total: intmy_choices_unlike_default: int+++@frozen+class ResolutionRunState:+ """The report's latest resolution run, as the list row and the drawer render it."""++ status: str # RESOLUTION_RESOLVING | RESOLUTION_STOPPED+ done: int = 0+ total: int = 0+ fixed: int = 0+ needs_attention: int = 0+++@frozen+class ResolutionSummary:+ """The report's latest resolution run, completed runs included, as an API reader reports it."""++ status: str # RESOLUTION_RESOLVING | RESOLUTION_STOPPED | RESOLUTION_COMPLETED+ started_at: datetime+ completed_at: datetime | None+ total: int+ fixed: int+ needs_attention: int+ commits: tuple[str, ...]+++@frozen+class PRStatusLatestReview:+ 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 PRStatusRequestOutcome:+ 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: PRStatusLatestReview | None+ latest_resolution: ResolutionSummary | None+ request_outcome: PRStatusRequestOutcome | None+++class InvalidPullRequestURLError(ValueError):+ """The text is not a GitHub pull request URL."""+++class ReviewNotFoundError(LookupError):+ """The project has no review with this id, or the review has no completed turn yet."""+++class ReviewTurnNotFoundError(ReviewNotFoundError):+ """The review has no completed turn with this run index."""+++@frozen+class ReviewProgress:+ """The in-flight review turn's stage, and its counters when the stage has them."""++ review_stage: str+ done: int | None+ total: int | None+++@frozen+class ReviewSummary:+ """One review report as the review list shows it, described by one of its completed turns."""++ id: UUID+ repository: str+ pr_number: int | None+ pr_title: str | None+ pr_author: str | None+ additions: int | None+ deletions: int | None+ changed_files: int | None+ head_branch: str+ github_url: str+ run_count: int+ last_run_at: datetime | None+ published: bool+ turn_published: bool+ review_mode: str | None+ review_design: str | None+ status_comment_url: str | None+ full_review_published: bool+ in_progress: bool+ progress: ReviewProgress | None+ resolution: ResolutionRunState | None+ latest_resolution: ResolutionSummary | None+ must_fix_count: int+ should_fix_count: int+ consider_count: int+ candidate_count: int+ dismissed_count: int+ files_reviewed: int | None+ chunk_count: int | None+ perspective_count: int | None+ perspective_issue_count: int | None+ blind_spot_issue_count: int | None+++@frozen+class ReviewSummaryPage:+ results: Sequence[ReviewSummary]+ has_more: bool+++@frozen+class ReviewTablePage:+ count: int+ # Running reviews that match the scope and every filter except the activity filter.+ running_count: int+ results: Sequence[ReviewSummary]+++@frozen+class ReviewLineRange:+ start: int+ end: int | None+++@frozen+class ReviewFinding:+ title: str+ file: str+ lines: Sequence[ReviewLineRange]+ body: str+ suggestion: str+ effective_priority: str+ reviewer_priority: str+ source_perspective: str | None+ validator_category: ReviewIssueCategory | None+ validator_note: str+++@frozen+class ReviewDroppedFinding:+ title: str+ file: str+ lines: Sequence[ReviewLineRange]+ body: str+ suggestion: str+ priority: str+ source_perspective: str | None+ disposition: DropDisposition+ duplicate_of: str | None+ comment_url: str | None+ rank: int | None+++@frozen+class ReviewSelectionChunk:+ chunk_id: int+ chunk_type: str | None+ files: Sequence[str]+ perspectives: Sequence[str]+ skipped: Sequence[str]+ reason: str+++@frozen+class ReviewPerspectiveSelection:+ roster: Sequence[str]+ chunks: Sequence[ReviewSelectionChunk]+++@frozen+class ReviewDetail:+ """One completed turn of a review: the list row, the findings, and the published body."""++ review: ReviewSummary+ run_index: int+ head_sha: str | None+ perspective_selection: ReviewPerspectiveSelection | None+ report_markdown: str | None+ run_urgency_threshold: str | None+ findings: Sequence[ReviewFinding]+ dismissed_findings: Sequence[ReviewFinding]+ dropped_findings: Sequence[ReviewDroppedFinding]+++@frozen+class ReviewPerspectiveStat:+ skill_name: str+ raised: int+ kept: int+ dismissed: int+++@frozen+class ReviewPerspectiveStats:+ report_count: int+ perspectives: Sequence[ReviewPerspectiveStat]diff --git a/products/review_hog/backend/facade/enums.py b/products/review_hog/backend/facade/enums.pyindex 8ec5e6f37091..4886622a665e 100644--- a/products/review_hog/backend/facade/enums.py+++ b/products/review_hog/backend/facade/enums.py@@ -1,6 +1,6 @@"""Choices the review contracts carry. No Django here, so clients and other products can read them."""-from enum import StrEnum+from enum import Enum, StrEnumfrom posthog.enums import LabeledStrEnum@@ -121,3 +121,42 @@ class RepositoryOverviewView(LabeledStrEnum):IN_PROJECT = "in_project", "In this project"EXCEPTIONS = "exceptions", "With exceptions"MINE = "mine", "My choices"+++class IssuePriority(Enum):+ """Priority levels for code review issues."""++ MUST_FIX = "must_fix" # Critical issues that should block merge+ SHOULD_FIX = "should_fix" # Significant improvements needed+ CONSIDER = "consider" # Nice-to-have improvements+++class ReviewReportScope(StrEnum):+ """Whose reviews a read covers."""++ MINE = "mine"+ EVERYONE = "everyone"+ # The user's own last Deep reviews. Only the perspective stats read this scope.+ OWN_DEEP = "own_deep"+++class ReviewActivityFilter(StrEnum):+ RUNNING = "running"+ COMPLETED = "completed"+++class ReviewPRState(LabeledStrEnum):+ NOT_REVIEWED = "not_reviewed", "Not reviewed"+ QUEUED = "queued", "Queued"+ REVIEWING = "reviewing", "Reviewing"+ RESOLVING = "resolving", "Resolving"+ IDLE = "idle", "Idle"+ UNKNOWN = "unknown", "Unknown"+++class ReviewRequestOutcomeStatus(LabeledStrEnum):+ PENDING = "pending", "Pending"+ COMPLETED = "completed", "Completed"+ SKIPPED = "skipped", "Skipped"+ FAILED = "failed", "Failed"+ UNKNOWN = "unknown", "Unknown"diff --git a/products/review_hog/backend/facade/reviews.py b/products/review_hog/backend/facade/reviews.pyindex e93738b0ac80..e6a8c04bad5f 100644--- a/products/review_hog/backend/facade/reviews.py+++ b/products/review_hog/backend/facade/reviews.py@@ -1,9 +1,12 @@-"""Facade for starting a review a PostHog user asked for, from outside the review API.+"""Facade for starting a review a PostHog user asked for, and for reading where a pull request's runs stand.-Lives apart from ``github.py`` because this path imports the Temporal client, which the webhook-enqueue in ``github.py`` must not load.+Lives apart from ``github.py`` and ``api.py`` because this path imports the Temporal client, which+the webhook enqueue in ``github.py`` must not load."""+from datetime import datetime++from posthog.dataclasses import frozenfrom posthog.models.scoping.manager import resolve_effective_team_idfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -13,11 +16,15 @@ from products.review_hog.backend.facade.contracts import (RUN_MODE_FLASH,RUN_MODE_REVIEW,RUN_MODE_REVIEW_ONLY,+ InvalidPullRequestURLError,PRReviewRequestOutcome,+ PRStatus,)from products.review_hog.backend.facade.enums import PRReviewRequestStatus+from products.review_hog.backend.pr_status import PRStatusLookupfrom products.review_hog.backend.requested_reviews import request_pr_review as _request_pr_review-from products.review_hog.backend.temporal.types import TRIGGER_COMMENT+from products.review_hog.backend.reviewer.tools.github_meta import PRParser+from products.review_hog.backend.temporal.types import TRIGGER_COMMENT, TRIGGER_UI__all__ = ["RUN_MODE_FLASH",@@ -25,12 +32,29 @@ __all__ = ["RUN_MODE_REVIEW_ONLY","PRReviewRequestOutcome","PRReviewRequestStatus",+ "get_pr_review_status","request_pr_review",+ "request_pr_review_by_url",]_FEATURE_FLAG = "review-hog"+@frozen+class _PullRequestURL:+ owner: str+ repo: str+ pr_number: int++ @classmethod+ def parse(cls, pr_url: str) -> "_PullRequestURL":+ try:+ pr_info = PRParser().parse_github_pr_url(pr_url)+ except ValueError as e:+ raise InvalidPullRequestURLError(str(e)) from e+ return cls(owner=str(pr_info["owner"]), repo=str(pr_info["repo"]), pr_number=int(pr_info["pr_number"]))++def request_pr_review(*, team_id: int, requester_id: int, repository: str, pr_number: int, run_mode: str) -> PRReviewRequestOutcome:@@ -62,3 +86,36 @@ def request_pr_review(run_mode=run_mode,trigger_source=TRIGGER_COMMENT,)+++def request_pr_review_by_url(*, team_id: int, requester_id: int, pr_url: str, run_mode: str) -> PRReviewRequestOutcome:+ """Start the run the review API asked for, with the requester as both the run user and the acting user.++ `team_id` is the root project id. The caller applies the `review-hog` flag. Raises+ `InvalidPullRequestURLError` when `pr_url` is not a pull request URL, and `GitHubRateLimitError`+ when GitHub rate-limits the App's token.+ """+ pull_request = _PullRequestURL.parse(pr_url)+ return _request_pr_review(+ team_id=team_id,+ requester_id=requester_id,+ owner=pull_request.owner,+ repo=pull_request.repo,+ pr_number=pull_request.pr_number,+ run_mode=run_mode,+ trigger_source=TRIGGER_UI,+ )+++def get_pr_review_status(+ *, team_id: int, pr_url: str, requested_at: datetime | None, run_mode: str, head_sha: str | None+) -> PRStatus:+ """Where the pull request's review runs stand, and how the request at `requested_at` ended.++ `team_id` is the root project id. Raises `InvalidPullRequestURLError` when `pr_url` is not a pull+ request URL.+ """+ pull_request = _PullRequestURL.parse(pr_url)+ return PRStatusLookup(+ team_id, owner=pull_request.owner, repo=pull_request.repo, pr_number=pull_request.pr_number+ ).status(requested_at, run_mode, head_sha)diff --git a/products/review_hog/backend/pr_status.py b/products/review_hog/backend/pr_status.pyindex fc262b3f521f..b6e67099040a 100644--- a/products/review_hog/backend/pr_status.py+++ b/products/review_hog/backend/pr_status.py@@ -8,23 +8,27 @@ 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.facade.contracts import RUN_MODE_FLASH, RUN_MODE_RESOLVE_ONLY-from products.review_hog.backend.models import ReviewReport-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 (+from products.review_hog.backend.facade.contracts import (RESOLUTION_COMPLETED,RESOLUTION_RESOLVING,RESOLUTION_STOPPED,+ REVIEW_MODE_FLASH,+ REVIEW_MODE_FULL,+ RUN_MODE_FLASH,+ RUN_MODE_RESOLVE_ONLY,+ PRStatus,+ PRStatusLatestReview,+ PRStatusRequestOutcome,+ ResolutionSummary,+)+from products.review_hog.backend.facade.enums import IssuePriority, ReviewPRState, ReviewRequestOutcomeStatus+from products.review_hog.backend.models import ReviewReport+from products.review_hog.backend.reviewer.constants import effective_priority+from products.review_hog.backend.reviewer.persistence import load_findings_bundle+from products.review_hog.backend.reviewer.progress import (RUN_OUTCOME_FAILED,RUN_STAGE_RESOLUTION,RUN_STAGE_REVIEW,- ResolutionSummary,RunOutcomeMarker,in_progress_report_ids,latest_resolution_summaries,@@ -35,24 +39,6 @@ from products.review_hog.backend.reviewer.progress import (from products.review_hog.backend.temporal.client import WorkflowProbe, probe_workflowfrom 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"@@ -61,39 +47,6 @@ _RUNNING_STATES = (ReviewPRState.QUEUED, ReviewPRState.REVIEWING, ReviewPRState._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@@ -161,7 +114,7 @@ class PRStatusLookup:return ReviewPRState.NOT_REVIEWEDreturn ReviewPRState.IDLE- def _latest_review(self) -> LatestReview | None:+ def _latest_review(self) -> PRStatusLatestReview | None:report = self.reportif report is None or self.report_id is None or report.run_count == 0:return None@@ -172,7 +125,7 @@ class PRStatusLookup:if verdict is not None and verdict.is_valid:counts[effective_priority(finding.priority, verdict.adjusted_priority)] += 1marker = turn_markers(self.team_id, [report_id]).get((report_id, report.run_count))- return LatestReview(+ return PRStatusLatestReview(review_id=report_id,review_mode=marker.review_mode if marker else None,head_sha=report.completed_head_sha or report.head_sha,@@ -214,13 +167,13 @@ class PRStatusLookup:return run_indexreturn None- def _ended_outcome(self, marker: RunOutcomeMarker, state: ReviewPRState) -> RequestOutcome:+ def _ended_outcome(self, marker: RunOutcomeMarker, state: ReviewPRState) -> PRStatusRequestOutcome:"""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)+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)if state == ReviewPRState.UNKNOWN:- return RequestOutcome(status=ReviewRequestOutcomeStatus.UNKNOWN, review_id=self.report_id)- return RequestOutcome(+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.UNKNOWN, review_id=self.report_id)+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus(marker.outcome),reason=marker.reason,review_id=self.report_id,@@ -229,7 +182,7 @@ class PRStatusLookup:def _review_outcome(self, requested_at: datetime, requested_mode: str, head_sha: str | None, state: ReviewPRState- ) -> RequestOutcome | None:+ ) -> PRStatusRequestOutcome | None:if self.report is None or self.report_id is None:return Nonereview_markers = [@@ -248,8 +201,8 @@ class PRStatusLookup: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(+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)+ return PRStatusRequestOutcome(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]@@ -259,22 +212,22 @@ class PRStatusLookup:def _resolve_outcome(self, requested_at: datetime, resolution: ResolutionSummary | None, state: ReviewPRState- ) -> RequestOutcome | None:+ ) -> PRStatusRequestOutcome | None:if self.report_id is None:return Noneif 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)+ return PRStatusRequestOutcome(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)+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)if state == ReviewPRState.UNKNOWN:- return RequestOutcome(status=ReviewRequestOutcomeStatus.UNKNOWN, review_id=self.report_id)- return RequestOutcome(+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.UNKNOWN, review_id=self.report_id)+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.FAILED, reason=STOPPED_REASON, review_id=self.report_id)- return RequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)skipped = [markerfor marker in run_outcome_markers(self.team_id, [self.report_id], since=requested_at)[self.report_id]@@ -284,13 +237,13 @@ class PRStatusLookup:return Nonereturn self._ended_outcome(skipped[-1], state)- def _unmatched_outcome(self, state: ReviewPRState) -> RequestOutcome:+ def _unmatched_outcome(self, state: ReviewPRState) -> PRStatusRequestOutcome:"""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)+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.PENDING, review_id=self.report_id)if state == ReviewPRState.UNKNOWN:- return RequestOutcome(status=ReviewRequestOutcomeStatus.UNKNOWN, review_id=self.report_id)- return RequestOutcome(+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.UNKNOWN, review_id=self.report_id)+ return PRStatusRequestOutcome(status=ReviewRequestOutcomeStatus.FAILED, reason=NO_MATCHING_RUN_REASON, review_id=self.report_id)@@ -301,7 +254,7 @@ class PRStatusLookup:if self.report is not None and self.report_id is not Noneelse None)- request_outcome: RequestOutcome | None = None+ request_outcome: PRStatusRequestOutcome | None = Noneif requested_at is not None:if run_mode == RUN_MODE_RESOLVE_ONLY:request_outcome = self._resolve_outcome(requested_at, resolution, state)diff --git a/products/review_hog/backend/presentation/views/reviews.py b/products/review_hog/backend/presentation/views/reviews.pyindex 9939a9245ab9..e116e3e957f3 100644--- a/products/review_hog/backend/presentation/views/reviews.py+++ b/products/review_hog/backend/presentation/views/reviews.py@@ -1,15 +1,13 @@import uuid-import logging+import dataclassesfrom typing import Any, cast, get_argsfrom django.db import models-from django.db.models import F, Func, OuterRef, Q, QuerySet, Subquery, Value-from django.db.models.fields.json import KeyTextTransform-from django.db.models.functions import Cast, Coalescefrom django.utils import timezonefrom drf_spectacular.openapi import AutoSchema-from drf_spectacular.utils import OpenApiResponse, extend_schema+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound@@ -24,57 +22,45 @@ from posthog.models.scoping.manager import resolve_effective_team_idfrom posthog.models.user import Userfrom posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids+from products.review_hog.backend.facade.api import (+ get_review_detail,+ get_review_perspective_stats,+ list_recent_reviews,+ list_reviews_table,+)from products.review_hog.backend.facade.contracts import (+ OWN_DEEP_STATS_REVIEW_LIMIT,+ RESOLUTION_COMPLETED,+ RESOLUTION_RESOLVING,+ RESOLUTION_STOPPED,+ REVIEW_DESIGN_PIPELINE,+ REVIEW_DESIGN_SINGLE_AGENT,+ REVIEW_MODE_FLASH,+ REVIEW_MODE_FULL,+ REVIEW_STAGES,RUN_MODE_FLASH,RUN_MODE_RESOLVE_ONLY,RUN_MODE_REVIEW,RUN_MODE_REVIEW_ONLY,-)-from products.review_hog.backend.facade.enums import PRReviewRequestStatus, ResolveSkipReason, ReviewRequestRefusal-from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact-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 request_pr_review-from products.review_hog.backend.reviewer.artefact_content import (- DroppedFindingArtefact,+ InvalidPullRequestURLError,+ PRStatus,+ ResolutionSummary,ReviewIssueCategory,- ReviewIssueFinding,- ValidationVerdict,+ ReviewNotFoundError,+ ReviewTurnNotFoundError,)-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.models.split_pr_into_chunks import ChunksList-from products.review_hog.backend.reviewer.persistence import (- TurnFindingsBundle,- load_chunk_set,- load_dropped_findings,- load_findings_bundle,+from products.review_hog.backend.facade.enums import (+ IssuePriority,+ PRReviewRequestStatus,+ ResolveSkipReason,+ ReviewActivityFilter,+ ReviewPRState,+ ReviewReportScope,+ ReviewRequestOutcomeStatus,+ ReviewRequestRefusal,+ UrgencyThreshold,)-from products.review_hog.backend.reviewer.progress import (- RESOLUTION_COMPLETED,- RESOLUTION_RESOLVING,- RESOLUTION_STOPPED,- REVIEW_STAGES,- ResolutionRunState,- ResolutionSummary,- SnapshotStats,- TurnMarker,- TurnStats,- finding_counts,- in_progress_report_ids,- latest_resolution_summaries,- progress_payload,- resolution_states,- running_q,- snapshot_stats,- turn_markers,- turn_stats,-)-from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT-from products.review_hog.backend.reviewer.review_state import completed_turn_review_mode-from products.review_hog.backend.reviewer.tools.github_meta import PRParser--logger = logging.getLogger(__name__)+from products.review_hog.backend.facade.reviews import get_pr_review_status, request_pr_review_by_urlDEFAULT_REVIEWS_LIMIT = 5DEFAULT_REVIEWS_TABLE_LIMIT = 25@@ -83,16 +69,10 @@ MAX_REVIEWS_LIMIT = 100# Far beyond any real history, and well inside PostgreSQL's bigint OFFSET.MAX_REVIEWS_TABLE_OFFSET = 1_000_000-# Effectiveness stats aggregate deeper than the list — enough history for survival rates to mean something.-PERSPECTIVE_STATS_REPORT_LIMIT = 50-OWN_DEEP_STATS_REVIEW_LIMIT = 10-_PRIORITY_CHOICES = [priority.value for priority in IssuePriority]-# Display order for the detail view: most urgent first.-_PRIORITY_DISPLAY_RANK = {IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 1, IssuePriority.CONSIDER: 2}-SCOPE_MINE = "mine"-SCOPE_EVERYONE = "everyone"+SCOPE_MINE = ReviewReportScope.MINE.value+SCOPE_EVERYONE = ReviewReportScope.EVERYONE.valueclass ReviewScope(models.TextChoices):@@ -120,7 +100,7 @@ class ReviewsListParamsSerializer(serializers.Serializer):class PerspectiveStatsScope(models.TextChoices):MINE = SCOPE_MINE, "Mine"EVERYONE = SCOPE_EVERYONE, "Everyone"- OWN_DEEP = "own_deep", "Own Deep reviews"+ OWN_DEEP = ReviewReportScope.OWN_DEEP.value, "Own Deep reviews"class PerspectiveStatsParamsSerializer(serializers.Serializer):@@ -152,9 +132,16 @@ class ReviewProgressSerializer(serializers.Serializer):)+class ResolutionStatus(models.TextChoices):+ # Labels equal the values, so the schema keeps the descriptions the plain list produced.+ RESOLVING = RESOLUTION_RESOLVING, RESOLUTION_RESOLVING+ STOPPED = RESOLUTION_STOPPED, RESOLUTION_STOPPED++class ReviewResolutionStatusSerializer(serializers.Serializer):resolution_status = serializers.ChoiceField(- choices=[RESOLUTION_RESOLVING, RESOLUTION_STOPPED],+ source="status",+ choices=ResolutionStatus.choices,help_text="Where the run stands: `resolving` while threads are being settled, `stopped` when the ""run died partway (went quiet with no closing summary).",)@@ -353,8 +340,8 @@ class ReviewRecentReviewsPageSerializer(serializers.Serializer):class ReviewTableStatus(models.TextChoices):- RUNNING = "running", "Running"- COMPLETED = "completed", "Completed"+ RUNNING = ReviewActivityFilter.RUNNING.value, "Running"+ COMPLETED = ReviewActivityFilter.COMPLETED.value, "Completed"class ReviewsTableParamsSerializer(serializers.Serializer):@@ -621,7 +608,7 @@ class ReviewFindingSerializer(serializers.Serializer):)-# Mirrors `DropDisposition`; `_dropped_finding_payload` fails loudly on a value missing here.+# Mirrors `DropDisposition`.class ReviewDropDisposition(models.TextChoices):OLD_CODE = "old_code", "On unchanged code"DEDUP_PRIOR = "dedup_prior", "Repeat of an earlier review"@@ -762,69 +749,6 @@ class _PageEnvelopeSchema(AutoSchema):return operation_id-def _completed_turn_mode(team_id: int) -> Subquery:- """The review mode on the completed turn's marker, matching what `turn_markers` puts on the row."""- content = Cast("content", models.JSONField())- return Subquery(- ReviewReportArtefact.objects.for_team(team_id)- .filter(report_id=OuterRef("id"), type=ReviewReportArtefact.ArtefactType.TURN_MARKER)- .annotate(- marker_run_index=Cast(KeyTextTransform("run_index", content), models.IntegerField()),- marker_review_mode=KeyTextTransform("review_mode", content),- )- .filter(marker_run_index=OuterRef("run_count"))- .order_by("-created_at", "-id")- .values_list("marker_review_mode")[:1]- )---def _completed_turn_published() -> Func:- """Whether `published_head_shas` has the completed turn's run index as a key (the row's `turn_published`)."""- return Coalesce(- Func(- F("published_head_shas"),- Cast("run_count", models.CharField()),- function="jsonb_exists",- output_field=models.BooleanField(),- ),- Value(False),- )---def _turn_progress(- team_id: int,- reports: list[ReviewReport],- in_progress_ids: set[str],- resolutions: dict[str, ResolutionRunState],- bundle: TurnFindingsBundle,-) -> dict[str, dict[str, Any]]:- """The in-flight review turn's stage payload for each visibly running report.-- A resolving report's live run is the resolution, not a review turn. Inferring a review stage- from the completed turn's artefacts would relabel it "deduplicating".- """- resolving_ids = {report_id for report_id, state in resolutions.items() if state.status == RESOLUTION_RESOLVING}- in_flight = [- report for report in reports if str(report.id) in in_progress_ids and str(report.id) not in resolving_ids- ]- if not in_flight:- return {}- live_heads = {str(report.id): report.head_sha for report in in_flight}- live_snapshots = snapshot_stats(team_id, live_heads)- live_turns = turn_stats(team_id, live_heads)- return {- str(report.id): progress_payload(- team_id,- report,- live_snapshots.get(str(report.id), SnapshotStats()),- live_turns.get(str(report.id), TurnStats()),- # The in-flight turn's findings live one run_index ahead of the completed watermark.- bundle.turn(str(report.id), report.run_count + 1),- )- for report in in_flight- }--def _latest_resolution_payload(summary: ResolutionSummary | None) -> dict[str, Any] | None:if summary is None:return None@@ -873,154 +797,9 @@ def _pr_status_payload(pr_status: PRStatus) -> dict[str, Any]:}-def _finding_payload(finding: ReviewIssueFinding, verdict: ValidationVerdict) -> dict[str, Any]:- return {- "title": finding.title,- "file": finding.file,- "lines": [{"start": line_range.start, "end": line_range.end} for line_range in finding.lines],- "body": finding.body,- "suggestion": finding.suggestion,- "effective_priority": effective_priority(finding.priority, verdict.adjusted_priority).value,- "reviewer_priority": finding.priority.value,- "source_perspective": finding.source_perspective,- "validator_category": verdict.category,- "validator_note": verdict.argumentation,- }---def _dropped_finding_payload(dropped: DroppedFindingArtefact, pr_url: str | None) -> dict[str, Any]:- finding = dropped.finding- comment_url = None- if pr_url and dropped.duplicate_of and dropped.duplicate_of.startswith("comment:"):- comment_url = f"{pr_url}#discussion_r{dropped.duplicate_of.removeprefix('comment:')}"- return {- "title": finding.title,- "file": finding.file,- "lines": [{"start": line_range.start, "end": line_range.end} for line_range in finding.lines],- "body": finding.body,- "suggestion": finding.suggestion,- "priority": finding.priority.value,- "source_perspective": finding.source_perspective,- "disposition": ReviewDropDisposition(dropped.disposition).value,- "duplicate_of": dropped.duplicate_of,- "comment_url": comment_url,- "rank": dropped.rank,- }---def _selection_payload(turn: TurnStats, chunks: ChunksList | None) -> dict[str, Any] | None:- """The selector's per-chunk plan for the detail drawer, joined with the chunk set's metadata."""- if turn.selection_roster is None or turn.selection_chunks is None:- return None- meta_by_id = {chunk.chunk_id: chunk for chunk in chunks.chunks} if chunks is not None else {}- rows: list[dict[str, Any]] = []- for entry in turn.selection_chunks:- meta = meta_by_id.get(entry.chunk_id)- selected = set(entry.perspectives)- rows.append(- {- "chunk_id": entry.chunk_id,- "chunk_type": meta.chunk_type if meta else None,- "files": [f.filename for f in meta.files] if meta else [],- "perspectives": [name for name in turn.selection_roster if name in selected],- "skipped": [name for name in turn.selection_roster if name not in selected],- "reason": entry.reason,- }- )- return {"roster": turn.selection_roster, "chunks": rows}---def _review_payload(- report: ReviewReport,- run_index: int,- snapshot: SnapshotStats,- turn: TurnStats,- pairs: list[tuple[ReviewIssueFinding, ValidationVerdict | None]],- marker: TurnMarker | None,- progress: dict[str, Any] | None,- resolution: ResolutionRunState | None,- latest_resolution: ResolutionSummary | None,-) -> dict[str, Any]:- """The list-row payload for one report's turn at `run_index`; the detail endpoint layers findings on top."""- counts, dismissed = finding_counts(pairs)- meta = snapshot.meta- return {- "id": report.id,- "repository": report.repository,- "pr_number": report.pr_number,- "pr_title": meta.title if meta else None,- "pr_author": meta.author if meta else None,- "additions": meta.additions if meta else None,- "deletions": meta.deletions if meta else None,- "changed_files": meta.changed_files if meta else None,- "head_branch": report.head_branch,- "github_url": report.pr_url or f"https://github.com/{report.repository}/tree/{report.head_branch}",- "run_count": report.run_count,- "last_run_at": report.last_run_at,- "published": report.published_head_sha is not None,- "turn_published": str(run_index) in (report.published_head_shas or {}),- "review_mode": marker.review_mode if marker else None,- "review_design": marker.review_design if marker else snapshot.review_design,- "status_comment_url": f"{report.pr_url}#issuecomment-{report.status_comment_id}"- if report.pr_url and report.status_comment_id- else None,- # Reads only the per-mode marker, so the list never loads findings to tell older reports apart.- "full_review_published": REVIEW_MODE_FULL in (report.published_heads_by_mode or {}),- "in_progress": progress is not None or (resolution is not None and resolution.status == RESOLUTION_RESOLVING),- "progress": progress,- "resolution": {- "resolution_status": resolution.status,- "done": resolution.done,- "total": resolution.total,- "fixed": resolution.fixed,- "needs_attention": resolution.needs_attention,- }- if resolution is not None- else None,- "latest_resolution": _latest_resolution_payload(latest_resolution),- "must_fix_count": counts[IssuePriority.MUST_FIX],- "should_fix_count": counts[IssuePriority.SHOULD_FIX],- "consider_count": counts[IssuePriority.CONSIDER],- "candidate_count": len(pairs),- "dismissed_count": dismissed,- "files_reviewed": snapshot.files_reviewed,- "chunk_count": turn.chunk_count,- "perspective_count": turn.perspective_count,- "perspective_issue_count": turn.perspective_issue_count,- "blind_spot_issue_count": turn.blind_spot_issue_count,- }---def _review_rows(team_id: int, reports: list[ReviewReport], in_progress_ids: set[str]) -> list[dict[str, Any]]:- """List-row payloads for a page of reports, with every per-row read batched across the page."""- # Row stats anchor to each report's COMPLETED turn (matching the findings' run_count); the- # in-flight progress payload alone reads the live head. Pre-column rows fall back to the live- # watermark, which is also correct for never-finalized first turns.- snapshots = snapshot_stats(team_id, {str(r.id): r.completed_head_sha or r.head_sha for r in reports})- turns = turn_stats(team_id, {str(r.id): r.completed_head_sha or r.head_sha for r in reports})- report_ids = [str(report.id) for report in reports]- bundle = load_findings_bundle(team_id=team_id, report_ids=report_ids)- resolution_map = resolution_states(team_id, reports)- progress_map = _turn_progress(team_id, reports, in_progress_ids, resolution_map, bundle)- markers = turn_markers(team_id, report_ids)- latest_resolutions = latest_resolution_summaries(team_id, reports)- items = []- for report in reports:- report_id = str(report.id)- items.append(- _review_payload(- report,- report.run_count,- snapshots.get(report_id, SnapshotStats()),- turns.get(report_id, TurnStats()),- bundle.turn(report_id, report.run_count),- markers.get((report_id, report.run_count)),- progress_map.get(report_id),- resolution_map.get(report_id),- latest_resolutions.get(report_id),- )- )- return items+_INVALID_PR_URL_ERROR = (+ "That doesn't look like a GitHub pull request URL (expected https://github.com/OWNER/REPO/pull/NUMBER)"+)class EffectiveTeamScopedKeyPermission(BasePermission):@@ -1056,27 +835,12 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetscope_object = "review_hog"permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamScopedKeyPermission]posthog_feature_flag = "review-hog"- # Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.- queryset = ReviewReport.objects.unscoped()serializer_class = ReviewRecentReviewSerializerpagination_class = Noneschema = _PageEnvelopeSchema()- def _reports(self, request: Request, scope: str = SCOPE_MINE) -> tuple[int, QuerySet[ReviewReport]]:- team_id = resolve_effective_team_id(self.team_id)- queryset = ReviewReport.objects.for_team(team_id, canonical=True)- if scope == SCOPE_MINE:- # "For you" is the union of reviews the user ran (acting user) and reviews of PRs they- # authored — a teammate-triggered review of your PR lands under THEIR acting_user, so- # without the author match the findings would never reach you. The author match rides- # the viewer's linked GitHub login (the reverse of the author→user mapping the reviewer- # runs under), case-insensitively; no linked login keeps the acting-user-only behavior.- mine = Q(acting_user_id=request.user.id)- github_login = cast(User, request.user).get_github_login()- if github_login:- mine |= Q(author_login__iexact=github_login)- queryset = queryset.filter(mine)- return team_id, queryset+ def _root_team_id(self) -> int:+ return resolve_effective_team_id(self.team_id)@extend_schema(parameters=[ReviewsListParamsSerializer],@@ -1096,43 +860,13 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetdef list(self, request: Request, **kwargs) -> Response:params = ReviewsListParamsSerializer(data=request.query_params)params.is_valid(raise_exception=True)- limit: int = params.validated_data["limit"]- # One row beyond the limit proves whether "Show more" has anything left to reveal.- probe_limit = limit + 1- team_id, queryset = self._reports(request, scope=params.validated_data["scope"])- completed = list(queryset.filter(last_run_at__isnull=False).order_by("-last_run_at")[:probe_limit])- # First-turn runs have no completed turn yet; they only surface while visibly running. A crashed- # run stays ACTIVE, so rank by report activity: ranked by creation, newer crashed runs fill the- # slice and hide an older live run.- running_first_turn = list(- queryset.filter(status=ReviewReport.Status.ACTIVE, last_run_at__isnull=True).order_by("-updated_at")[- :probe_limit- ]+ page = list_recent_reviews(+ self._root_team_id(),+ cast(User, request.user).id,+ ReviewReportScope(params.validated_data["scope"]),+ params.validated_data["limit"],)- # A re-review keeps the previous turn's last_run_at until it finalizes, so a dormant report's- # in-flight turn can rank below the completed slice — fetch running re-reviews explicitly or- # an actively reviewed PR vanishes from the list mid-run.- running_re_review = list(- queryset.filter(status=ReviewReport.Status.ACTIVE, last_run_at__isnull=False).order_by("-updated_at")[- :probe_limit- ]- )- in_progress_ids = in_progress_report_ids(team_id, running_first_turn + running_re_review + completed)- # Visibly running first (first turns, then re-reviews), then recent completed — deduped so a- # re-review that also ranks in the completed slice keeps its front position.- seen: set[str] = set()- reports: list[ReviewReport] = []- for report in [- *[report for report in running_first_turn if str(report.id) in in_progress_ids],- *[report for report in running_re_review if str(report.id) in in_progress_ids],- *completed,- ]:- if str(report.id) not in seen:- seen.add(str(report.id))- reports.append(report)- has_more = len(reports) > limit- items = _review_rows(team_id, reports[:limit], in_progress_ids)- return Response(ReviewRecentReviewsPageSerializer({"results": items, "has_more": has_more}).data)+ return Response(ReviewRecentReviewsPageSerializer(page).data)@extend_schema(parameters=[ReviewsTableParamsSerializer],@@ -1155,34 +889,18 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetparams = ReviewsTableParamsSerializer(data=request.query_params)params.is_valid(raise_exception=True)filters = params.validated_data- team_id, queryset = self._reports(request, scope=filters["scope"])- running = running_q(team_id)- # A first turn that died before completing has nothing to show, so it only appears while it runs.- queryset = queryset.filter(Q(last_run_at__isnull=False) | running)- if "repository" in filters:- queryset = queryset.filter(repository__iexact=filters["repository"])- if "review_mode" in filters:- queryset = queryset.annotate(completed_turn_mode=_completed_turn_mode(team_id)).filter(- completed_turn_mode=filters["review_mode"]- )- if filters["published"] is not None:- queryset = queryset.annotate(completed_turn_published=_completed_turn_published()).filter(- completed_turn_published=filters["published"]- )- running_count = queryset.filter(running).count()- if filters.get("status") == ReviewTableStatus.RUNNING:- queryset = queryset.filter(running)- elif filters.get("status") == ReviewTableStatus.COMPLETED:- queryset = queryset.filter(last_run_at__isnull=False).exclude(running)-- offset: int = filters["offset"]- reports = list(queryset.order_by("-updated_at", "-id")[offset : offset + filters["limit"]])- items = _review_rows(team_id, reports, in_progress_report_ids(team_id, reports))- return Response(- ReviewReviewsTablePageSerializer(- {"count": queryset.count(), "running_count": running_count, "results": items}- ).data+ page = list_reviews_table(+ self._root_team_id(),+ cast(User, request.user).id,+ ReviewReportScope(filters["scope"]),+ repository=filters.get("repository"),+ review_mode=filters.get("review_mode"),+ activity=ReviewActivityFilter(filters["status"]) if "status" in filters else None,+ published=filters["published"],+ limit=filters["limit"],+ offset=filters["offset"],)+ return Response(ReviewReviewsTablePageSerializer(page).data)@extend_schema(parameters=[PerspectiveStatsParamsSerializer],@@ -1202,44 +920,10 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetdef perspective_stats(self, request: Request, **kwargs) -> Response:params = PerspectiveStatsParamsSerializer(data=request.query_params)params.is_valid(raise_exception=True)- scope = params.validated_data["scope"]- queryset: QuerySet[ReviewReport]- if scope == PerspectiveStatsScope.OWN_DEEP:- team_id = resolve_effective_team_id(self.team_id)- # Filter before the report limit, so newer Standard reports cannot push Deep ones out of the window.- # Rows from before the per-mode watermark predate Standard reviews.- queryset = ReviewReport.objects.for_team(team_id, canonical=True).filter(- Q(published_heads_by_mode__has_key=REVIEW_MODE_FULL) | Q(published_heads_by_mode__isnull=True),- acting_user_id=request.user.id,- )- else:- team_id, queryset = self._reports(request, scope=scope)- reports = list(- queryset.filter(last_run_at__isnull=False).order_by("-last_run_at")[:PERSPECTIVE_STATS_REPORT_LIMIT]+ stats = get_review_perspective_stats(+ self._root_team_id(), cast(User, request.user).id, ReviewReportScope(params.validated_data["scope"]))- bundle = load_findings_bundle(team_id=team_id, report_ids=[str(report.id) for report in reports])- turns = [bundle.turn(str(report.id), report.run_count) for report in reports]- if scope == PerspectiveStatsScope.OWN_DEEP:- # Standard turns read none of the user's skills, so they would dilute the kept counts.- turns = [- pairs- for report, pairs in zip(reports, turns)- if completed_turn_review_mode(report, pairs) == REVIEW_MODE_FULL- ]- turns = turns[:OWN_DEEP_STATS_REVIEW_LIMIT]- stats: dict[str, dict[str, int]] = {}- for pairs in turns:- for finding, verdict in pairs:- entry = stats.setdefault(- finding.source_perspective or "unknown", {"raised": 0, "kept": 0, "dismissed": 0}- )- entry["raised"] += 1- if verdict is not None:- entry["kept" if verdict.is_valid else "dismissed"] += 1- items: list[dict[str, Any]] = [{"skill_name": skill_name, **counts} for skill_name, counts in stats.items()]- items.sort(key=lambda item: (-item["kept"], -item["raised"], item["skill_name"]))- payload = {"report_count": len(turns), "perspectives": items}- return Response(ReviewPerspectiveStatsSerializer(payload).data)+ return Response(ReviewPerspectiveStatsSerializer(stats).data)@extend_schema(request=ReviewTriggerRequestSerializer,@@ -1284,29 +968,20 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)@action(methods=["POST"], detail=False, required_scopes=["review_hog:write"])def trigger(self, request: Request, **kwargs) -> Response:- team_id = resolve_effective_team_id(self.team_id)+ team_id = self._root_team_id()serializer = ReviewTriggerRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)- try:- pr_info = PRParser().parse_github_pr_url(serializer.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,- )requested_at = timezone.now()try:- outcome = request_pr_review(+ outcome = request_pr_review_by_url(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"]),+ pr_url=serializer.validated_data["pr_url"],run_mode=serializer.validated_data["run_mode"],)+ except InvalidPullRequestURLError:+ return Response({"error": _INVALID_PR_URL_ERROR}, status=status.HTTP_400_BAD_REQUEST)except GitHubRateLimitError as e:return github_rate_limited_response(e)if outcome.error:@@ -1350,30 +1025,32 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)@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)+ team_id = self._root_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,+ pr_status = get_pr_review_status(+ team_id=team_id,+ pr_url=params.validated_data["pr_url"],+ requested_at=params.validated_data.get("requested_at"),+ run_mode=params.validated_data["run_mode"],+ head_sha=params.validated_data.get("head_sha"),)- 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"],- params.validated_data.get("head_sha"),- )+ except InvalidPullRequestURLError:+ return Response({"error": _INVALID_PR_URL_ERROR}, status=status.HTTP_400_BAD_REQUEST)return Response(ReviewPRStatusSerializer(_pr_status_payload(pr_status)).data)@extend_schema(- parameters=[ReviewDetailParamsSerializer],+ parameters=[+ # The viewset has no queryset, so the path parameter does not get its type from the model.+ OpenApiParameter(+ "id",+ OpenApiTypes.UUID,+ OpenApiParameter.PATH,+ description="A UUID string identifying this review report.",+ ),+ ReviewDetailParamsSerializer,+ ],responses={200: OpenApiResponse(response=ReviewDetailSerializer,@@ -1393,71 +1070,15 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetreport_uuid = uuid.UUID(str(pk))except ValueError:raise NotFound("Review not found.")- # Project-wide on purpose: the detail must open for any review the everyone-scope list shows.- team_id, queryset = self._reports(request, scope=SCOPE_EVERYONE)- # Detail describes a completed turn — a first run still in flight has nothing to show yet.- report = queryset.filter(id=report_uuid, last_run_at__isnull=False).first()- if report is None:- raise NotFound("Review not found.")-params = ReviewDetailParamsSerializer(data=request.query_params)params.is_valid(raise_exception=True)- run_index: int = params.validated_data.get("run_index", report.run_count)- if not 1 <= run_index <= report.run_count:+ try:+ detail = get_review_detail(self._root_team_id(), report_uuid, params.validated_data.get("run_index"))+ except ReviewTurnNotFoundError:raise NotFound("No completed review turn with that run_index.")- is_latest = run_index == report.run_count-- report_id = str(report.id)- marker = turn_markers(team_id, [report_id]).get((report_id, run_index))- # Everything the detail returns (stats, chunk set, link-anchoring head) describes the same- # completed turn the findings come from, never an in-flight turn's watermark.- if is_latest:- turn_head = report.completed_head_sha or report.head_sha- else:- turn_head = (marker.head_sha if marker else None) or (report.published_head_shas or {}).get(str(run_index))- snapshots = snapshot_stats(team_id, {report_id: turn_head})- turns = turn_stats(team_id, {report_id: turn_head})- bundle = load_findings_bundle(team_id=team_id, report_ids=[report_id])- pairs = bundle.turn(report_id, run_index)- chunk_set = load_chunk_set(team_id=team_id, report_id=report_id, head_sha=turn_head) if turn_head else None- resolutions = resolution_states(team_id, [report])- in_progress_ids = in_progress_report_ids(team_id, [report])- progress = _turn_progress(team_id, [report], in_progress_ids, resolutions, bundle).get(report_id)-- def sort_key(payload: dict[str, Any]) -> tuple[int, str]:- return (_PRIORITY_DISPLAY_RANK[IssuePriority(payload["effective_priority"])], payload["file"])-- valid = [_finding_payload(f, v) for f, v in pairs if v is not None and v.is_valid]- dismissed = [_finding_payload(f, v) for f, v in pairs if v is not None and not v.is_valid]- payload = {- **_review_payload(- report,- run_index,- snapshots.get(report_id, SnapshotStats()),- turns.get(report_id, TurnStats()),- pairs,- marker,- progress,- resolutions.get(report_id),- latest_resolution_summaries(team_id, [report]).get(report_id),- ),- "run_index": run_index,- "head_sha": turn_head,- "report_markdown": report.report_markdown if is_latest else None,- "run_urgency_threshold": (- report.run_urgency_threshold- if is_latest- else (report.published_urgency_thresholds or {}).get(str(run_index))- )- or None,- "findings": sorted(valid, key=sort_key),- "dismissed_findings": sorted(dismissed, key=sort_key),- "dropped_findings": [- _dropped_finding_payload(dropped, report.pr_url)- for dropped in load_dropped_findings(- team_id=team_id, report_id=report_id, run_index=run_index, head_sha=turn_head- )- ],- "perspective_selection": _selection_payload(turns.get(report_id, TurnStats()), chunk_set),- }- return Response(ReviewDetailSerializer(payload).data)+ except ReviewNotFoundError:+ raise NotFound("Review not found.")+ # The detail serializer extends the list row, so the row's fields sit next to the detail's own.+ data = dataclasses.asdict(detail)+ data.update(data.pop("review"))+ return Response(ReviewDetailSerializer(data).data)diff --git a/products/review_hog/backend/receivers.py b/products/review_hog/backend/receivers.pyindex daa2b837320a..ebf52b5c62f3 100644--- a/products/review_hog/backend/receivers.py+++ b/products/review_hog/backend/receivers.py@@ -1,6 +1,6 @@"""The inbox trigger: auto-review self-driving (Signals) implementations when they produce a PR.-A `post_save` receiver on `tasks.TaskRun` (resolved via the app registry — tasks never imports+A `post_save` receiver on `tasks.TaskRun`, connected through the tasks facade hook (tasks never importsreview_hog, keeping every product edge in the existing direction). The trigger is the save thatrecords a review target on the run's `output` — NOT run completion: on the tasks architecture asuccessful run deliberately never leaves `in_progress` (it stays followable and the PR follow-up@@ -39,9 +39,7 @@ import jsonimport loggingfrom typing import Any-from django.apps import apps as django_appsfrom django.db import transaction-from django.db.models.signals import post_savefrom products.review_hog.backend.models import ReviewUserSettingsfrom products.review_hog.backend.preferences import ReviewPreferences@@ -54,6 +52,7 @@ from products.stamphog.backend.facade.review_evidence import (ReviewEvidenceState,register_review_evidence_provider,)+from products.tasks.backend.facade.task_run_signals import connect_task_run_post_save# This module loads during django.setup() (AppConfig.ready() wires the receiver), and# posthog/test/repo_invariants/test_startup_import_budget.py forbids temporalio/modal/openai/anthropic at setup —@@ -68,11 +67,7 @@ REVIEWER_NAME = "PostHog Review"def connect() -> None:"""Wire the TaskRun-save receiver and the stamphog hooks; called once from `AppConfig.ready()`."""- post_save.connect(- handle_task_run_saved,- sender=django_apps.get_model("tasks", "TaskRun"),- dispatch_uid="review_hog_task_run_completed",- )+ connect_task_run_post_save(handle_task_run_saved, dispatch_uid="review_hog_task_run_completed")# Stamphog re-checks this toggle before re-reviewing a self-driving PR. It gets the resolver# through a hook because importing review_hog from stamphog would be a dependency cycle.register_inbox_acting_reviewer_resolver(resolve_stamphog_acting_reviewer)diff --git a/products/review_hog/backend/review_listing.py b/products/review_hog/backend/review_listing.pynew file mode 100644index 000000000000..b6a39e385fe7--- /dev/null+++ b/products/review_hog/backend/review_listing.py@@ -0,0 +1,487 @@+"""The review list, the review table, one review's detail, and the perspective stats.++Every read is batched across the page of reports it describes, and returns facade contracts.+"""++from uuid import UUID++from django.db import models+from django.db.models import F, Func, OuterRef, Q, QuerySet, Subquery, Value+from django.db.models.fields.json import KeyTextTransform+from django.db.models.functions import Cast, Coalesce++from posthog.models.user import User++from products.review_hog.backend.facade.contracts import (+ OWN_DEEP_STATS_REVIEW_LIMIT,+ RESOLUTION_RESOLVING,+ REVIEW_MODE_FULL,+ ResolutionRunState,+ ResolutionSummary,+ ReviewDetail,+ ReviewDroppedFinding,+ ReviewFinding,+ ReviewLineRange,+ ReviewNotFoundError,+ ReviewPerspectiveSelection,+ ReviewPerspectiveStat,+ ReviewPerspectiveStats,+ ReviewProgress,+ ReviewSelectionChunk,+ ReviewSummary,+ ReviewSummaryPage,+ ReviewTablePage,+ ReviewTurnNotFoundError,+)+from products.review_hog.backend.facade.enums import IssuePriority, ReviewActivityFilter, ReviewReportScope+from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact+from products.review_hog.backend.reviewer.artefact_content import (+ DroppedFindingArtefact,+ ReviewIssueFinding,+ ValidationVerdict,+)+from products.review_hog.backend.reviewer.constants import effective_priority+from products.review_hog.backend.reviewer.models.split_pr_into_chunks import ChunksList+from products.review_hog.backend.reviewer.persistence import (+ TurnFindingsBundle,+ load_chunk_set,+ load_dropped_findings,+ load_findings_bundle,+)+from products.review_hog.backend.reviewer.progress import (+ SnapshotStats,+ TurnMarker,+ TurnStats,+ finding_counts,+ in_progress_report_ids,+ latest_resolution_summaries,+ progress_payload,+ resolution_states,+ running_q,+ snapshot_stats,+ turn_markers,+ turn_stats,+)+from products.review_hog.backend.reviewer.review_state import completed_turn_review_mode++# Effectiveness stats aggregate deeper than the list — enough history for survival rates to mean something.+PERSPECTIVE_STATS_REPORT_LIMIT = 50++# Display order for the detail view: most urgent first.+_PRIORITY_DISPLAY_RANK = {IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 1, IssuePriority.CONSIDER: 2}+++def _completed_turn_mode(team_id: int) -> Subquery:+ """The review mode on the completed turn's marker, matching what `turn_markers` puts on the row."""+ content = Cast("content", models.JSONField())+ return Subquery(+ ReviewReportArtefact.objects.for_team(team_id)+ .filter(report_id=OuterRef("id"), type=ReviewReportArtefact.ArtefactType.TURN_MARKER)+ .annotate(+ marker_run_index=Cast(KeyTextTransform("run_index", content), models.IntegerField()),+ marker_review_mode=KeyTextTransform("review_mode", content),+ )+ .filter(marker_run_index=OuterRef("run_count"))+ .order_by("-created_at", "-id")+ .values_list("marker_review_mode")[:1]+ )+++def _completed_turn_published() -> Func:+ """Whether `published_head_shas` has the completed turn's run index as a key (the row's `turn_published`)."""+ return Coalesce(+ Func(+ F("published_head_shas"),+ Cast("run_count", models.CharField()),+ function="jsonb_exists",+ output_field=models.BooleanField(),+ ),+ Value(False),+ )+++def _turn_progress(+ team_id: int,+ reports: list[ReviewReport],+ in_progress_ids: set[str],+ resolutions: dict[str, ResolutionRunState],+ bundle: TurnFindingsBundle,+) -> dict[str, ReviewProgress]:+ """The in-flight review turn's stage for each visibly running report.++ A resolving report's live run is the resolution, not a review turn. Inferring a review stage+ from the completed turn's artefacts would relabel it "deduplicating".+ """+ resolving_ids = {report_id for report_id, state in resolutions.items() if state.status == RESOLUTION_RESOLVING}+ in_flight = [+ report for report in reports if str(report.id) in in_progress_ids and str(report.id) not in resolving_ids+ ]+ if not in_flight:+ return {}+ live_heads = {str(report.id): report.head_sha for report in in_flight}+ live_snapshots = snapshot_stats(team_id, live_heads)+ live_turns = turn_stats(team_id, live_heads)+ return {+ str(report.id): ReviewProgress(+ **progress_payload(+ team_id,+ report,+ live_snapshots.get(str(report.id), SnapshotStats()),+ live_turns.get(str(report.id), TurnStats()),+ # The in-flight turn's findings live one run_index ahead of the completed watermark.+ bundle.turn(str(report.id), report.run_count + 1),+ )+ )+ for report in in_flight+ }+++def _line_ranges(finding: ReviewIssueFinding) -> list[ReviewLineRange]:+ return [ReviewLineRange(start=line_range.start, end=line_range.end) for line_range in finding.lines]+++def _finding(finding: ReviewIssueFinding, verdict: ValidationVerdict) -> ReviewFinding:+ return ReviewFinding(+ title=finding.title,+ file=finding.file,+ lines=_line_ranges(finding),+ body=finding.body,+ suggestion=finding.suggestion,+ effective_priority=effective_priority(finding.priority, verdict.adjusted_priority).value,+ reviewer_priority=finding.priority.value,+ source_perspective=finding.source_perspective,+ validator_category=verdict.category,+ validator_note=verdict.argumentation,+ )+++def _dropped_finding(dropped: DroppedFindingArtefact, pr_url: str | None) -> ReviewDroppedFinding:+ finding = dropped.finding+ comment_url = None+ if pr_url and dropped.duplicate_of and dropped.duplicate_of.startswith("comment:"):+ comment_url = f"{pr_url}#discussion_r{dropped.duplicate_of.removeprefix('comment:')}"+ return ReviewDroppedFinding(+ title=finding.title,+ file=finding.file,+ lines=_line_ranges(finding),+ body=finding.body,+ suggestion=finding.suggestion,+ priority=finding.priority.value,+ source_perspective=finding.source_perspective,+ disposition=dropped.disposition,+ duplicate_of=dropped.duplicate_of,+ comment_url=comment_url,+ rank=dropped.rank,+ )+++def _selection(turn: TurnStats, chunks: ChunksList | None) -> ReviewPerspectiveSelection | None:+ """The selector's per-chunk plan for the detail drawer, joined with the chunk set's metadata."""+ if turn.selection_roster is None or turn.selection_chunks is None:+ return None+ meta_by_id = {chunk.chunk_id: chunk for chunk in chunks.chunks} if chunks is not None else {}+ rows: list[ReviewSelectionChunk] = []+ for entry in turn.selection_chunks:+ meta = meta_by_id.get(entry.chunk_id)+ selected = set(entry.perspectives)+ rows.append(+ ReviewSelectionChunk(+ chunk_id=entry.chunk_id,+ chunk_type=meta.chunk_type if meta else None,+ files=[f.filename for f in meta.files] if meta else [],+ perspectives=[name for name in turn.selection_roster if name in selected],+ skipped=[name for name in turn.selection_roster if name not in selected],+ reason=entry.reason,+ )+ )+ return ReviewPerspectiveSelection(roster=turn.selection_roster, chunks=rows)+++def _summary(+ report: ReviewReport,+ run_index: int,+ snapshot: SnapshotStats,+ turn: TurnStats,+ pairs: list[tuple[ReviewIssueFinding, ValidationVerdict | None]],+ marker: TurnMarker | None,+ progress: ReviewProgress | None,+ resolution: ResolutionRunState | None,+ latest_resolution: ResolutionSummary | None,+) -> ReviewSummary:+ """The list row for one report's turn at `run_index`; the detail layers findings on top."""+ counts, dismissed = finding_counts(pairs)+ meta = snapshot.meta+ return ReviewSummary(+ id=report.id,+ repository=report.repository,+ pr_number=report.pr_number,+ pr_title=meta.title if meta else None,+ pr_author=meta.author if meta else None,+ additions=meta.additions if meta else None,+ deletions=meta.deletions if meta else None,+ changed_files=meta.changed_files if meta else None,+ head_branch=report.head_branch,+ github_url=report.pr_url or f"https://github.com/{report.repository}/tree/{report.head_branch}",+ run_count=report.run_count,+ last_run_at=report.last_run_at,+ published=report.published_head_sha is not None,+ turn_published=str(run_index) in (report.published_head_shas or {}),+ review_mode=marker.review_mode if marker else None,+ review_design=marker.review_design if marker else snapshot.review_design,+ status_comment_url=f"{report.pr_url}#issuecomment-{report.status_comment_id}"+ if report.pr_url and report.status_comment_id+ else None,+ # Reads only the per-mode marker, so the list never loads findings to tell older reports apart.+ full_review_published=REVIEW_MODE_FULL in (report.published_heads_by_mode or {}),+ in_progress=progress is not None or (resolution is not None and resolution.status == RESOLUTION_RESOLVING),+ progress=progress,+ resolution=resolution,+ latest_resolution=latest_resolution,+ must_fix_count=counts[IssuePriority.MUST_FIX],+ should_fix_count=counts[IssuePriority.SHOULD_FIX],+ consider_count=counts[IssuePriority.CONSIDER],+ candidate_count=len(pairs),+ dismissed_count=dismissed,+ files_reviewed=snapshot.files_reviewed,+ chunk_count=turn.chunk_count,+ perspective_count=turn.perspective_count,+ perspective_issue_count=turn.perspective_issue_count,+ blind_spot_issue_count=turn.blind_spot_issue_count,+ )+++def _summaries(team_id: int, reports: list[ReviewReport], in_progress_ids: set[str]) -> list[ReviewSummary]:+ """List rows for a page of reports, with every per-row read batched across the page."""+ # Row stats anchor to each report's COMPLETED turn (matching the findings' run_count); the+ # in-flight progress payload alone reads the live head. Pre-column rows fall back to the live+ # watermark, which is also correct for never-finalized first turns.+ snapshots = snapshot_stats(team_id, {str(r.id): r.completed_head_sha or r.head_sha for r in reports})+ turns = turn_stats(team_id, {str(r.id): r.completed_head_sha or r.head_sha for r in reports})+ report_ids = [str(report.id) for report in reports]+ bundle = load_findings_bundle(team_id=team_id, report_ids=report_ids)+ resolution_map = resolution_states(team_id, reports)+ progress_map = _turn_progress(team_id, reports, in_progress_ids, resolution_map, bundle)+ markers = turn_markers(team_id, report_ids)+ latest_resolutions = latest_resolution_summaries(team_id, reports)+ items = []+ for report in reports:+ report_id = str(report.id)+ items.append(+ _summary(+ report,+ report.run_count,+ snapshots.get(report_id, SnapshotStats()),+ turns.get(report_id, TurnStats()),+ bundle.turn(report_id, report.run_count),+ markers.get((report_id, report.run_count)),+ progress_map.get(report_id),+ resolution_map.get(report_id),+ latest_resolutions.get(report_id),+ )+ )+ return items+++def _display_order(finding: ReviewFinding) -> tuple[int, str]:+ return (_PRIORITY_DISPLAY_RANK[IssuePriority(finding.effective_priority)], finding.file)+++class ReviewListing:+ """Reads of the review reports of one project. `team_id` is the root project id."""++ def __init__(self, team_id: int) -> None:+ self.team_id = team_id++ def _reports(self, user_id: int, scope: ReviewReportScope) -> QuerySet[ReviewReport]:+ queryset = ReviewReport.objects.for_team(self.team_id, canonical=True)+ if scope == ReviewReportScope.MINE:+ # "For you" is the union of reviews the user ran (acting user) and reviews of PRs they+ # authored — a teammate-triggered review of your PR lands under THEIR acting_user, so+ # without the author match the findings would never reach you. The author match rides+ # the viewer's linked GitHub login (the reverse of the author→user mapping the reviewer+ # runs under), case-insensitively; no linked login keeps the acting-user-only behavior.+ mine = Q(acting_user_id=user_id)+ github_login = User.objects.get(id=user_id).get_github_login()+ if github_login:+ mine |= Q(author_login__iexact=github_login)+ queryset = queryset.filter(mine)+ return queryset++ def recent(self, user_id: int, scope: ReviewReportScope, limit: int) -> ReviewSummaryPage:+ # One row beyond the limit proves whether "Show more" has anything left to reveal.+ probe_limit = limit + 1+ queryset = self._reports(user_id, scope)+ completed = list(queryset.filter(last_run_at__isnull=False).order_by("-last_run_at")[:probe_limit])+ # First-turn runs have no completed turn yet; they only surface while visibly running. A crashed+ # run stays ACTIVE, so rank by report activity: ranked by creation, newer crashed runs fill the+ # slice and hide an older live run.+ running_first_turn = list(+ queryset.filter(status=ReviewReport.Status.ACTIVE, last_run_at__isnull=True).order_by("-updated_at")[+ :probe_limit+ ]+ )+ # A re-review keeps the previous turn's last_run_at until it finalizes, so a dormant report's+ # in-flight turn can rank below the completed slice — fetch running re-reviews explicitly or+ # an actively reviewed PR vanishes from the list mid-run.+ running_re_review = list(+ queryset.filter(status=ReviewReport.Status.ACTIVE, last_run_at__isnull=False).order_by("-updated_at")[+ :probe_limit+ ]+ )+ in_progress_ids = in_progress_report_ids(self.team_id, running_first_turn + running_re_review + completed)+ # Visibly running first (first turns, then re-reviews), then recent completed — deduped so a+ # re-review that also ranks in the completed slice keeps its front position.+ seen: set[str] = set()+ reports: list[ReviewReport] = []+ for report in [+ *[report for report in running_first_turn if str(report.id) in in_progress_ids],+ *[report for report in running_re_review if str(report.id) in in_progress_ids],+ *completed,+ ]:+ if str(report.id) not in seen:+ seen.add(str(report.id))+ reports.append(report)+ return ReviewSummaryPage(+ results=_summaries(self.team_id, reports[:limit], in_progress_ids), has_more=len(reports) > limit+ )++ def table(+ self,+ user_id: int,+ scope: ReviewReportScope,+ *,+ repository: str | None,+ review_mode: str | None,+ activity: ReviewActivityFilter | None,+ published: bool | None,+ limit: int,+ offset: int,+ ) -> ReviewTablePage:+ queryset = self._reports(user_id, scope)+ running = running_q(self.team_id)+ # A first turn that died before completing has nothing to show, so it only appears while it runs.+ queryset = queryset.filter(Q(last_run_at__isnull=False) | running)+ if repository is not None:+ queryset = queryset.filter(repository__iexact=repository)+ if review_mode is not None:+ queryset = queryset.annotate(completed_turn_mode=_completed_turn_mode(self.team_id)).filter(+ completed_turn_mode=review_mode+ )+ if published is not None:+ queryset = queryset.annotate(completed_turn_published=_completed_turn_published()).filter(+ completed_turn_published=published+ )+ running_count = queryset.filter(running).count()+ if activity == ReviewActivityFilter.RUNNING:+ queryset = queryset.filter(running)+ elif activity == ReviewActivityFilter.COMPLETED:+ queryset = queryset.filter(last_run_at__isnull=False).exclude(running)++ reports = list(queryset.order_by("-updated_at", "-id")[offset : offset + limit])+ results = _summaries(self.team_id, reports, in_progress_report_ids(self.team_id, reports))+ return ReviewTablePage(count=queryset.count(), running_count=running_count, results=results)++ def perspective_stats(self, user_id: int, scope: ReviewReportScope) -> ReviewPerspectiveStats:+ queryset: QuerySet[ReviewReport]+ if scope == ReviewReportScope.OWN_DEEP:+ # Filter before the report limit, so newer Standard reports cannot push Deep ones out of the window.+ # Rows from before the per-mode watermark predate Standard reviews.+ queryset = ReviewReport.objects.for_team(self.team_id, canonical=True).filter(+ Q(published_heads_by_mode__has_key=REVIEW_MODE_FULL) | Q(published_heads_by_mode__isnull=True),+ acting_user_id=user_id,+ )+ else:+ queryset = self._reports(user_id, scope)+ reports = list(+ queryset.filter(last_run_at__isnull=False).order_by("-last_run_at")[:PERSPECTIVE_STATS_REPORT_LIMIT]+ )+ bundle = load_findings_bundle(team_id=self.team_id, report_ids=[str(report.id) for report in reports])+ turns = [bundle.turn(str(report.id), report.run_count) for report in reports]+ if scope == ReviewReportScope.OWN_DEEP:+ # Standard turns read none of the user's skills, so they would dilute the kept counts.+ turns = [+ pairs+ for report, pairs in zip(reports, turns)+ if completed_turn_review_mode(report, pairs) == REVIEW_MODE_FULL+ ]+ turns = turns[:OWN_DEEP_STATS_REVIEW_LIMIT]+ stats: dict[str, dict[str, int]] = {}+ for pairs in turns:+ for finding, verdict in pairs:+ entry = stats.setdefault(+ finding.source_perspective or "unknown", {"raised": 0, "kept": 0, "dismissed": 0}+ )+ entry["raised"] += 1+ if verdict is not None:+ entry["kept" if verdict.is_valid else "dismissed"] += 1+ items = [ReviewPerspectiveStat(skill_name=skill_name, **counts) for skill_name, counts in stats.items()]+ items.sort(key=lambda item: (-item.kept, -item.raised, item.skill_name))+ return ReviewPerspectiveStats(report_count=len(turns), perspectives=items)++ def detail(self, report_id: UUID, run_index: int | None) -> ReviewDetail:+ # Project-wide on purpose: the detail must open for any review the everyone-scope list shows.+ # Detail describes a completed turn — a first run still in flight has nothing to show yet.+ report = (+ ReviewReport.objects.for_team(self.team_id, canonical=True)+ .filter(id=report_id, last_run_at__isnull=False)+ .first()+ )+ if report is None:+ raise ReviewNotFoundError(f"No completed review {report_id}.")+ if run_index is None:+ run_index = report.run_count+ if not 1 <= run_index <= report.run_count:+ raise ReviewTurnNotFoundError(f"Review {report_id} has no completed turn {run_index}.")+ is_latest = run_index == report.run_count++ team_id = self.team_id+ key = str(report.id)+ marker = turn_markers(team_id, [key]).get((key, run_index))+ # Everything the detail returns (stats, chunk set, link-anchoring head) describes the same+ # completed turn the findings come from, never an in-flight turn's watermark.+ if is_latest:+ turn_head = report.completed_head_sha or report.head_sha+ else:+ turn_head = (marker.head_sha if marker else None) or (report.published_head_shas or {}).get(str(run_index))+ snapshots = snapshot_stats(team_id, {key: turn_head})+ turns = turn_stats(team_id, {key: turn_head})+ bundle = load_findings_bundle(team_id=team_id, report_ids=[key])+ pairs = bundle.turn(key, run_index)+ chunk_set = load_chunk_set(team_id=team_id, report_id=key, head_sha=turn_head) if turn_head else None+ resolutions = resolution_states(team_id, [report])+ in_progress_ids = in_progress_report_ids(team_id, [report])+ progress = _turn_progress(team_id, [report], in_progress_ids, resolutions, bundle).get(key)++ valid = [_finding(f, v) for f, v in pairs if v is not None and v.is_valid]+ dismissed = [_finding(f, v) for f, v in pairs if v is not None and not v.is_valid]+ run_urgency_threshold: str | None = (+ report.run_urgency_threshold+ if is_latest+ else (report.published_urgency_thresholds or {}).get(str(run_index))+ )+ return ReviewDetail(+ review=_summary(+ report,+ run_index,+ snapshots.get(key, SnapshotStats()),+ turns.get(key, TurnStats()),+ pairs,+ marker,+ progress,+ resolutions.get(key),+ latest_resolution_summaries(team_id, [report]).get(key),+ ),+ run_index=run_index,+ head_sha=turn_head,+ perspective_selection=_selection(turns.get(key, TurnStats()), chunk_set),+ report_markdown=report.report_markdown if is_latest else None,+ run_urgency_threshold=run_urgency_threshold or None,+ findings=sorted(valid, key=_display_order),+ dismissed_findings=sorted(dismissed, key=_display_order),+ dropped_findings=[+ _dropped_finding(dropped, report.pr_url)+ for dropped in load_dropped_findings(+ team_id=team_id, report_id=key, run_index=run_index, head_sha=turn_head+ )+ ],+ )diff --git a/products/review_hog/backend/reviewer/artefact_content.py b/products/review_hog/backend/reviewer/artefact_content.pyindex 813b1637884d..86d006a913ae 100644--- a/products/review_hog/backend/reviewer/artefact_content.py+++ b/products/review_hog/backend/reviewer/artefact_content.py@@ -17,6 +17,7 @@ from typing import Any, Literal, castfrom pydantic import BaseModel, Field, ValidationError, field_validator+from products.review_hog.backend.facade.contracts import ReviewIssueCategoryfrom products.review_hog.backend.reviewer.models.github_meta import PRComment, PRFile, PRMetadatafrom products.review_hog.backend.reviewer.models.issues_review import (DropDisposition,@@ -36,20 +37,6 @@ from products.signals.backend.artefact_schemas import (TaskRunArtefact,)-# Mirrors `IssueValidation.category` (the live LLM contract); redefined here so the durable-# artefact shape doesn't drift with the regenerated review-tool schema.-ReviewIssueCategory = Literal[- "bug",- "security",- "performance",- "code_quality",- "best_practice",- "documentation",- "testing",- "accessibility",- "compatibility",-]-class ReviewIssueFinding(BaseModel):"""Content schema for an `issue_finding` artefact: one durable review finding.diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.pyindex 5354b5117a53..632804dbc334 100644--- a/products/review_hog/backend/reviewer/constants.py+++ b/products/review_hog/backend/reviewer/constants.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Finalfrom posthog.dataclasses import frozen+from products.review_hog.backend.facade.contracts import REVIEW_MODE_FLASH, REVIEW_MODE_FULLfrom products.review_hog.backend.reviewer.models.issues_review import IssuePriority, ReportedPriorityfrom products.review_hog.backend.reviewer.review_design import (REVIEW_DESIGN_PIPELINE,@@ -73,13 +74,6 @@ DEFAULT_REVIEW_ARM = ReviewArm()-# REVIEW MODE-# What a single turn runs on, chosen per trigger and carried in the workflow input, never persisted on-# the report: a flash turn must not change what the PR's next normal review runs on. Plain strings so-# Temporal payloads stay forward/backward-compatible across deploys, like the trigger sources.-REVIEW_MODE_FULL = "full"-REVIEW_MODE_FLASH = "flash"-# REVIEW DESIGN# The design a Flash turn runs on by default. Full turns always run on the pipeline. The# `reviewhog-flash-pipeline-kill-switch` feature flag overrides it without a deploydiff --git a/products/review_hog/backend/reviewer/models/issues_review.py b/products/review_hog/backend/reviewer/models/issues_review.pyindex 35442e721a5b..ce9bfb429800 100644--- a/products/review_hog/backend/reviewer/models/issues_review.py+++ b/products/review_hog/backend/reviewer/models/issues_review.py@@ -7,16 +7,10 @@ from pydantic.json_schema import SkipJsonSchemafrom posthog.dataclasses import frozen-logger = logging.getLogger(__name__)---# Issue priority enum-class IssuePriority(Enum):- """Priority levels for code review issues."""+from products.review_hog.backend.facade.contracts import DropDisposition+from products.review_hog.backend.facade.enums import IssuePriority- MUST_FIX = "must_fix" # Critical issues that should block merge- SHOULD_FIX = "should_fix" # Significant improvements needed- CONSIDER = "consider" # Nice-to-have improvements+logger = logging.getLogger(__name__)# The single-agent reviewer's own scale. Storage folds P0 and P1 into `IssuePriority.MUST_FIX`.@@ -77,22 +71,6 @@ class Issue(BaseModel):)-# Why a single-agent turn drops a finding. A `dedup_*` drop repeats an earlier turn's finding, a main-# finding (anchor), or a finding of its own session or lens (sibling). Only records from before Flash-# stopped reading PR comments carry `dedup_comment`. `cap` is the cut in `compose_flash_findings`, and-# `budget` the cut the pull request's finding budget adds on top (`finding_budget.py`).-# `old_code` is a follow-up turn's P3 finding on code that did not change since the last reviewed head.-DropDisposition = Literal[- "old_code",- "dedup_prior",- "dedup_comment",- "dedup_anchor",- "dedup_sibling",- "cap",- "budget",-]--@frozenclass DroppedIssue:"""A finding a single-agent turn does not keep, and why."""diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.pyindex bf581b00dd71..8425908ffb20 100644--- a/products/review_hog/backend/reviewer/progress.py+++ b/products/review_hog/backend/reviewer/progress.py@@ -37,6 +37,13 @@ from pydantic import ValidationErrorfrom posthog.dataclasses import frozen+from products.review_hog.backend.facade.contracts import (+ RESOLUTION_COMPLETED,+ RESOLUTION_RESOLVING,+ RESOLUTION_STOPPED,+ ResolutionRunState,+ ResolutionSummary,+)from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact, ReviewSkillConfigfrom products.review_hog.backend.reviewer.artefact_content import (RUN_OUTCOME_NOTE_AUTHOR,@@ -59,27 +66,10 @@ from products.signals.backend.artefact_attribution import ArtefactAttributionlogger = logging.getLogger(__name__)-REVIEW_STAGES = [- "fetching",- "chunking",- "selecting",- "reviewing",- "deduplicating",- "validating",- "finalizing",- # The single-agent design writes no chunk, selection, or validator state, so it has its own shorter sequence.- "single_agent_preparing",- "single_agent_reviewing",- "single_agent_finalizing",-]-# Artefacts and activity heartbeats keep active reviews fresh; stopped runs must age out so the UI# does not show a live spinner forever. A resolution run with no closing note then reads as stopped.IN_PROGRESS_STALE_AFTER = timedelta(minutes=30)-RESOLUTION_RESOLVING = "resolving"-RESOLUTION_STOPPED = "stopped"-RESOLUTION_COMPLETED = "completed"# The `author` the resolution stage stamps on its closing run `note` — the completion marker the# state derivation looks for. Kept here so the writer (temporal/resolution.py) and this reader# can't drift apart.@@ -427,30 +417,6 @@ def run_outcome_markers(return markers-@frozen-class ResolutionRunState:- """The report's latest resolution run, as the list row and the drawer render it."""-- status: str # RESOLUTION_RESOLVING | RESOLUTION_STOPPED- done: int = 0- total: int = 0- fixed: int = 0- needs_attention: int = 0---@frozen-class ResolutionSummary:- """The report's latest resolution run, completed runs included, as an API reader reports it."""-- status: str # RESOLUTION_RESOLVING | RESOLUTION_STOPPED | RESOLUTION_COMPLETED- started_at: datetime- completed_at: datetime | None- total: int- fixed: int- needs_attention: int- commits: tuple[str, ...]--@frozenclass _ThreadVerdictRow:outcome: strdiff --git a/products/review_hog/backend/reviewer/review_design.py b/products/review_hog/backend/reviewer/review_design.pyindex 4ffa68e20fe9..7223650b0592 100644--- a/products/review_hog/backend/reviewer/review_design.py+++ b/products/review_hog/backend/reviewer/review_design.py@@ -1,9 +1,9 @@-# Kept free of imports: `models.py` reaches these through `artefact_content.py`, so anything imported-# here lands on the `django.setup()` path.--# How a turn finds its issues, decided per turn at fetch. Plain strings, like the review mode.-REVIEW_DESIGN_PIPELINE = "pipeline"-REVIEW_DESIGN_SINGLE_AGENT = "single_agent"+# `models.py` reaches these through `artefact_content.py`, so anything imported here lands on the+# `django.setup()` path. The facade contracts import nothing from Django.+from products.review_hog.backend.facade.contracts import (+ REVIEW_DESIGN_PIPELINE as REVIEW_DESIGN_PIPELINE,+ REVIEW_DESIGN_SINGLE_AGENT as REVIEW_DESIGN_SINGLE_AGENT,+)# Why a turn runs on its design. The review-started event reports it next to the design.REVIEW_DESIGN_REASON_FULL_MODE = "full_mode"diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.pyindex 7708d7ea0faf..2138810aaae9 100644--- a/products/review_hog/backend/tests/test_reviews_api.py+++ b/products/review_hog/backend/tests/test_reviews_api.py@@ -1225,7 +1225,7 @@ class TestRecentReviewsAPI(APIBaseTest):last_run_at=datetime(2026, 8, 1, tzinfo=UTC))- with patch("products.review_hog.backend.presentation.views.reviews.PERSPECTIVE_STATS_REPORT_LIMIT", 2):+ with patch("products.review_hog.backend.review_listing.PERSPECTIVE_STATS_REPORT_LIMIT", 2):res = self.client.get(f"{self.url}perspective_stats/?scope=own_deep")assert res.status_code == 200diff --git a/products/review_hog/package.json b/products/review_hog/package.jsonindex 2ef012192f39..0f6bd5229922 100644--- a/products/review_hog/package.json+++ b/products/review_hog/package.json@@ -1,7 +1,8 @@{"name": "@posthog/products-review-hog","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/reviewer/tests -v --tb=short"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/reviewer/tests -v --tb=short",+ "backend:contract-check": "echo 'Contract files unchanged'"},"dependencies": {"kea": "catalog:",diff --git a/products/review_hog/turbo.json b/products/review_hog/turbo.jsonnew file mode 100644index 000000000000..908ed09e3c03--- /dev/null+++ b/products/review_hog/turbo.json@@ -0,0 +1,19 @@+{+ "extends": ["//"],+ "tasks": {+ "backend:contract-check": {+ "inputs": [+ "backend/facade/**",+ "backend/presentation/**",+ "backend/routes.py",+ "backend/webhook_consumers.py",+ "backend/tasks/**",+ "backend/temporal/**",+ "backend/models.py",+ "backend/migrations/**"+ ],+ "outputs": [],+ "cache": true+ }+ }+}diff --git a/pyproject.toml b/pyproject.tomlindex 77b55ff2cbbc..cad9d47188ba 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -644,19 +644,6 @@ ignore_imports = ["products.mcp_store.backend.presentation.views -> products.mcp_store.backend.tools","products.notifications.backend.presentation.views -> products.notifications.backend.cache","products.notifications.backend.presentation.views -> products.notifications.backend.models",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.models",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.pr_status",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.preferences",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.requested_reviews",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.artefact_content",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.constants",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.models.issues_review",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.models.split_pr_into_chunks",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.persistence",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.progress",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.review_design",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.review_state",- "products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.tools.github_meta","products.tracing.backend.presentation.views -> products.tracing.backend.logic","products.tracing.backend.presentation.views -> products.tracing.backend.sparkline_query_runner","products.tracing.backend.presentation.views -> products.tracing.backend.has_spans_query_runner",