Skip to content

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

feat(review_hog): add turn mode, resolve outcome and turn picker to review reads (#114891)

Julian Beza26e239253ed
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index 96dc9fab13ac..c9cab7983ce2 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -23,6 +23,7 @@ from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
+from products.review_hog.backend.preferences import UrgencyThreshold
from products.review_hog.backend.requested_reviews import (
RUN_MODE_FLASH,
RUN_MODE_RESOLVE_ONLY,
@@ -41,18 +42,23 @@ from products.review_hog.backend.reviewer.artefact_content import (
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 load_chunk_set, load_findings_bundle, load_turn_findings
+from products.review_hog.backend.reviewer.persistence import TurnFindingsBundle, load_chunk_set, load_findings_bundle
from products.review_hog.backend.reviewer.progress import (
IN_PROGRESS_STALE_AFTER,
+ RESOLUTION_COMPLETED,
RESOLUTION_RESOLVING,
RESOLUTION_STOPPED,
REVIEW_STAGES,
ResolutionRunState,
+ ResolutionSummary,
SnapshotStats,
+ TurnMarker,
TurnStats,
+ latest_resolution_summaries,
progress_payload,
resolution_states,
snapshot_stats,
+ turn_markers,
turn_stats,
)
from products.review_hog.backend.reviewer.review_state import completed_turn_review_mode
@@ -142,6 +148,39 @@ class ReviewResolutionStatusSerializer(serializers.Serializer):
)
+class ReviewTriggerReviewMode(models.TextChoices):
+ FULL = REVIEW_MODE_FULL, "Deep"
+ FLASH = REVIEW_MODE_FLASH, "Standard"
+
+
+class ReviewLatestResolutionStatus(models.TextChoices):
+ RESOLVING = RESOLUTION_RESOLVING, "Resolving"
+ STOPPED = RESOLUTION_STOPPED, "Stopped"
+ COMPLETED = RESOLUTION_COMPLETED, "Completed"
+
+
+class ReviewLatestResolutionSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=ReviewLatestResolutionStatus.choices,
+ help_text="Where the run stands: 'resolving' while threads are being settled, 'completed' when it "
+ "finished, 'stopped' when it died partway or a newer review turn replaced it.",
+ )
+ started_at = serializers.DateTimeField(help_text="When the run queued its threads.")
+ completed_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the run finished; null unless the status is 'completed'."
+ )
+ total = serializers.IntegerField(help_text="Threads queued for this run.")
+ fixed = serializers.IntegerField(help_text="Threads the run fixed with a commit to the branch.")
+ needs_attention = serializers.IntegerField(
+ help_text="Threads left for the author: judged worth doing but not safe to fix unattended."
+ )
+ commits = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="SHAs of the run's fix commits, oldest first. Only commits confirmed on the pull request "
+ "branch that touch no protected files; the replies on GitHub link the same commits.",
+ )
+
+
class ReviewSelectionChunkSerializer(serializers.Serializer):
chunk_id = serializers.IntegerField(help_text="The chunk this row describes, as numbered by the chunker.")
chunk_type = serializers.CharField(
@@ -195,7 +234,25 @@ class ReviewRecentReviewSerializer(serializers.Serializer):
last_run_at = serializers.DateTimeField(
allow_null=True, help_text="When the latest review turn completed; null while the first is in flight."
)
- published = serializers.BooleanField(help_text="Whether a review has been published back to GitHub.")
+ published = serializers.BooleanField(
+ help_text="Whether any turn of this report has been published back to GitHub. See `turn_published` "
+ "for the returned turn."
+ )
+ turn_published = serializers.BooleanField(
+ help_text="Whether the returned turn (the latest completed one, or `run_index` on the detail) was "
+ "published to GitHub. False when it found nothing to post or publishing was off."
+ )
+ review_mode = serializers.ChoiceField(
+ choices=ReviewTriggerReviewMode.choices,
+ allow_null=True,
+ help_text="What the returned turn ran: 'full' (Deep) or 'flash' (Standard). Null when the turn did "
+ "not record its mode (turns from before the mode was recorded).",
+ )
+ status_comment_url = serializers.CharField(
+ allow_null=True,
+ help_text="Link to the review's status comment on the pull request; null when there is no status "
+ "comment or no pull request URL.",
+ )
full_review_published = serializers.BooleanField(
help_text="Whether a Deep review of this pull request has been published. No Standard review runs after one."
)
@@ -214,6 +271,11 @@ class ReviewRecentReviewSerializer(serializers.Serializer):
"while it runs, or where it stopped when it died partway. Null when there is none, it completed, "
"or a newer review turn superseded it.",
)
+ latest_resolution = ReviewLatestResolutionSerializer(
+ allow_null=True,
+ help_text="The report's latest resolution run, completed runs included: its status, counts, and "
+ "fix commits. Null when no resolution run has queued threads on this report.",
+ )
must_fix_count = serializers.IntegerField(
help_text="The latest turn's valid findings at must_fix effective priority."
)
@@ -295,11 +357,6 @@ class ReviewTriggerRequestSerializer(serializers.Serializer):
)
-class ReviewTriggerReviewMode(models.TextChoices):
- FULL = REVIEW_MODE_FULL, "Deep"
- FLASH = REVIEW_MODE_FLASH, "Standard"
-
-
class ReviewTriggerResponseSerializer(serializers.Serializer):
workflow_id = serializers.CharField(
allow_blank=True, help_text="Temporal workflow id for the started review run; empty when no run was started."
@@ -382,10 +439,20 @@ class ReviewFindingSerializer(serializers.Serializer):
)
+class ReviewDetailParamsSerializer(serializers.Serializer):
+ run_index = serializers.IntegerField(
+ required=False,
+ help_text="The completed review turn to read, from 1 to `run_count`. Defaults to the latest "
+ "completed turn. Use it to read an older turn's findings.",
+ )
+
+
class ReviewDetailSerializer(ReviewRecentReviewSerializer):
+ run_index = serializers.IntegerField(help_text="The review turn this detail describes, from 1 to `run_count`.")
head_sha = serializers.CharField(
allow_null=True,
- help_text="The PR head commit the latest turn reviewed — anchors GitHub links to the exact code.",
+ help_text="The PR head commit the returned turn reviewed. Anchors GitHub links to the exact code. "
+ "Null for an older turn whose head was not recorded.",
)
perspective_selection = ReviewPerspectiveSelectionSerializer(
allow_null=True,
@@ -393,18 +460,23 @@ class ReviewDetailSerializer(ReviewRecentReviewSerializer):
"without a selection (selector unavailable, failed, or the run predates it).",
)
report_markdown = serializers.CharField(
- allow_blank=True, help_text="The rendered review body published to GitHub, as markdown."
+ allow_blank=True,
+ allow_null=True,
+ help_text="The rendered review body published to GitHub, as markdown. Only kept for the latest "
+ "turn, so null when `run_index` selects an older turn.",
)
run_urgency_threshold = serializers.ChoiceField(
- choices=_PRIORITY_CHOICES,
+ choices=UrgencyThreshold.choices,
allow_null=True,
- help_text="The urgency threshold the completed turn's publishing gated on (stamped at finalize "
+ help_text="The urgency threshold the returned turn's publishing gated on (stamped at finalize "
"from the run's own resolve snapshot); null for turns that predate its recording — readers "
"fall back to the viewer's current setting as an approximation.",
)
- findings = ReviewFindingSerializer(many=True, help_text="The latest turn's validated findings, most urgent first.")
+ findings = ReviewFindingSerializer(
+ many=True, help_text="The returned turn's validated findings, most urgent first."
+ )
dismissed_findings = ReviewFindingSerializer(
- many=True, help_text="The latest turn's findings the validator dismissed, with its reasoning."
+ many=True, help_text="The returned turn's findings the validator dismissed, with its reasoning."
)
@@ -478,6 +550,54 @@ def _in_progress_report_ids(team_id: int, reports: list[ReviewReport]) -> set[st
return fresh
+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
+ return {
+ "status": summary.status,
+ "started_at": summary.started_at,
+ "completed_at": summary.completed_at,
+ "total": summary.total,
+ "fixed": summary.fixed,
+ "needs_attention": summary.needs_attention,
+ "commits": list(summary.commits),
+ }
+
+
def _finding_payload(finding: ReviewIssueFinding, verdict: ValidationVerdict) -> dict[str, Any]:
return {
"title": finding.title,
@@ -517,13 +637,16 @@ def _selection_payload(turn: TurnStats, chunks: ChunksList | None) -> dict[str,
def _review_payload(
report: ReviewReport,
+ run_index: int,
snapshot: SnapshotStats,
turn: TurnStats,
pairs: list[tuple[ReviewIssueFinding, ValidationVerdict | None]],
- progress: dict[str, Any] | None = None,
- resolution: ResolutionRunState | None = 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; the detail endpoint layers findings on top."""
+ """The list-row payload for one report's turn at `run_index`; the detail endpoint layers findings on top."""
counts = dict.fromkeys(IssuePriority, 0)
dismissed = 0
for finding, verdict in pairs:
@@ -548,6 +671,11 @@ def _review_payload(
"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,
+ "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),
@@ -561,6 +689,7 @@ def _review_payload(
}
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],
@@ -689,33 +818,28 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
# 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})
- in_flight = [report for report in reports if str(report.id) in in_progress_ids]
- live_heads = {str(report.id): report.head_sha for report in in_flight}
- live_snapshots = snapshot_stats(team_id, live_heads) if in_flight else {}
- live_turns = turn_stats(team_id, live_heads) if in_flight else {}
- bundle = load_findings_bundle(team_id=team_id, report_ids=[str(report.id) for report 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)
- snapshot = snapshots.get(report_id, SnapshotStats())
- turn = turns.get(report_id, TurnStats())
- pairs = bundle.turn(report_id, report.run_count)
- resolution = resolution_map.get(report_id)
- progress = None
- # 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".
- if report_id in in_progress_ids and (resolution is None or resolution.status != RESOLUTION_RESOLVING):
- # The in-flight turn's findings live one run_index ahead of the completed watermark.
- current_pairs = bundle.turn(report_id, report.run_count + 1)
- progress = progress_payload(
- team_id,
+ items.append(
+ _review_payload(
report,
- live_snapshots.get(report_id, SnapshotStats()),
- live_turns.get(report_id, TurnStats()),
- current_pairs,
+ 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),
)
- items.append(_review_payload(report, snapshot, turn, pairs, progress, resolution))
+ )
return Response(ReviewRecentReviewsPageSerializer({"results": items, "has_more": has_more}).data)
@extend_schema(
@@ -871,17 +995,20 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
)
@extend_schema(
+ parameters=[ReviewDetailParamsSerializer],
responses={
200: OpenApiResponse(
response=ReviewDetailSerializer,
description="The review's detail: findings (valid and dismissed) and the published body.",
),
- 404: OpenApiResponse(description="No such review on this project."),
+ 404: OpenApiResponse(description="No such review on this project, or no such completed turn."),
},
summary="Retrieve one review's detail",
- description="One completed ReviewHog review on this project, with the latest turn's validated "
- "findings, the findings the validator dismissed (and why), and the review body published to "
- "GitHub. Project-wide, so reviews listed under `scope=everyone` can be opened too.",
+ description="One completed ReviewHog review on this project, with one turn's validated findings, "
+ "the findings the validator dismissed (and why), and the review body published to GitHub. The "
+ "latest completed turn by default; `run_index` reads an older one. `in_progress`, `progress`, and "
+ "the resolution fields describe the report now, whatever the turn. Project-wide, so reviews listed "
+ "under `scope=everyone` can be opened too.",
)
def retrieve(self, request: Request, pk: str | None = None, **kwargs) -> Response:
try:
@@ -895,16 +1022,29 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
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:
+ raise NotFound("No completed review turn with that run_index.")
+ is_latest = run_index == report.run_count
+
report_id = str(report.id)
- # Everything the detail returns — stats, chunk set, link-anchoring head — describes the same
+ 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.
- completed_head = report.completed_head_sha or report.head_sha
- snapshots = snapshot_stats(team_id, {report_id: completed_head})
- turns = turn_stats(team_id, {report_id: completed_head})
- pairs = load_turn_findings(team_id=team_id, report_id=report_id, run_index=report.run_count)
- chunk_set = (
- load_chunk_set(team_id=team_id, report_id=report_id, head_sha=completed_head) if completed_head else None
- )
+ 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"])
@@ -914,14 +1054,24 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
payload = {
**_review_payload(
report,
+ run_index,
snapshots.get(report_id, SnapshotStats()),
turns.get(report_id, TurnStats()),
pairs,
- resolution=resolution_states(team_id, [report]).get(report_id),
+ marker,
+ progress,
+ resolutions.get(report_id),
+ latest_resolution_summaries(team_id, [report]).get(report_id),
),
- "head_sha": completed_head,
- "report_markdown": report.report_markdown,
- "run_urgency_threshold": report.run_urgency_threshold or None,
+ "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),
"perspective_selection": _selection_payload(turns.get(report_id, TurnStats()), chunk_set),
diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.py
index 4879bd85df9d..39029629d086 100644
--- a/products/review_hog/backend/reviewer/progress.py
+++ b/products/review_hog/backend/reviewer/progress.py
@@ -61,6 +61,7 @@ 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.
@@ -252,6 +253,39 @@ def turn_stats(team_id: int, heads: dict[str, str | None]) -> dict[str, TurnStat
return stats
+@frozen
+class TurnMarker:
+ """The mode and head of one executed turn, from its `turn_marker` artefact."""
+
+ review_mode: str
+ head_sha: str | None
+
+
+def turn_markers(team_id: int, report_ids: list[str]) -> dict[tuple[str, int], TurnMarker]:
+ """Each turn's marker, keyed by (report id, run index). The newest row of a retried turn wins.
+
+ Turns that started before markers existed, or whose marker write failed, are absent.
+ """
+ rows = (
+ ReviewReportArtefact.objects.for_team(team_id)
+ .filter(report_id__in=report_ids, type=ReviewReportArtefact.ArtefactType.TURN_MARKER)
+ .annotate(
+ marker_run_index=KeyTextTransform("run_index", _content_json()),
+ marker_review_mode=KeyTextTransform("review_mode", _content_json()),
+ )
+ .order_by("created_at", "id")
+ .values("report_id", "head_sha", "marker_run_index", "marker_review_mode")
+ )
+ markers: dict[tuple[str, int], TurnMarker] = {}
+ for row in rows:
+ if row["marker_run_index"] is None or row["marker_review_mode"] is None:
+ continue
+ markers[(str(row["report_id"]), int(row["marker_run_index"]))] = TurnMarker(
+ review_mode=row["marker_review_mode"], head_sha=row["head_sha"]
+ )
+ return markers
+
+
@frozen
class ResolutionRunState:
"""The report's latest resolution run, as the list row and the drawer render it."""
@@ -263,6 +297,36 @@ class ResolutionRunState:
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 _ThreadVerdictRow:
+ outcome: str
+ reply_posted: bool
+ # Only a fix commit the public reply links to: verified on the PR branch and not touching restricted paths.
+ linked_commit_sha: str | None
+
+
+@frozen
+class _RunSignals:
+ """Per report, the newest `pr_snapshot`, closing run `note`, and turn-written artefact."""
+
+ snapshot_latest: dict[str, datetime]
+ note_latest: dict[str, datetime]
+ activity_latest: dict[str, datetime]
+
+
def _latest_created_at(queryset: QuerySet) -> dict[str, datetime]:
rows = queryset.values_list("report_id").annotate(latest=Max("created_at")).values_list("report_id", "latest")
return {str(report_id): latest for report_id, latest in rows}
@@ -295,6 +359,34 @@ def _load_resolution_runs(
return runs
+def _run_signals(team_id: int, report_ids: list[str]) -> _RunSignals:
+ scoped = ReviewReportArtefact.objects.for_team(team_id).filter(report_id__in=report_ids)
+ return _RunSignals(
+ snapshot_latest=_latest_created_at(scoped.filter(type=ReviewReportArtefact.ArtefactType.PR_SNAPSHOT)),
+ note_latest=_latest_created_at(
+ scoped.filter(type=ReviewReportArtefact.ArtefactType.NOTE)
+ .annotate(note_author=KeyTextTransform("author", _content_json()))
+ .filter(note_author=RESOLUTION_RUN_NOTE_AUTHOR)
+ ),
+ activity_latest=_latest_created_at(scoped.exclude(type=ReviewReportArtefact.ArtefactType.FINDING_OUTCOME)),
+ )
+
+
+def _superseded(signals: _RunSignals, report_id: str, started_at: datetime) -> bool:
+ snapshot_at = signals.snapshot_latest.get(report_id)
+ return snapshot_at is not None and snapshot_at > started_at
+
+
+def _closed_at(signals: _RunSignals, report_id: str, started_at: datetime) -> datetime | None:
+ note_at = signals.note_latest.get(report_id)
+ return note_at if note_at is not None and note_at >= started_at else None
+
+
+def _is_fresh(report: ReviewReport, latest_artefact_at: datetime | None) -> bool:
+ last_activity = max(filter(None, [report.updated_at, latest_artefact_at]), default=None)
+ return last_activity is not None and last_activity >= timezone.now() - IN_PROGRESS_STALE_AFTER
+
+
def _live_resolution_runs(
team_id: int, runs: dict[str, tuple[ResolutionRunArtefact, datetime]]
) -> tuple[dict[str, tuple[ResolutionRunArtefact, datetime]], dict[str, datetime]]:
@@ -304,34 +396,24 @@ def _live_resolution_runs(
it completed (a closing run `note` after the anchor). Activity liveness reuses the same signal
`_in_progress_report_ids` uses for review turns, so the two can't disagree about "visibly moving".
"""
- scoped = ReviewReportArtefact.objects.for_team(team_id).filter(report_id__in=list(runs))
- snapshot_latest = _latest_created_at(scoped.filter(type=ReviewReportArtefact.ArtefactType.PR_SNAPSHOT))
- note_latest = _latest_created_at(
- scoped.filter(type=ReviewReportArtefact.ArtefactType.NOTE)
- .annotate(note_author=KeyTextTransform("author", _content_json()))
- .filter(note_author=RESOLUTION_RUN_NOTE_AUTHOR)
- )
- activity_latest = _latest_created_at(scoped.exclude(type=ReviewReportArtefact.ArtefactType.FINDING_OUTCOME))
-
+ signals = _run_signals(team_id, list(runs))
live: dict[str, tuple[ResolutionRunArtefact, datetime]] = {}
for report_id, (run, started_at) in runs.items():
- superseded = snapshot_latest.get(report_id) is not None and snapshot_latest[report_id] > started_at
- completed = note_latest.get(report_id) is not None and note_latest[report_id] >= started_at
- if not superseded and not completed:
+ if not _superseded(signals, report_id, started_at) and _closed_at(signals, report_id, started_at) is None:
live[report_id] = (run, started_at)
- return live, activity_latest
+ return live, signals.activity_latest
def _thread_verdicts(
team_id: int, live: dict[str, tuple[ResolutionRunArtefact, datetime]]
-) -> dict[str, dict[str, tuple[str, bool]]]:
+) -> dict[str, dict[str, _ThreadVerdictRow]]:
"""Latest verdict per thread within each live run (rows come oldest-first, so later rows win).
Scoped to the run's own queued threads, because redelivering a prior run's verdict also appends
rows during this run. Only delivered verdicts (`reply_posted`) count: a judged thread whose
GitHub writes failed has no reply yet, so it must not read as settled.
"""
- verdicts: dict[str, dict[str, tuple[str, bool]]] = {report_id: {} for report_id in live}
+ verdicts: dict[str, dict[str, _ThreadVerdictRow]] = {report_id: {} for report_id in live}
verdict_rows = (
ReviewReportArtefact.objects.for_team(team_id)
.filter(
@@ -343,18 +425,32 @@ def _thread_verdicts(
thread_id=KeyTextTransform("thread_id", _content_json()),
outcome=KeyTextTransform("outcome", _content_json()),
reply_posted=KeyTextTransform("reply_posted", _content_json()),
+ commit_sha=KeyTextTransform("commit_sha", _content_json()),
+ commit_verified=KeyTextTransform("commit_verified", _content_json()),
+ commit_restricted=KeyTextTransform("commit_restricted", _content_json()),
)
.order_by("created_at", "id")
- .values("report_id", "thread_id", "outcome", "reply_posted", "created_at")
+ .values(
+ "report_id",
+ "thread_id",
+ "outcome",
+ "reply_posted",
+ "commit_sha",
+ "commit_verified",
+ "commit_restricted",
+ "created_at",
+ )
)
for verdict_row in verdict_rows:
report_id = str(verdict_row["report_id"])
run, started_at = live[report_id]
if verdict_row["created_at"] < started_at or verdict_row["thread_id"] not in run.thread_ids:
continue
- verdicts[report_id][verdict_row["thread_id"]] = (
- verdict_row["outcome"],
- verdict_row["reply_posted"] == "true",
+ linked = verdict_row["commit_verified"] == "true" and verdict_row["commit_restricted"] != "true"
+ verdicts[report_id][verdict_row["thread_id"]] = _ThreadVerdictRow(
+ outcome=verdict_row["outcome"],
+ reply_posted=verdict_row["reply_posted"] == "true",
+ linked_commit_sha=verdict_row["commit_sha"] if linked else None,
)
return verdicts
@@ -381,14 +477,11 @@ def resolution_states(team_id: int, reports: list[ReviewReport]) -> dict[str, Re
verdicts = _thread_verdicts(team_id, live)
- cutoff = timezone.now() - IN_PROGRESS_STALE_AFTER
reports_by_id = {str(report.id): report for report in reports}
states: dict[str, ResolutionRunState] = {}
for report_id, (run, _started_at) in live.items():
- report = reports_by_id[report_id]
- last_activity = max(filter(None, [report.updated_at, activity_latest.get(report_id)]), default=None)
- fresh = last_activity is not None and last_activity >= cutoff
- delivered = [outcome for outcome, reply_posted in verdicts[report_id].values() if reply_posted]
+ fresh = _is_fresh(reports_by_id[report_id], activity_latest.get(report_id))
+ delivered = [verdict.outcome for verdict in verdicts[report_id].values() if verdict.reply_posted]
states[report_id] = ResolutionRunState(
status=RESOLUTION_RESOLVING if fresh else RESOLUTION_STOPPED,
done=len(delivered),
@@ -399,6 +492,44 @@ def resolution_states(team_id: int, reports: list[ReviewReport]) -> dict[str, Re
return states
+def latest_resolution_summaries(team_id: int, reports: list[ReviewReport]) -> dict[str, ResolutionSummary]:
+ """Each report's latest resolution run, completed runs included, with its outcome counts and fix commits.
+
+ A sibling of `resolution_states`, which drops completed and superseded runs because the list row
+ only shows a run while it matters for progress. A run that a newer review turn superseded
+ without its closing note reads as stopped.
+ """
+ runs = _load_resolution_runs(team_id, reports)
+ if not runs:
+ return {}
+ signals = _run_signals(team_id, list(runs))
+ verdicts = _thread_verdicts(team_id, runs)
+ reports_by_id = {str(report.id): report for report in reports}
+ summaries: dict[str, ResolutionSummary] = {}
+ for report_id, (run, started_at) in runs.items():
+ completed_at = _closed_at(signals, report_id, started_at)
+ if completed_at is not None:
+ status = RESOLUTION_COMPLETED
+ elif not _superseded(signals, report_id, started_at) and _is_fresh(
+ reports_by_id[report_id], signals.activity_latest.get(report_id)
+ ):
+ status = RESOLUTION_RESOLVING
+ else:
+ status = RESOLUTION_STOPPED
+ delivered = [verdict for verdict in verdicts[report_id].values() if verdict.reply_posted]
+ fixed = [verdict for verdict in delivered if verdict.outcome == "fixed"]
+ summaries[report_id] = ResolutionSummary(
+ status=status,
+ started_at=started_at,
+ completed_at=completed_at,
+ total=run.total,
+ fixed=len(fixed),
+ needs_attention=sum(1 for verdict in delivered if verdict.outcome == "escalate"),
+ commits=tuple(dict.fromkeys(v.linked_commit_sha for v in fixed if v.linked_commit_sha)),
+ )
+ return summaries
+
+
def _expected_reads(team_id: int, report: ReviewReport, turn: TurnStats) -> int | None:
"""How many (pass, chunk) reviews this turn should produce.
diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.py
index 6131252f7129..e66623e73fbd 100644
--- a/products/review_hog/backend/tests/test_reviews_api.py
+++ b/products/review_hog/backend/tests/test_reviews_api.py
@@ -22,7 +22,7 @@ from products.review_hog.backend.reviewer.artefact_content import (
TurnMarkerArtefact,
ValidationVerdict,
)
-from products.review_hog.backend.reviewer.constants import DEFAULT_REVIEW_ARM, REVIEW_MODE_FLASH
+from products.review_hog.backend.reviewer.constants import DEFAULT_REVIEW_ARM, REVIEW_MODE_FLASH, REVIEW_MODE_FULL
from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRMetadata
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, IssuesReview, LineRange
from products.review_hog.backend.reviewer.models.perspective_selection import (
@@ -149,6 +149,101 @@ class TestRecentReviewsAPI(APIBaseTest):
attribution=ArtefactAttribution.system(),
)
+ def _turn_marker(self, report: ReviewReport, *, run_index: int, review_mode: str, head_sha: str) -> None:
+ ReviewReportArtefact.add_turn_marker(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=TurnMarkerArtefact(
+ head_sha=head_sha,
+ run_index=run_index,
+ review_mode=review_mode,
+ reviewhog_version="v",
+ reviewhog_fingerprint="f",
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ @parameterized.expand([("flash", REVIEW_MODE_FLASH), ("full", REVIEW_MODE_FULL), ("no_marker", None)])
+ def test_review_mode_comes_from_the_completed_turns_marker(self, _name: str, review_mode: str | None) -> None:
+ # A clean, unpublished Standard turn has no findings to carry its mode, which the findings-based
+ # fallback reads as Deep. The marker is the only source that tells the two apart. The older
+ # turn's marker and the in-flight turn's marker must not leak onto the completed turn.
+ report = self._report(pr_number=1, acting_user=self.user, run_count=2, head_sha="c3")
+ self._turn_marker(report, run_index=1, review_mode=REVIEW_MODE_FULL, head_sha="c1")
+ if review_mode is not None:
+ self._turn_marker(report, run_index=2, review_mode=review_mode, head_sha="c2")
+ self._turn_marker(report, run_index=3, review_mode=REVIEW_MODE_FULL, head_sha="c3")
+
+ row = self.client.get(self.url).json()["results"][0]
+ detail = self.client.get(f"{self.url}{report.id}/").json()
+
+ assert row["review_mode"] == review_mode
+ assert detail["review_mode"] == review_mode
+
+ @parameterized.expand(
+ [
+ (
+ "latest_turn_published",
+ {"1": "a", "2": "b"},
+ 99,
+ True,
+ "https://github.com/PostHog/posthog/pull/1#issuecomment-99",
+ ),
+ ("only_an_older_turn_published", {"1": "a"}, None, False, None),
+ ("never_published", None, None, False, None),
+ ]
+ )
+ def test_turn_published_and_status_comment_url(
+ self,
+ _name: str,
+ published_head_shas: dict[str, str] | None,
+ status_comment_id: int | None,
+ turn_published: bool,
+ status_comment_url: str | None,
+ ) -> None:
+ # `published` means "ever", so an agent reading a clean re-review would think the new turn posted.
+ self._report(
+ pr_number=1,
+ acting_user=self.user,
+ run_count=2,
+ published_head_sha="a" if published_head_shas else None,
+ published_head_shas=published_head_shas,
+ status_comment_id=status_comment_id,
+ )
+
+ row = self.client.get(self.url).json()["results"][0]
+
+ assert row["published"] is bool(published_head_shas)
+ assert row["turn_published"] is turn_published
+ assert row["status_comment_url"] == status_comment_url
+
+ def test_run_index_reads_an_older_completed_turn(self) -> None:
+ # The body is stored for the latest turn only, so an older turn must not return it as its own.
+ report = self._report(
+ pr_number=1,
+ acting_user=self.user,
+ run_count=2,
+ report_markdown="## Turn 2",
+ published_head_shas={"1": "c1"},
+ published_urgency_thresholds={"1": "consider"},
+ run_urgency_threshold="must_fix",
+ )
+ self._turn_marker(report, run_index=1, review_mode=REVIEW_MODE_FLASH, head_sha="c1")
+ self._finding(report, "1-old", priority=IssuePriority.MUST_FIX, run_index=1)
+ self._finding(report, "2-new", priority=IssuePriority.CONSIDER, run_index=2)
+
+ latest = self.client.get(f"{self.url}{report.id}/").json()
+ older = self.client.get(f"{self.url}{report.id}/", {"run_index": 1}).json()
+
+ assert (latest["run_index"], latest["report_markdown"], latest["turn_published"]) == (2, "## Turn 2", False)
+ assert [f["title"] for f in latest["findings"]] == ["title 2-new"]
+ assert (older["run_index"], older["report_markdown"], older["turn_published"]) == (1, None, True)
+ assert (older["head_sha"], older["review_mode"], older["run_urgency_threshold"]) == ("c1", "flash", "consider")
+ assert [f["title"] for f in older["findings"]] == ["title 1-old"]
+ assert older["must_fix_count"] == 1
+ for out_of_range in (0, 3):
+ assert self.client.get(f"{self.url}{report.id}/", {"run_index": out_of_range}).status_code == 404
+
def test_lists_only_my_completed_reviews(self) -> None:
# The default (mine) scope is "your recent reviews": a teammate's report and an abandoned
# (stale, never completed) run must not appear — a filter regression would leak other users'
@@ -617,12 +712,29 @@ class TestRecentReviewsAPI(APIBaseTest):
attribution=ArtefactAttribution.system(),
)
- def _thread_verdict(self, report: ReviewReport, thread_id: str, outcome: str, *, delivered: bool = True) -> None:
+ def _thread_verdict(
+ self,
+ report: ReviewReport,
+ thread_id: str,
+ outcome: str,
+ *,
+ delivered: bool = True,
+ commit_sha: str | None = None,
+ commit_verified: bool | None = None,
+ commit_restricted: bool | None = None,
+ ) -> None:
ReviewReportArtefact.append_thread_verdict(
team_id=self.team.id,
report_id=str(report.id),
content=ThreadVerdictArtefact(
- thread_id=thread_id, outcome=outcome, reasoning="r", reply="reply", reply_posted=delivered
+ thread_id=thread_id,
+ outcome=outcome,
+ reasoning="r",
+ reply="reply",
+ reply_posted=delivered,
+ commit_sha=commit_sha,
+ commit_verified=commit_verified,
+ commit_restricted=commit_restricted,
),
attribution=ArtefactAttribution.system(),
)
@@ -669,11 +781,11 @@ class TestRecentReviewsAPI(APIBaseTest):
@parameterized.expand(
[
- ("completed_run_via_closing_note",),
- ("superseded_by_newer_review_turn",),
+ ("completed_run_via_closing_note", "completed"),
+ ("superseded_by_newer_review_turn", "stopped"),
]
)
- def test_finished_or_superseded_resolution_carries_no_state(self, scenario: str) -> None:
+ def test_finished_or_superseded_resolution_carries_no_state(self, scenario: str, latest_status: str) -> None:
# A completed run must not render as crashed once it ages past the staleness window (the
# closing note is the completion marker), and a crashed run must yield the row to a newer
# review turn's own progress instead of pinning a stale "didn't finish" on it.
@@ -696,6 +808,30 @@ class TestRecentReviewsAPI(APIBaseTest):
row = self.client.get(self.url).json()["results"][0]
assert row["resolution"] is None
+ # The agent-facing summary keeps the finished run, so a caller can still read what it did.
+ assert (row["latest_resolution"]["status"], row["latest_resolution"]["fixed"]) == (latest_status, 1)
+ assert (row["latest_resolution"]["completed_at"] is not None) is (latest_status == "completed")
+
+ def test_completed_resolution_lists_only_commits_the_replies_link(self) -> None:
+ # A fix commit that failed branch verification or touches protected files gets no public link
+ # on GitHub, so the API must not hand its SHA to an agent as a trusted fix either.
+ report = self._report(pr_number=5, acting_user=self.user)
+ self._resolution_run(report, ["PRRT_1", "PRRT_2", "PRRT_3", "PRRT_4", "PRRT_5"])
+ self._thread_verdict(report, "PRRT_1", "fixed", commit_sha="good", commit_verified=True)
+ self._thread_verdict(report, "PRRT_2", "fixed", commit_sha="unverified", commit_verified=False)
+ self._thread_verdict(
+ report, "PRRT_3", "fixed", commit_sha="restricted", commit_verified=True, commit_restricted=True
+ )
+ self._thread_verdict(report, "PRRT_4", "fixed", commit_sha="unchecked")
+ self._thread_verdict(report, "PRRT_5", "escalate")
+ self._closing_run_note(report)
+
+ detail = self.client.get(f"{self.url}{report.id}/").json()
+
+ assert detail["resolution"] is None
+ latest = detail["latest_resolution"]
+ assert (latest["status"], latest["total"], latest["fixed"], latest["needs_attention"]) == ("completed", 5, 4, 1)
+ assert latest["commits"] == ["good"]
def test_dead_resolution_run_shows_where_it_stopped(self) -> None:
# The silent-death mode: a resolution that dies partway used to leave no trace anywhere.
@@ -790,6 +926,9 @@ class TestRecentReviewsAPI(APIBaseTest):
detail = self.client.get(f"{self.url}{report_id}/").json()
assert detail["head_sha"] == "abc"
assert detail["pr_title"] == "completed title"
+ # The detail must report the running re-review like the row does, not read as idle.
+ assert detail["in_progress"] is True
+ assert detail["progress"] == row["progress"]
def test_in_progress_re_review_of_a_dormant_report_still_lists(self) -> None:
# A re-review keeps the previous turn's last_run_at until it finalizes, so a dormant report's
diff --git a/products/review_hog/frontend/CodeReviewScene.stories.tsx b/products/review_hog/frontend/CodeReviewScene.stories.tsx
index f062aca696e1..bbaf53a48cb7 100644
--- a/products/review_hog/frontend/CodeReviewScene.stories.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.stories.tsx
@@ -77,10 +77,14 @@ function completedReview(overrides: Partial<ReviewRecentReviewApi>): ReviewRecen
run_count: 1,
last_run_at: '2026-09-30T10:00:00Z',
published: true,
+ turn_published: true,
+ review_mode: 'full',
+ status_comment_url: null,
full_review_published: true,
in_progress: false,
progress: null,
resolution: null,
+ latest_resolution: null,
must_fix_count: 1,
should_fix_count: 2,
consider_count: 1,
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 91d895bade46..049a35be7d3c 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -607,6 +607,18 @@ export interface PatchedReviewResolutionConfigSelectApi {
active?: boolean
}
+/**
+ * * `full` - Deep
+ * * `flash` - Standard
+ */
+export type ReviewTriggerReviewModeEnumApi =
+ (typeof ReviewTriggerReviewModeEnumApi)[keyof typeof ReviewTriggerReviewModeEnumApi]
+
+export const ReviewTriggerReviewModeEnumApi = {
+ Full: 'full',
+ Flash: 'flash',
+} as const
+
/**
* * `fetching` - fetching
* * `chunking` - chunking
@@ -687,6 +699,44 @@ export interface ReviewResolutionStatusApi {
needs_attention: number
}
+/**
+ * * `resolving` - Resolving
+ * * `stopped` - Stopped
+ * * `completed` - Completed
+ */
+export type ReviewLatestResolutionStatusEnumApi =
+ (typeof ReviewLatestResolutionStatusEnumApi)[keyof typeof ReviewLatestResolutionStatusEnumApi]
+
+export const ReviewLatestResolutionStatusEnumApi = {
+ Resolving: 'resolving',
+ Stopped: 'stopped',
+ Completed: 'completed',
+} as const
+
+export interface ReviewLatestResolutionApi {
+ /** Where the run stands: 'resolving' while threads are being settled, 'completed' when it finished, 'stopped' when it died partway or a newer review turn replaced it.
+ *
+ * * `resolving` - Resolving
+ * * `stopped` - Stopped
+ * * `completed` - Completed */
+ status: ReviewLatestResolutionStatusEnumApi
+ /** When the run queued its threads. */
+ started_at: string
+ /**
+ * When the run finished; null unless the status is 'completed'.
+ * @nullable
+ */
+ completed_at: string | null
+ /** Threads queued for this run. */
+ total: number
+ /** Threads the run fixed with a commit to the branch. */
+ fixed: number
+ /** Threads left for the author: judged worth doing but not safe to fix unattended. */
+ needs_attention: number
+ /** SHAs of the run's fix commits, oldest first. Only commits confirmed on the pull request branch that touch no protected files; the replies on GitHub link the same commits. */
+ commits: string[]
+}
+
export interface ReviewRecentReviewApi {
/** The review report's id, for fetching the review's detail. */
id: string
@@ -733,8 +783,20 @@ export interface ReviewRecentReviewApi {
* @nullable
*/
last_run_at: string | null
- /** Whether a review has been published back to GitHub. */
+ /** Whether any turn of this report has been published back to GitHub. See `turn_published` for the returned turn. */
published: boolean
+ /** Whether the returned turn (the latest completed one, or `run_index` on the detail) was published to GitHub. False when it found nothing to post or publishing was off. */
+ turn_published: boolean
+ /** What the returned turn ran: 'full' (Deep) or 'flash' (Standard). Null when the turn did not record its mode (turns from before the mode was recorded).
+ *
+ * * `full` - Deep
+ * * `flash` - Standard */
+ review_mode: ReviewTriggerReviewModeEnumApi | null
+ /**
+ * Link to the review's status comment on the pull request; null when there is no status comment or no pull request URL.
+ * @nullable
+ */
+ status_comment_url: string | null
/** Whether a Deep review of this pull request has been published. No Standard review runs after one. */
full_review_published: boolean
/** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */
@@ -743,6 +805,8 @@ export interface ReviewRecentReviewApi {
progress: ReviewProgressApi | null
/** The report's latest resolution run (settling the PR's review threads): live progress while it runs, or where it stopped when it died partway. Null when there is none, it completed, or a newer review turn superseded it. */
resolution: ReviewResolutionStatusApi | null
+ /** The report's latest resolution run, completed runs included: its status, counts, and fix commits. Null when no resolution run has queued threads on this report. */
+ latest_resolution: ReviewLatestResolutionApi | null
/** The latest turn's valid findings at must_fix effective priority. */
must_fix_count: number
/** The latest turn's valid findings at should_fix effective priority. */
@@ -812,6 +876,16 @@ export interface ReviewPerspectiveSelectionApi {
chunks: ReviewSelectionChunkApi[]
}
+export interface ReviewFindingLineRangeApi {
+ /** First affected line. */
+ start: number
+ /**
+ * Last affected line; null for a single line.
+ * @nullable
+ */
+ end: number | null
+}
+
/**
* * `must_fix` - must_fix
* * `should_fix` - should_fix
@@ -825,16 +899,6 @@ export const ReviewIssuePriorityEnumApi = {
Consider: 'consider',
} as const
-export interface ReviewFindingLineRangeApi {
- /** First affected line. */
- start: number
- /**
- * Last affected line; null for a single line.
- * @nullable
- */
- end: number | null
-}
-
/**
* * `bug` - bug
* * `security` - security
@@ -950,8 +1014,20 @@ export interface ReviewDetailApi {
* @nullable
*/
last_run_at: string | null
- /** Whether a review has been published back to GitHub. */
+ /** Whether any turn of this report has been published back to GitHub. See `turn_published` for the returned turn. */
published: boolean
+ /** Whether the returned turn (the latest completed one, or `run_index` on the detail) was published to GitHub. False when it found nothing to post or publishing was off. */
+ turn_published: boolean
+ /** What the returned turn ran: 'full' (Deep) or 'flash' (Standard). Null when the turn did not record its mode (turns from before the mode was recorded).
+ *
+ * * `full` - Deep
+ * * `flash` - Standard */
+ review_mode: ReviewTriggerReviewModeEnumApi | null
+ /**
+ * Link to the review's status comment on the pull request; null when there is no status comment or no pull request URL.
+ * @nullable
+ */
+ status_comment_url: string | null
/** Whether a Deep review of this pull request has been published. No Standard review runs after one. */
full_review_published: boolean
/** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */
@@ -960,6 +1036,8 @@ export interface ReviewDetailApi {
progress: ReviewProgressApi | null
/** The report's latest resolution run (settling the PR's review threads): live progress while it runs, or where it stopped when it died partway. Null when there is none, it completed, or a newer review turn superseded it. */
resolution: ReviewResolutionStatusApi | null
+ /** The report's latest resolution run, completed runs included: its status, counts, and fix commits. Null when no resolution run has queued threads on this report. */
+ latest_resolution: ReviewLatestResolutionApi | null
/** The latest turn's valid findings at must_fix effective priority. */
must_fix_count: number
/** The latest turn's valid findings at should_fix effective priority. */
@@ -995,24 +1073,29 @@ export interface ReviewDetailApi {
* @nullable
*/
blind_spot_issue_count: number | null
+ /** The review turn this detail describes, from 1 to `run_count`. */
+ run_index: number
/**
- * The PR head commit the latest turn reviewed — anchors GitHub links to the exact code.
+ * The PR head commit the returned turn reviewed. Anchors GitHub links to the exact code. Null for an older turn whose head was not recorded.
* @nullable
*/
head_sha: string | null
/** The selector's per-chunk perspective plan for the latest turn; null when the turn ran without a selection (selector unavailable, failed, or the run predates it). */
perspective_selection: ReviewPerspectiveSelectionApi | null
- /** The rendered review body published to GitHub, as markdown. */
- report_markdown: string
- /** The urgency threshold the completed turn's publishing gated on (stamped at finalize from the run's own resolve snapshot); null for turns that predate its recording — readers fall back to the viewer's current setting as an approximation.
+ /**
+ * The rendered review body published to GitHub, as markdown. Only kept for the latest turn, so null when `run_index` selects an older turn.
+ * @nullable
+ */
+ report_markdown: string | null
+ /** The urgency threshold the returned turn's publishing gated on (stamped at finalize from the run's own resolve snapshot); null for turns that predate its recording — readers fall back to the viewer's current setting as an approximation.
*
- * * `must_fix` - must_fix
- * * `should_fix` - should_fix
- * * `consider` - consider */
- run_urgency_threshold: ReviewIssuePriorityEnumApi | null
- /** The latest turn's validated findings, most urgent first. */
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ run_urgency_threshold: UrgencyThresholdEnumApi | null
+ /** The returned turn's validated findings, most urgent first. */
findings: ReviewFindingApi[]
- /** The latest turn's findings the validator dismissed, with its reasoning. */
+ /** The returned turn's findings the validator dismissed, with its reasoning. */
dismissed_findings: ReviewFindingApi[]
}
@@ -1062,18 +1145,6 @@ export interface ReviewTriggerRequestApi {
run_mode?: ReviewTriggerRequestRunModeEnumApi
}
-/**
- * * `full` - Deep
- * * `flash` - Standard
- */
-export type ReviewTriggerReviewModeEnumApi =
- (typeof ReviewTriggerReviewModeEnumApi)[keyof typeof ReviewTriggerReviewModeEnumApi]
-
-export const ReviewTriggerReviewModeEnumApi = {
- Full: 'full',
- Flash: 'flash',
-} as const
-
/**
* * `run_mode_excludes_resolve` - The run mode never resolves comments
* * `owner_not_opted_in` - The pull request owner has not opted in to resolution
@@ -1362,6 +1433,13 @@ export const ReviewHogReviewsListScope = {
Everyone: 'everyone',
} as const
+export type ReviewHogReviewsRetrieveParams = {
+ /**
+ * The completed review turn to read, from 1 to `run_count`. Defaults to the latest completed turn. Use it to read an older turn's findings.
+ */
+ run_index?: number
+}
+
export type ReviewHogReviewsPerspectiveStatsRetrieveParams = {
/**
* Whose reviews to aggregate: `mine` (the default) for reviews the requesting user ran plus reviews of pull requests they authored (matched via their linked GitHub login), `everyone` for every review on this project, `own_deep` for the last 10 Deep reviews the requesting user started. The review skills in the settings use `own_deep`, because only the person who starts a Deep review picks its skills.
diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.ts
index 6310725d036a..02ea5ad2fa46 100644
--- a/products/review_hog/frontend/generated/api.ts
+++ b/products/review_hog/frontend/generated/api.ts
@@ -21,6 +21,7 @@ import type {
ReviewHogRepositoryOverviewRetrieveParams,
ReviewHogReviewsListParams,
ReviewHogReviewsPerspectiveStatsRetrieveParams,
+ ReviewHogReviewsRetrieveParams,
ReviewInstallationClaimApi,
ReviewInstallationClaimCreateApi,
ReviewPerspectiveConfigApi,
@@ -568,20 +569,37 @@ export const reviewHogReviewsList = async (
})
}
-export const getReviewHogReviewsRetrieveUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/review_hog/reviews/${id}/`
+export const getReviewHogReviewsRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params?: ReviewHogReviewsRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/review_hog/reviews/${id}/?${stringifiedParams}`
+ : `/api/projects/${projectId}/review_hog/reviews/${id}/`
}
/**
- * One completed ReviewHog review on this project, with the latest turn's validated findings, the findings the validator dismissed (and why), and the review body published to GitHub. Project-wide, so reviews listed under `scope=everyone` can be opened too.
+ * One completed ReviewHog review on this project, with one turn's validated findings, the findings the validator dismissed (and why), and the review body published to GitHub. The latest completed turn by default; `run_index` reads an older one. `in_progress`, `progress`, and the resolution fields describe the report now, whatever the turn. Project-wide, so reviews listed under `scope=everyone` can be opened too.
* @summary Retrieve one review's detail
*/
export const reviewHogReviewsRetrieve = async (
projectId: string,
id: string,
+ params?: ReviewHogReviewsRetrieveParams,
options?: RequestInit
): Promise<ReviewDetailApi> => {
- return apiMutator<ReviewDetailApi>(getReviewHogReviewsRetrieveUrl(projectId, id), {
+ return apiMutator<ReviewDetailApi>(getReviewHogReviewsRetrieveUrl(projectId, id, params), {
...options,
method: 'GET',
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index dd555b3f1d5e..32b525c2ff33 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -95194,6 +95194,18 @@ export namespace Schemas {
body: string;
}
+ /**
+ * * `full` - Deep
+ * * `flash` - Standard
+ */
+ export type ReviewTriggerReviewModeEnum = typeof ReviewTriggerReviewModeEnum[keyof typeof ReviewTriggerReviewModeEnum];
+
+
+ export const ReviewTriggerReviewModeEnum = {
+ Full: 'full',
+ Flash: 'flash',
+ } as const;
+
/**
* * `fetching` - fetching
* * `chunking` - chunking
@@ -95264,6 +95276,44 @@ export namespace Schemas {
needs_attention: number;
}
+ /**
+ * * `resolving` - Resolving
+ * * `stopped` - Stopped
+ * * `completed` - Completed
+ */
+ export type ReviewLatestResolutionStatusEnum = typeof ReviewLatestResolutionStatusEnum[keyof typeof ReviewLatestResolutionStatusEnum];
+
+
+ export const ReviewLatestResolutionStatusEnum = {
+ Resolving: 'resolving',
+ Stopped: 'stopped',
+ Completed: 'completed',
+ } as const;
+
+ export interface ReviewLatestResolution {
+ /** Where the run stands: 'resolving' while threads are being settled, 'completed' when it finished, 'stopped' when it died partway or a newer review turn replaced it.
+ *
+ * * `resolving` - Resolving
+ * * `stopped` - Stopped
+ * * `completed` - Completed */
+ status: ReviewLatestResolutionStatusEnum;
+ /** When the run queued its threads. */
+ started_at: string;
+ /**
+ * When the run finished; null unless the status is 'completed'.
+ * @nullable
+ */
+ completed_at: string | null;
+ /** Threads queued for this run. */
+ total: number;
+ /** Threads the run fixed with a commit to the branch. */
+ fixed: number;
+ /** Threads left for the author: judged worth doing but not safe to fix unattended. */
+ needs_attention: number;
+ /** SHAs of the run's fix commits, oldest first. Only commits confirmed on the pull request branch that touch no protected files; the replies on GitHub link the same commits. */
+ commits: string[];
+ }
+
export interface ReviewSelectionChunk {
/** The chunk this row describes, as numbered by the chunker. */
chunk_id: number;
@@ -95289,6 +95339,16 @@ export namespace Schemas {
chunks: ReviewSelectionChunk[];
}
+ export interface ReviewFindingLineRange {
+ /** First affected line. */
+ start: number;
+ /**
+ * Last affected line; null for a single line.
+ * @nullable
+ */
+ end: number | null;
+ }
+
/**
* * `must_fix` - must_fix
* * `should_fix` - should_fix
@@ -95303,16 +95363,6 @@ export namespace Schemas {
Consider: 'consider',
} as const;
- export interface ReviewFindingLineRange {
- /** First affected line. */
- start: number;
- /**
- * Last affected line; null for a single line.
- * @nullable
- */
- end: number | null;
- }
-
/**
* * `bug` - bug
* * `security` - security
@@ -95429,8 +95479,20 @@ export namespace Schemas {
* @nullable
*/
last_run_at: string | null;
- /** Whether a review has been published back to GitHub. */
+ /** Whether any turn of this report has been published back to GitHub. See `turn_published` for the returned turn. */
published: boolean;
+ /** Whether the returned turn (the latest completed one, or `run_index` on the detail) was published to GitHub. False when it found nothing to post or publishing was off. */
+ turn_published: boolean;
+ /** What the returned turn ran: 'full' (Deep) or 'flash' (Standard). Null when the turn did not record its mode (turns from before the mode was recorded).
+ *
+ * * `full` - Deep
+ * * `flash` - Standard */
+ review_mode: ReviewTriggerReviewModeEnum | null;
+ /**
+ * Link to the review's status comment on the pull request; null when there is no status comment or no pull request URL.
+ * @nullable
+ */
+ status_comment_url: string | null;
/** Whether a Deep review of this pull request has been published. No Standard review runs after one. */
full_review_published: boolean;
/** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */
@@ -95439,6 +95501,8 @@ export namespace Schemas {
progress: ReviewProgress | null;
/** The report's latest resolution run (settling the PR's review threads): live progress while it runs, or where it stopped when it died partway. Null when there is none, it completed, or a newer review turn superseded it. */
resolution: ReviewResolutionStatus | null;
+ /** The report's latest resolution run, completed runs included: its status, counts, and fix commits. Null when no resolution run has queued threads on this report. */
+ latest_resolution: ReviewLatestResolution | null;
/** The latest turn's valid findings at must_fix effective priority. */
must_fix_count: number;
/** The latest turn's valid findings at should_fix effective priority. */
@@ -95474,24 +95538,29 @@ export namespace Schemas {
* @nullable
*/
blind_spot_issue_count: number | null;
+ /** The review turn this detail describes, from 1 to `run_count`. */
+ run_index: number;
/**
- * The PR head commit the latest turn reviewed — anchors GitHub links to the exact code.
+ * The PR head commit the returned turn reviewed. Anchors GitHub links to the exact code. Null for an older turn whose head was not recorded.
* @nullable
*/
head_sha: string | null;
/** The selector's per-chunk perspective plan for the latest turn; null when the turn ran without a selection (selector unavailable, failed, or the run predates it). */
perspective_selection: ReviewPerspectiveSelection | null;
- /** The rendered review body published to GitHub, as markdown. */
- report_markdown: string;
- /** The urgency threshold the completed turn's publishing gated on (stamped at finalize from the run's own resolve snapshot); null for turns that predate its recording — readers fall back to the viewer's current setting as an approximation.
+ /**
+ * The rendered review body published to GitHub, as markdown. Only kept for the latest turn, so null when `run_index` selects an older turn.
+ * @nullable
+ */
+ report_markdown: string | null;
+ /** The urgency threshold the returned turn's publishing gated on (stamped at finalize from the run's own resolve snapshot); null for turns that predate its recording — readers fall back to the viewer's current setting as an approximation.
*
- * * `must_fix` - must_fix
- * * `should_fix` - should_fix
- * * `consider` - consider */
- run_urgency_threshold: ReviewIssuePriorityEnum | null;
- /** The latest turn's validated findings, most urgent first. */
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ run_urgency_threshold: UrgencyThresholdEnum | null;
+ /** The returned turn's validated findings, most urgent first. */
findings: ReviewFinding[];
- /** The latest turn's findings the validator dismissed, with its reasoning. */
+ /** The returned turn's findings the validator dismissed, with its reasoning. */
dismissed_findings: ReviewFinding[];
}
@@ -95654,8 +95723,20 @@ export namespace Schemas {
* @nullable
*/
last_run_at: string | null;
- /** Whether a review has been published back to GitHub. */
+ /** Whether any turn of this report has been published back to GitHub. See `turn_published` for the returned turn. */
published: boolean;
+ /** Whether the returned turn (the latest completed one, or `run_index` on the detail) was published to GitHub. False when it found nothing to post or publishing was off. */
+ turn_published: boolean;
+ /** What the returned turn ran: 'full' (Deep) or 'flash' (Standard). Null when the turn did not record its mode (turns from before the mode was recorded).
+ *
+ * * `full` - Deep
+ * * `flash` - Standard */
+ review_mode: ReviewTriggerReviewModeEnum | null;
+ /**
+ * Link to the review's status comment on the pull request; null when there is no status comment or no pull request URL.
+ * @nullable
+ */
+ status_comment_url: string | null;
/** Whether a Deep review of this pull request has been published. No Standard review runs after one. */
full_review_published: boolean;
/** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */
@@ -95664,6 +95745,8 @@ export namespace Schemas {
progress: ReviewProgress | null;
/** The report's latest resolution run (settling the PR's review threads): live progress while it runs, or where it stopped when it died partway. Null when there is none, it completed, or a newer review turn superseded it. */
resolution: ReviewResolutionStatus | null;
+ /** The report's latest resolution run, completed runs included: its status, counts, and fix commits. Null when no resolution run has queued threads on this report. */
+ latest_resolution: ReviewLatestResolution | null;
/** The latest turn's valid findings at must_fix effective priority. */
must_fix_count: number;
/** The latest turn's valid findings at should_fix effective priority. */
@@ -96010,18 +96093,6 @@ export namespace Schemas {
run_mode?: ReviewTriggerRequestRunModeEnum;
}
- /**
- * * `full` - Deep
- * * `flash` - Standard
- */
- export type ReviewTriggerReviewModeEnum = typeof ReviewTriggerReviewModeEnum[keyof typeof ReviewTriggerReviewModeEnum];
-
-
- export const ReviewTriggerReviewModeEnum = {
- Full: 'full',
- Flash: 'flash',
- } as const;
-
export interface ReviewTriggerResponse {
/** Temporal workflow id for the started review run; empty when no run was started. */
workflow_id: string;
@@ -126388,6 +126459,13 @@ export namespace Schemas {
Everyone: 'everyone',
} as const;
+ export type ReviewHogReviewsRetrieveParams = {
+ /**
+ * The completed review turn to read, from 1 to `run_count`. Defaults to the latest completed turn. Use it to read an older turn's findings.
+ */
+ run_index?: number;
+ };
+
export type ReviewHogReviewsPerspectiveStatsRetrieveParams = {
/**
* Whose reviews to aggregate: `mine` (the default) for reviews the requesting user ran plus reviews of pull requests they authored (matched via their linked GitHub login), `everyone` for every review on this project, `own_deep` for the last 10 Deep reviews the requesting user started. The review skills in the settings use `own_deep`, because only the person who starts a Deep review picks its skills.
diff --git a/services/mcp/src/generated/review_hog/api.ts b/services/mcp/src/generated/review_hog/api.ts
index f2be9ed564f4..ef8b859b58ab 100644
--- a/services/mcp/src/generated/review_hog/api.ts
+++ b/services/mcp/src/generated/review_hog/api.ts
@@ -43,7 +43,7 @@ export const ReviewHogReviewsListQueryParams = () => zod.object({
})
/**
- * One completed ReviewHog review on this project, with the latest turn's validated findings, the findings the validator dismissed (and why), and the review body published to GitHub. Project-wide, so reviews listed under `scope=everyone` can be opened too.
+ * One completed ReviewHog review on this project, with one turn's validated findings, the findings the validator dismissed (and why), and the review body published to GitHub. The latest completed turn by default; `run_index` reads an older one. `in_progress`, `progress`, and the resolution fields describe the report now, whatever the turn. Project-wide, so reviews listed under `scope=everyone` can be opened too.
* @summary Retrieve one review's detail
*/
export const ReviewHogReviewsRetrieveParams = () => zod.object({
@@ -55,6 +55,15 @@ export const ReviewHogReviewsRetrieveParams = () => zod.object({
),
})
+export const ReviewHogReviewsRetrieveQueryParams = () => zod.object({
+ run_index: zod
+ .number()
+ .optional()
+ .describe(
+ "The completed review turn to read, from 1 to `run_count`. Defaults to the latest completed turn. Use it to read an older turn's findings."
+ ),
+})
+
/**
* Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The run appears under the requesting user's recent reviews. A Deep review uses the requester's enabled perspectives, blind-spot check, validator, and urgency threshold; a Standard review uses none of them. Resolution writes to the branch only when the pull request owner opted in, whoever asks. `run_mode` picks the variant: 'review' is a Deep review that chains the resolution stage per the owner's resolve_comments setting, 'review_only' is a Deep review without resolving, 'resolve_only' runs resolution only, and 'flash' is a lower-cost Standard review that never resolves comments and is refused after a published Deep review. Nonexistent, closed, and fork PRs are rejected synchronously. A PR whose current commit already has a published review in the requested mode returns 'already_reviewed' without starting a run (resolve_only skips that check, because settling threads on a reviewed head is its whole point). A request while a review runs is queued on that PR's run. Otherwise non-blocking: returns immediately with the PR's head, the review's id when one exists, and whether resolution will run, while the run executes in the worker.
* @summary Start a review of a pull request
diff --git a/services/mcp/src/tools/generated/review_hog.ts b/services/mcp/src/tools/generated/review_hog.ts
index dc9809319312..c0ab14d9eb0a 100644
--- a/services/mcp/src/tools/generated/review_hog.ts
+++ b/services/mcp/src/tools/generated/review_hog.ts
@@ -8,7 +8,8 @@ import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const ReviewHogReviewsGetSchema = () => {
const ReviewHogReviewsRetrieveParams = orvalSchemas.ReviewHogReviewsRetrieveParams()
- return ReviewHogReviewsRetrieveParams.omit({ project_id: true })
+ const ReviewHogReviewsRetrieveQueryParams = orvalSchemas.ReviewHogReviewsRetrieveQueryParams()
+ return ReviewHogReviewsRetrieveParams.omit({ project_id: true }).extend(ReviewHogReviewsRetrieveQueryParams.shape)
}
const reviewHogReviewsGet = (): ToolBase<ReturnType<typeof ReviewHogReviewsGetSchema>, Schemas.ReviewDetail> => ({
@@ -19,6 +20,9 @@ const reviewHogReviewsGet = (): ToolBase<ReturnType<typeof ReviewHogReviewsGetSc
const result = await context.api.request<Schemas.ReviewDetail>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/review_hog/reviews/${encodeURIComponent(String(params.id))}/`,
+ query: {
+ run_index: params.run_index,
+ },
})
return result
},