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): surface held-back findings to PR authors (#72868)

Alex Lebedeve5f75a833862
diff --git a/posthog/settings/access.py b/posthog/settings/access.py
index 3409403f6721..3c4dd9278faa 100644
--- a/posthog/settings/access.py
+++ b/posthog/settings/access.py
@@ -150,6 +150,11 @@ AGENT_PROXY_CALLBACK_SECRET: str | None = os.getenv("AGENT_PROXY_CALLBACK_SECRET
REVIEWHOG_TRIGGER_TOKEN: str | None = os.getenv("REVIEWHOG_TRIGGER_TOKEN") or None
REVIEWHOG_TEAM_ID: int | None = get_from_env("REVIEWHOG_TEAM_ID", optional=True, type_cast=int)
REVIEWHOG_RUN_USER_ID: int | None = get_from_env("REVIEWHOG_RUN_USER_ID", optional=True, type_cast=int)
+# The GitHub App's bot login (`<app slug>[bot]`) ReviewHog posts as. When set, the marker-based
+# idempotency scans only trust comments/reviews authored by this exact identity — otherwise any
+# installed bot could paste a public marker and suppress a publish (or get its comment PATCHed).
+# Unset falls back to trusting any Bot-typed author.
+REVIEWHOG_GITHUB_BOT_LOGIN: str = get_from_env("REVIEWHOG_GITHUB_BOT_LOGIN", "")
# These are legacy values only kept around for backwards compatibility with self hosted versions
SALT_KEY = get_list(os.getenv("SALT_KEY", "0123456789abcdefghijklmnopqrstuvwxyz"))
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index cbbbddec201a..4ec430025e13 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -210,7 +210,15 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /
finding — if all are off-diff (no inline comments resolve) the body still posts, carrying them in the
Other-findings section, so a review is never dropped wholesale. Falls back to a body-only review when
posting with inline comments fails. Authenticates with the team's installation token. Gated **per run** by `inputs.publish` (the workflow only dispatches this stage
- when publishing is on); the eval CLI defaults it off, the label trigger sets it on.
+ when publishing is on); the eval CLI defaults it off, the label trigger sets it on. Both publish-idempotency
+ marker scans (`_review_already_posted` here, `_find_marker_comment` on the status comment) trust the marker
+ only in **app-bot** comments/reviews — on a public repo anyone can paste it, and a spoofed match would
+ suppress the publish or clobber a stranger's comment. On the publish path a live **status comment**
+ (`reviewer/status_comment.py`) is posted at kickoff, edited with stage progress, and rewritten with the
+ outcome: the full found counts, what was published, and — when the urgency threshold held findings back —
+ whose threshold it was (the author's / the requester's / the default, from `resolved_from`) plus a
+ "View them in PostHog" deep link to the exact report (`/project/<team>/code_review?review=<report id>`,
+ a **permanent public contract** — the frontend URL sync and `report_deep_link` must keep agreeing on it).
---
@@ -410,7 +418,11 @@ IDOR rule) via `class X(UUIDModel, TeamScopedRootMixin)`:
key, so re-runs append turns rather than create a new report; branch-only targets key on
`(team, repository, head_branch) WHERE pr_number IS NULL`). Carries `status` (`active`/`idle`/`closed`),
`run_count`, `last_run_at`, the `head_sha` + `last_seen_comment_id` watermark, `published_head_sha`, the
- rendered `report_markdown`, `acting_user`, and the `signal_report_id` / `trigger_source` provenance.
+ rendered `report_markdown`, `acting_user`, `author_login` (the PR author's GitHub login, refreshed from the
+ fetched metadata every turn — powers the "For you" scope's authored-PRs match), `run_urgency_threshold` (the
+ gate the last **completed** turn's body/publish ran under, stamped at finalize alongside `run_count` — what
+ the drawer buckets findings by; null for pre-column turns), and the `signal_report_id` / `trigger_source`
+ provenance.
- **`ReviewReportArtefact`** — the append-only work log mirroring `SignalReportArtefact`, with a funnel that
derives `type` from the content-model class and maps `ArtefactAttribution` → `created_by_id` / `task_id`.
`ArtefactType`: `issue_finding`, `validation_verdict`, `task_run`, `commit`, `code_reference`, `note`, plus
@@ -461,6 +473,17 @@ See [DECISIONS.md](./DECISIONS.md) for the "reuse the leaf, own the model" bound
trigger (a `TaskRun` receiver auto-reviews self-driving Signals implementations). See [DECISIONS.md](./DECISIONS.md)
for each trigger's auth / scope / identity rules.
+**Review surfaces (Code review scene).** The reviews API's `scope=mine` ("For you") matches reports where the
+viewer is the **acting user OR the PR's author** — `author_login` compared case-insensitively against the
+viewer's linked GitHub login (`User.get_github_login()`, the reverse of the author→user mapping the reviewer
+runs under; no linked login → acting-user match only). `scope=everyone` is the whole project; `retrieve` is
+project-wide so any listed review opens. A specific report is linkable at `/code_review?review=<report id>`
+(mirrored to/from the drawer by `reviewHogSettingsLogic`'s URL sync; the status comment's held-back link
+targets it, so the param is a permanent contract). The drawer buckets a review's findings into published vs
+below-threshold by the detail's stored `run_urgency_threshold` — the viewer's current setting is only the
+fallback for pre-column rows — and its first tab reads "Published" only when the review actually posted
+(`published_head_sha` set), "Kept" otherwise.
+
---
## Known issues & tech debt
@@ -488,6 +511,13 @@ for each trigger's auth / scope / identity rules.
`published_head_sha` (a zero-findings or crashed turn), slots can silently mis-map. Identical rosters are always
safe. Fix belongs with cross-turn finding identity: key results by `skill_name`(+version) instead of slot, and
drop persisted selection/results whose recorded roster differs from the run's.
+- **TODO — the drawer's "Published" flag trusts the report-lifetime watermark, not the shown turn.** The
+ reviews API computes `published` as `published_head_sha IS NOT NULL`, while the drawer shows the _latest
+ completed turn_'s findings. A report that published once and later finalizes a turn that never posts
+ (store-only re-run, or `publish_review` failing past retries) shows that turn's findings under
+ "Published" with no not-published banner. Fix: `retrieve` already loads the completed head — expose
+ per-turn truth (`published_head_sha == completed_head_sha`) on the detail payload and gate the drawer's
+ published flag on it.
- **Alpha maturity** — the published comment still says "ReviewHog Alpha" and asks users to reply
"valid"/"invalid" (`reviewer/tools/publish_review.py`, the `post_promo` block). Publish is now live
per-run (the trigger endpoint posts with `publish=true`), so settle the prod wording before real users
diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.md
index 8d179e8ddaf6..50d4c852f64c 100644
--- a/products/review_hog/DECISIONS.md
+++ b/products/review_hog/DECISIONS.md
@@ -198,6 +198,49 @@ read `FINAL_REPORT.md` there first (config glossary + coverage matrix + ranking)
rate drops materially (toward ≤50%) on frozen-PR evals with the valid-finding set intact (item 5's
coverage matrix as the guard); kill if valid findings drop with the noise.
+### ✅ BUILT 2026-07-21 — held-back reviews reach PR authors (deep links, authored-PRs scope, truthful drawer + comment)
+
+Dogfooding surfaced a dead-end: a review triggered from the Code review scene runs under the **requester's**
+`urgency_threshold` ("requester wins" — deliberate, unchanged), and when every finding fell below it, publish
+self-skipped and the findings were effectively invisible to the PR author — not in their "For you" tab (which
+matched `acting_user` only), no way to link to the report (drawer state was kea-only), the status comment
+blamed "the author's … ReviewHog settings" for a threshold that wasn't theirs, and the drawer's "Published (N)"
+tab claimed publication for findings computed against the _viewer's current_ threshold. Decisions:
+
+- **Report deep links**: `/code_review?review=<report UUID>`, mirrored both ways by the existing URL sync in
+ `reviewHogSettingsLogic` (`replace`, never `push`, so drawer open/close doesn't stack history). The status
+ comment's held-back sentence links here ("View them in PostHog", auth-gated — same posture as Slack links),
+ which makes the param a **permanent public contract**. A deep link has no list row, so the drawer renders
+ entirely from the loaded detail (skeletons until then) via an id-only `openReviewDetailById` action.
+- **`ReviewReport.author_login`** (nullable, refreshed from `pr_metadata.author` every turn at upsert): the
+ "For you" scope becomes `acting_user = me OR author_login ~= my linked GitHub login` — the reverse of the
+ author→user mapping the reviewer already uses. Chosen over joining the snapshot jsonb (per-row parse on a
+ list endpoint) and over resolving login→user at write time (the mapping can change; the login is the stable
+ fact). No backfill: old rows stay null and re-stamp organically on their next turn. Accepted limit: authors
+ without a linked GitHub identity only get the PR-comment link.
+- **`ReviewReport.run_urgency_threshold`**, stamped at **finalize** (with `run_count` / `completed_head_sha`)
+ from the same snapshot the body renderer and publish gate consumed — NOT at resolve, which describes the
+ _next_ turn and would drift mid re-review under a different acting user. The drawer buckets by it; the
+ viewer-settings proxy survives only as the fallback for pre-column rows. "Published (N)" now reads "Kept (N)"
+ unless the review actually posted (`published_head_sha` set).
+- **Default-fallback threshold guard**: a default-resolved run (label trigger, unmapped author) now gates at
+ `DEFAULT_URGENCY_THRESHOLD` instead of the borrowed run user's saved threshold — the same "borrowed settings
+ must not leak into someone else's PR" rule that already forced `review_labeled_prs=True`. Applied where
+ `ResolveActingUserResult` is built so publish, the comment, and the finalize stamp agree. Consequence: a
+ default-resolved run gates at `consider`, so its held-back count is always 0 and the comment's "the default"
+ wording variant is defensive-only (kept + render-tested anyway).
+- **Bot-author guard on `_review_already_posted`**: the publish idempotency marker scan now requires
+ `user.type == "Bot"` like the status comment's `_find_marker_comment` always did — on a public repo anyone
+ can paste the marker, and a spoofed match silently suppressed the publish.
+- **Deferred residual (2026-07-24, pre-merge safety review):** the drawer's published flag is
+ report-lifetime, not per-turn — `published` = `published_head_sha IS NOT NULL`, while the drawer buckets
+ the latest completed turn. A once-published report whose later turn finalizes without posting (store-only
+ re-run, or publish failure past retries — finalize stamps before publish by design) shows that turn's
+ never-posted findings under "Published". Deferred as a follow-up with the user: the edge needs a
+ once-published report plus a never-posting later turn, and store-only re-runs are currently internal
+ experiments. Fix sketch in ARCHITECTURE.md's known issues (per-turn `published_head_sha ==
+completed_head_sha` on the detail payload).
+
### ✅ BUILT 2026-07-17 — one-shot LLM stages retry across provider overload spells
First cross-repo dogfood run (a `PostHog/billing` PR via the Stage 5c UI trigger) died in dedup on
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index b2988e6f7530..69b56a4d988f 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -4,7 +4,7 @@ from datetime import timedelta
from typing import Any, cast, get_args
from django.conf import settings
-from django.db.models import Max, QuerySet
+from django.db.models import Max, Q, QuerySet
from django.utils import timezone
from drf_spectacular.openapi import AutoSchema
@@ -70,8 +70,9 @@ class ReviewsListParamsSerializer(serializers.Serializer):
scope = serializers.ChoiceField(
choices=[SCOPE_MINE, SCOPE_EVERYONE],
default=SCOPE_MINE,
- help_text="Whose reviews to list: `mine` for reviews of the requesting user's pull requests "
- "(the default), `everyone` for every review on this project.",
+ help_text="Whose reviews to list: `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.",
)
limit = serializers.IntegerField(
default=DEFAULT_REVIEWS_LIMIT,
@@ -86,8 +87,9 @@ class PerspectiveStatsParamsSerializer(serializers.Serializer):
scope = serializers.ChoiceField(
choices=[SCOPE_MINE, SCOPE_EVERYONE],
default=SCOPE_MINE,
- help_text="Whose reviews to aggregate: `mine` for reviews of the requesting user's pull requests "
- "(the default), `everyone` for every review on this project.",
+ help_text="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.",
)
@@ -276,6 +278,13 @@ class ReviewDetailSerializer(ReviewRecentReviewSerializer):
report_markdown = serializers.CharField(
allow_blank=True, help_text="The rendered review body published to GitHub, as markdown."
)
+ run_urgency_threshold = serializers.ChoiceField(
+ choices=_PRIORITY_CHOICES,
+ allow_null=True,
+ help_text="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.",
+ )
findings = ReviewFindingSerializer(many=True, help_text="The latest 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."
@@ -450,8 +459,9 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
Read-only meta for the Code review tab's "recent reviews" block: what was reviewed, how many
valid findings at each effective priority, the reviewed PR's facts, and the pipeline shape of
- the latest turn. `list` covers the requesting user's reviews (reports where they are the acting
- user) by default, or the whole project's via `scope=everyone` — mirroring the inbox's
+ the latest turn. `list` covers the requesting user's reviews by default — reports where they are
+ the acting user OR the PR's author (`author_login` matched case-insensitively against their
+ linked GitHub login) — or the whole project's via `scope=everyone`, mirroring the inbox's
"For you / Entire project" switch; `perspective_stats` honors the same `scope` so the
effectiveness cards can follow the page-level switch. `retrieve` adds the findings themselves
(valid + dismissed) and the published review body; it is project-wide so any listed review can
@@ -469,7 +479,16 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
team_id = resolve_effective_team_id(self.team_id)
queryset = ReviewReport.objects.for_team(team_id, canonical=True)
if scope == SCOPE_MINE:
- queryset = queryset.filter(acting_user_id=request.user.id)
+ # "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
@extend_schema(
@@ -758,6 +777,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
),
"head_sha": completed_head,
"report_markdown": report.report_markdown,
+ "run_urgency_threshold": report.run_urgency_threshold 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/migrations/0019_reviewreport_author_login_and_more.py b/products/review_hog/backend/migrations/0019_reviewreport_author_login_and_more.py
new file mode 100644
index 000000000000..50f26c7c5984
--- /dev/null
+++ b/products/review_hog/backend/migrations/0019_reviewreport_author_login_and_more.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.14 on 2026-07-22 11:52
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("review_hog", "0018_backfill_urgency_threshold_to_consider"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="reviewreport",
+ name="author_login",
+ field=models.CharField(blank=True, max_length=255, null=True),
+ ),
+ migrations.AddField(
+ model_name="reviewreport",
+ name="run_urgency_threshold",
+ field=models.CharField(blank=True, max_length=20, null=True),
+ ),
+ ]
diff --git a/products/review_hog/backend/migrations/max_migration.txt b/products/review_hog/backend/migrations/max_migration.txt
index de8a8444e484..9e5990482cc7 100644
--- a/products/review_hog/backend/migrations/max_migration.txt
+++ b/products/review_hog/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0018_backfill_urgency_threshold_to_consider
+0019_reviewreport_author_login_and_more
diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.py
index 23cfb57251c9..636d844c212e 100644
--- a/products/review_hog/backend/models.py
+++ b/products/review_hog/backend/models.py
@@ -45,6 +45,11 @@ class ReviewReport(UUIDModel, TeamScopedRootMixin):
acting_user = models.ForeignKey(
"posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False
)
+ # The PR author's GitHub login, refreshed from the fetched metadata every turn. Powers the
+ # "For you" scope's authored-PRs match (compared case-insensitively against the viewer's linked
+ # GitHub login) — a teammate-triggered review of your PR lands under THEIR acting_user, so
+ # without this the findings would be invisible to you. Null until a post-column turn stamps it.
+ author_login = models.CharField(max_length=255, null=True, blank=True)
status = models.CharField(max_length=20, choices=Status, default=Status.ACTIVE)
run_count = models.IntegerField(default=0)
last_run_at = models.DateTimeField(null=True, blank=True)
@@ -54,6 +59,12 @@ class ReviewReport(UUIDModel, TeamScopedRootMixin):
# turn START. Read paths pairing stats/links with the completed turn's findings anchor here, so an
# in-flight or crashed turn's metadata never splices onto the previous turn's findings.
completed_head_sha = models.CharField(max_length=64, null=True, blank=True)
+ # The urgency threshold the last COMPLETED turn's body/publish gated on — stamped at finalize
+ # (alongside `run_count` / `completed_head_sha`) from the same resolve snapshot both consumed,
+ # so the detail view buckets published vs held-back findings truthfully even when the acting
+ # user's settings later change. Null for pre-column turns (readers fall back to the viewer's
+ # own setting as an approximation).
+ run_urgency_threshold = models.CharField(max_length=20, null=True, blank=True)
# Idempotency watermark — the head the review was last *published* to GitHub for (distinct from
# `head_sha`, what was reviewed). Publishing skips when this equals the current head, so an
# activity retry / re-trigger can't double-post the review or the one-time alpha promo comment.
diff --git a/products/review_hog/backend/reviewer/persistence.py b/products/review_hog/backend/reviewer/persistence.py
index f652982f9747..0e48c456c8ca 100644
--- a/products/review_hog/backend/reviewer/persistence.py
+++ b/products/review_hog/backend/reviewer/persistence.py
@@ -91,6 +91,7 @@ def upsert_review_report(
"pr_url": pr_url,
"head_branch": pr_metadata.head_branch,
"base_branch": pr_metadata.base_branch,
+ "author_login": pr_metadata.author or None,
"status": ReviewReport.Status.ACTIVE,
"signal_report_id": signal_report_id,
}
@@ -119,6 +120,10 @@ def upsert_review_report(
updates["pr_number"] = pr_number # branch-keyed row upgrades once its PR exists
if pr_url:
updates["pr_url"] = pr_url # a branch turn's empty URL must not erase a known PR URL
+ if pr_metadata.author:
+ # Refreshed every turn (the stable fact is the login, not a login→user resolution that
+ # can change) — old rows re-stamp organically on their next turn, no backfill.
+ updates["author_login"] = pr_metadata.author
if report.signal_report_id is None and signal_report_id is not None:
updates["signal_report_id"] = signal_report_id
qs.filter(pk=report.pk).update(**updates)
@@ -576,7 +581,15 @@ def load_prior_findings_with_verdicts(
return pairs
-def finalize_review_report(*, team_id: int, report_id: str, body_markdown: str, run_index: int, head_sha: str) -> None:
+def finalize_review_report(
+ *,
+ team_id: int,
+ report_id: str,
+ body_markdown: str,
+ run_index: int,
+ head_sha: str,
+ urgency_threshold: str | None = None,
+) -> None:
"""Mark the turn complete: store the body, bump `run_count`, stamp `last_run_at` and the reviewed head.
Idempotent per turn: the update is conditioned on `run_count == run_index - 1` (the turn's fixed
@@ -584,12 +597,16 @@ def finalize_review_report(*, team_id: int, report_id: str, body_markdown: str,
a blind `F("run_count") + 1` would double-bump and break the `run_index == run_count` invariant
every latest-turn reader relies on. `completed_head_sha` records what this finished turn reviewed;
the live `head_sha` watermark already points at the NEXT turn's commit the moment that turn starts.
+ `urgency_threshold` is the resolve snapshot the turn's body/publish gated on — stamped HERE, not
+ at resolve (which describes the *next* turn and would drift mid re-review under a different
+ acting user), so the detail view buckets published vs held-back findings by the gate that ran.
"""
ReviewReport.objects.for_team(team_id).filter(id=report_id, run_count=run_index - 1).update(
report_markdown=body_markdown,
run_count=run_index,
last_run_at=timezone.now(),
completed_head_sha=head_sha,
+ run_urgency_threshold=urgency_threshold,
status=ReviewReport.Status.IDLE,
)
diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.py
index 007efdd9b6e0..eb700ca13946 100644
--- a/products/review_hog/backend/reviewer/status_comment.py
+++ b/products/review_hog/backend/reviewer/status_comment.py
@@ -16,6 +16,7 @@ import logging
from datetime import timedelta
from typing import Any
+from django.conf import settings
from django.db.models import Q
from django.utils import timezone
@@ -36,6 +37,7 @@ from products.review_hog.backend.reviewer.tools.github_client import (
GitHubAPIError,
github_api_get_paginated,
github_api_request,
+ is_app_bot_author,
)
logger = logging.getLogger(__name__)
@@ -63,6 +65,19 @@ _THRESHOLD_LABELS = {
IssuePriority.MUST_FIX: "Must fix",
}
+# Whose threshold gated publishing, keyed by how the acting user resolved (`resolved_from`): the PR
+# author's own settings, the requester's ("requester wins" when someone else triggers the review),
+# or the built-in default when the author has no linked PostHog user. The default variant is
+# defensive — a default-resolved run gates at "All issues", so nothing can be held back — but the
+# comment must never blame a settings page that played no part.
+_THRESHOLD_ATTRIBUTIONS = {
+ "author": "the author's",
+ "override": "the requester's",
+ "default": "the default",
+}
+# Only personal thresholds live in someone's ReviewHog settings; the default variant has no page to point at.
+_PERSONAL_THRESHOLD_SOURCES = frozenset({"author", "override"})
+
_PRIORITY_LABELS = {
IssuePriority.MUST_FIX: "must fix",
IssuePriority.SHOULD_FIX: "should fix",
@@ -96,6 +111,16 @@ def status_marker(report_id: str) -> str:
return f"<!-- reviewhog:status:{report_id} -->"
+def report_deep_link(team_id: int, report_id: str) -> str:
+ """The app URL opening this report's review drawer — the held-back "View them in PostHog" target.
+
+ `?review=<report id>` is a permanent public contract (baked into GitHub comments that never get
+ re-edited); the frontend's Code review URL sync accepts exactly this param, so the two must keep
+ agreeing. Auth-gated like any app link — the same posture as posting Slack links publicly.
+ """
+ return f"{settings.SITE_URL}/project/{team_id}/code_review?review={report_id}"
+
+
def _plural(count: int, noun: str) -> str:
return f"{count} {noun}" if count == 1 else f"{count} {noun}s"
@@ -130,11 +155,16 @@ def render_final_body(
held_back_count: int,
threshold: IssuePriority,
review_url: str | None,
+ resolved_from: str = "author",
+ report_url: str | None = None,
) -> str:
"""The completed-state body: the full found counts, and how many the threshold held back.
The counts always show everything the run found, even when only a subset was published, so
- two inline comments on the PR never read as "the review only found two things".
+ two inline comments on the PR never read as "the review only found two things". The held-back
+ sentence attributes the gating threshold to whoever it actually belonged to (`resolved_from`)
+ and links to the report in PostHog (`report_url`, auth-gated) — the PR is otherwise the only
+ place the author hears about held-back findings, so the comment must not dead-end.
"""
found_total = sum(counts.values())
found_line = "Found " + ", ".join(
@@ -160,11 +190,18 @@ def render_final_body(
published_line += f" ([view the review]({review_url}))"
lines.append(published_line + ".")
if held_back_count > 0:
- lines.append(
- f"{_plural(held_back_count, 'finding')} stayed below the author's "
- f'"{_THRESHOLD_LABELS[threshold]}" urgency threshold in their ReviewHog settings, '
- "so they were not published."
+ # An unrecognized resolved_from reads as "author" throughout (attribution AND suffix).
+ source = resolved_from if resolved_from in _THRESHOLD_ATTRIBUTIONS else "author"
+ sentence = (
+ f"{_plural(held_back_count, 'finding')} stayed below {_THRESHOLD_ATTRIBUTIONS[source]} "
+ f'"{_THRESHOLD_LABELS[threshold]}" urgency threshold'
)
+ if source in _PERSONAL_THRESHOLD_SOURCES:
+ sentence += " in their ReviewHog settings"
+ sentence += ", so they were not published."
+ if report_url:
+ sentence += f" [View them in PostHog]({report_url})."
+ lines.append(sentence)
lines.extend(["", status_marker(report_id)])
return "\n".join(lines)
@@ -204,9 +241,10 @@ def _find_marker_comment(
installation_id=installation_id,
endpoint="/repos/{owner}/{repo}/issues/{issue_number}/comments",
):
- # Adopt only app-bot comments: anyone can paste the marker on a public repo, and the
- # returned id gets PATCHed — matching a stranger's comment would overwrite it.
- if (comment.get("user") or {}).get("type") != "Bot":
+ # Adopt only our own app-bot's comments (`is_app_bot_author`): anyone can paste the marker
+ # on a public repo, and the returned id gets PATCHed — matching a stranger's comment would
+ # overwrite it.
+ if not is_app_bot_author(comment.get("user")):
continue
if marker in (comment.get("body") or ""):
return comment.get("id")
@@ -342,6 +380,7 @@ def finalize_status_comment(
run_index: int,
urgency_threshold: str,
review_url: str | None,
+ resolved_from: str = "author",
) -> None:
"""Rewrite the status comment with the turn's outcome: everything found vs. what was published."""
try:
@@ -362,6 +401,8 @@ def finalize_status_comment(
held_back_count=held_back_count,
threshold=threshold,
review_url=review_url,
+ resolved_from=resolved_from,
+ report_url=report_deep_link(team_id, report_id),
)
_edit_and_stamp(team_id, report, body)
except Exception:
diff --git a/products/review_hog/backend/reviewer/tests/test_publish_review.py b/products/review_hog/backend/reviewer/tests/test_publish_review.py
index 07511190fcb8..6d93851cdbfc 100644
--- a/products/review_hog/backend/reviewer/tests/test_publish_review.py
+++ b/products/review_hog/backend/reviewer/tests/test_publish_review.py
@@ -196,9 +196,13 @@ class TestPostGithubReview:
def test_skips_when_a_review_with_our_marker_is_already_present(
self, mock_request: MagicMock, mock_paginated: MagicMock
) -> None:
- # Post-then-crash idempotency: a review already carrying this run's marker means we posted but
- # didn't record the watermark, so the retry must post neither a second review nor the promo.
- _wire_readbacks(mock_paginated, reviews=[{"body": "an earlier review\n\nmarker-xyz"}])
+ # Post-then-crash idempotency: an app-bot review already carrying this run's marker means we
+ # posted but didn't record the watermark, so the retry must post neither a second review nor
+ # the promo. (Only bot reviews count — a pasted marker in a human review must not match.)
+ _wire_readbacks(
+ mock_paginated,
+ reviews=[{"body": "an earlier review\n\nmarker-xyz", "user": {"login": "posthog[bot]", "type": "Bot"}}],
+ )
_post_github_review(
"o", "r", 1, "body", [], token="t", head_sha="s", post_promo=True, marker="marker-xyz", promo_marker="pm"
diff --git a/products/review_hog/backend/reviewer/tools/github_client.py b/products/review_hog/backend/reviewer/tools/github_client.py
index ea20cc8ac86c..d36c998f7f90 100644
--- a/products/review_hog/backend/reviewer/tools/github_client.py
+++ b/products/review_hog/backend/reviewer/tools/github_client.py
@@ -10,6 +10,8 @@ import logging
from collections.abc import Iterator
from typing import Any
+from django.conf import settings
+
import requests
from posthog.egress.github.transport import github_request, raise_if_github_rate_limited
@@ -17,6 +19,23 @@ from posthog.egress.limiter.policies import Priority
logger = logging.getLogger(__name__)
+
+def is_app_bot_author(user: dict[str, Any] | None) -> bool:
+ """Whether a GitHub review/comment author is OUR app's bot identity.
+
+ Guards the marker-based idempotency scans: on a public repo anyone can paste a marker, and a
+ spoofed match suppresses a publish or gets a stranger's comment PATCHed. `type == "Bot"` blocks
+ human spoofers; when `REVIEWHOG_GITHUB_BOT_LOGIN` is configured (the app's `<slug>[bot]` login),
+ markers pasted by OTHER installed bots are rejected too. Unset fails open to the type check —
+ the app's own login isn't derivable from an installation token without extra API calls.
+ """
+ author = user or {}
+ if author.get("type") != "Bot":
+ return False
+ expected = settings.REVIEWHOG_GITHUB_BOT_LOGIN
+ return author.get("login") == expected if expected else True
+
+
GITHUB_API_BASE = "https://api.github.com"
_SOURCE = "review_hog"
diff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.py
index a28876aa8b5f..00d46779b166 100644
--- a/products/review_hog/backend/reviewer/tools/publish_review.py
+++ b/products/review_hog/backend/reviewer/tools/publish_review.py
@@ -15,6 +15,7 @@ from products.review_hog.backend.reviewer.tools.github_client import (
GitHubAPIError,
github_api_get_paginated,
github_api_request,
+ is_app_bot_author,
)
logger = logging.getLogger(__name__)
@@ -329,11 +330,14 @@ def _review_already_posted(
"""True if a review carrying this run's `marker` is already on the PR (we posted, then crashed).
Best-effort idempotency backstop: if the readback fails we proceed to post rather than silently
- drop the review — the `published_head_sha` watermark still guards the common retry path.
+ drop the review — the `published_head_sha` watermark still guards the common retry path. Only
+ our own app-bot's reviews count (`is_app_bot_author`, shared with the status comment's marker
+ scan): on a public repo anyone can paste the marker, and a spoofed match would silently
+ suppress the publish.
"""
try:
return any(
- marker in (review.get("body") or "")
+ is_app_bot_author(review.get("user")) and marker in (review.get("body") or "")
for review in github_api_get_paginated(
f"/repos/{owner}/{repo}/pulls/{pr_number}/reviews",
token=token,
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index 625d9e29667b..f7a2f3dc27e0 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -33,6 +33,7 @@ from products.review_hog.backend.reviewer.constants import (
CHUNKING_ONESHOT_MAX_ADDITIONS,
CHUNKING_REASONING_EFFORT,
CHUNKING_RUNTIME_ADAPTER,
+ DEFAULT_URGENCY_THRESHOLD,
REVIEW_INITIAL_PERMISSION_MODE,
REVIEW_MODEL,
REVIEW_REASONING_EFFORT,
@@ -390,6 +391,9 @@ class FinalizeStatusCommentInput:
# The run's snapshotted threshold, so the held-back explanation matches what publish enforced.
urgency_threshold: str
review_url: str | None = None
+ # Whose threshold gated the run ("author" / "override" / "default", from the resolve snapshot) —
+ # the held-back sentence must blame the right settings. Defaulted so pre-field payloads deserialize.
+ resolved_from: str = "author"
# --- Setup activities ------------------------------------------------------------------------------
@@ -604,8 +608,14 @@ def _resolve_acting_user(
# user never imports their personal switch into someone else's PR.
review_labeled_prs=settings.review_labeled_prs if resolved_from in ("author", "override") else True,
# str() unwraps the TextChoices member an unsaved defaults instance carries — the payload
- # must hold the plain value.
- urgency_threshold=str(settings.urgency_threshold),
+ # must hold the plain value. A default-resolved run gates at the built-in default, never the
+ # borrowed run user's saved threshold — the same "borrowed settings must not leak into
+ # someone else's PR" rule that forces review_labeled_prs above.
+ urgency_threshold=(
+ str(settings.urgency_threshold)
+ if resolved_from in ("author", "override")
+ else DEFAULT_URGENCY_THRESHOLD.value
+ ),
review_inbox_prs=settings.review_inbox_prs,
resolved_from=resolved_from,
)
@@ -1152,7 +1162,14 @@ def _build_and_finalize(
published_priorities=published_priorities_for(IssuePriority(urgency_threshold)),
)
finalize_review_report(
- team_id=team_id, report_id=report_id, body_markdown=body, run_index=run_index, head_sha=head_sha
+ team_id=team_id,
+ report_id=report_id,
+ body_markdown=body,
+ run_index=run_index,
+ head_sha=head_sha,
+ # The same snapshot the body above and the publish gate consume — stamped so the detail view
+ # buckets this turn's findings by the gate that actually ran.
+ urgency_threshold=urgency_threshold,
)
@@ -1239,6 +1256,7 @@ async def finalize_status_comment_activity(input: FinalizeStatusCommentInput) ->
run_index=input.run_index,
urgency_threshold=input.urgency_threshold,
review_url=input.review_url,
+ resolved_from=input.resolved_from,
)
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index 6e140504126b..8197f829f18e 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -608,6 +608,7 @@ class ReviewPRWorkflow:
run_index=meta.run_index,
urgency_threshold=acting.urgency_threshold,
review_url=publish_result.review_url if publish_result is not None else None,
+ resolved_from=acting.resolved_from,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
diff --git a/products/review_hog/backend/tests/test_acting_user.py b/products/review_hog/backend/tests/test_acting_user.py
index 67f1a4d4bac4..26754abba70e 100644
--- a/products/review_hog/backend/tests/test_acting_user.py
+++ b/products/review_hog/backend/tests/test_acting_user.py
@@ -86,6 +86,22 @@ class TestResolveActingUser(BaseTest):
assert (as_default.acting_user_id, as_default.resolved_from) == (self.user.id, "default")
assert as_default.review_labeled_prs is True
+ def test_urgency_threshold_follows_personal_sources_but_never_a_borrowed_default_user(self) -> None:
+ # The publish-gate twin of the opt-out rule above: the run user's saved must_fix threshold
+ # must not decide what lands on someone ELSE's PR — a default-resolved run gates at the
+ # built-in default. Personal resolutions (author, requester override) keep the saved value.
+ ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, urgency_threshold=ReviewUserSettings.UrgencyThreshold.MUST_FIX
+ )
+ as_author = _resolve_acting_user(self.team.id, "octocat", None, trigger_source=TRIGGER_LABEL)
+ assert (as_author.resolved_from, as_author.urgency_threshold) == ("author", "must_fix")
+ as_override = _resolve_acting_user(self.team.id, "ghost", self.user.id, trigger_source=TRIGGER_LABEL)
+ assert (as_override.resolved_from, as_override.urgency_threshold) == ("override", "must_fix")
+ as_default = _resolve_acting_user(
+ self.team.id, "ghost", None, trigger_source=TRIGGER_LABEL, default_user_id=self.user.id
+ )
+ assert (as_default.resolved_from, as_default.urgency_threshold) == ("default", "consider")
+
def test_resolve_stamps_the_acting_user_onto_the_report(self) -> None:
# "Your recent reviews" filters on this stamp — if resolve stops writing it, the list goes empty.
report = ReviewReport.objects.for_team(self.team.id).create(
diff --git a/products/review_hog/backend/tests/test_persistence.py b/products/review_hog/backend/tests/test_persistence.py
index 636379a546ae..40de436d52c9 100644
--- a/products/review_hog/backend/tests/test_persistence.py
+++ b/products/review_hog/backend/tests/test_persistence.py
@@ -45,7 +45,7 @@ def _content_as(model: type[_ContentT], artefact_type: str, content: str) -> _Co
return parsed
-def _pr_metadata(pr_number: int = 123, head_sha: str | None = None) -> PRMetadata:
+def _pr_metadata(pr_number: int = 123, head_sha: str | None = None, author: str = "a") -> PRMetadata:
return PRMetadata(
number=pr_number,
title="t",
@@ -53,7 +53,7 @@ def _pr_metadata(pr_number: int = 123, head_sha: str | None = None) -> PRMetadat
draft=False,
created_at="2026-01-01T00:00:00Z",
updated_at="2026-01-01T00:00:00Z",
- author="a",
+ author=author,
base_branch="main",
head_branch="feat",
head_sha=head_sha,
@@ -105,6 +105,34 @@ class TestUpsertReviewReport(BaseTest):
assert report.status == ReviewReport.Status.IDLE
assert report.completed_head_sha == "sha-2" # what the finished turn reviewed, for read anchoring
+ def test_author_login_is_stamped_on_create_and_refreshed_each_turn(self) -> None:
+ # The "For you" scope's authored-PRs match rides this stamp. It must track the PR's current
+ # author (the login is the stable fact, not a login→user resolution), and a turn with
+ # unknown authorship must not erase a known one.
+ report_id = upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata())
+ assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).author_login == "a"
+ upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata(author="b"))
+ assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).author_login == "b"
+ upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata(author=""))
+ assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).author_login == "b"
+
+ def test_finalize_stamps_the_turns_urgency_threshold(self) -> None:
+ # The detail view buckets published vs held-back findings by this stamp; a finalize that
+ # stops writing it silently reverts the drawer to bucketing by the VIEWER's settings — the
+ # exact lie the stamp exists to fix. Absent (pre-column) turns stay null for the fallback.
+ report_id = upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata())
+ assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).run_urgency_threshold is None
+ finalize_review_report(
+ team_id=self.team.id,
+ report_id=report_id,
+ body_markdown="# r",
+ run_index=1,
+ head_sha="sha-1",
+ urgency_threshold="must_fix",
+ )
+ report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
+ assert (report.run_urgency_threshold, report.run_count) == ("must_fix", 1)
+
def test_finalize_is_idempotent_within_a_turn(self) -> None:
# build_body_activity retries on worker crash after its finalize committed: the retry must
# not double-bump run_count, or run_index != run_count and every latest-turn reader (list
diff --git a/products/review_hog/backend/tests/test_publish_idempotency.py b/products/review_hog/backend/tests/test_publish_idempotency.py
index 31033cbd948f..8d6a7d8536eb 100644
--- a/products/review_hog/backend/tests/test_publish_idempotency.py
+++ b/products/review_hog/backend/tests/test_publish_idempotency.py
@@ -4,6 +4,8 @@ from typing import Any
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.test import override_settings
+
from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.persistence import upsert_review_report
@@ -47,12 +49,23 @@ def _promo_posted(marker: str, comments: list[dict[str, Any]], *, boom: bool = F
def test_review_already_posted_detects_our_own_markered_review() -> None:
- # Post-then-crash backstop: a review we posted carries this run's marker, so a retry recognizes it
- # and skips. A review without the marker (another turn/author) must not match.
+ # Post-then-crash backstop: a review we posted (an app-bot review) carries this run's marker, so
+ # a retry recognizes it and skips. A review without the marker (another turn/author) must not
+ # match — and neither may a human review carrying a pasted marker: on a public repo anyone can
+ # copy it, and a match here silently suppresses the publish.
marker = _review_marker("rep-1", "sha1")
- assert _review_posted(marker, [{"body": f"body text\n\n{marker}"}]) is True
- assert _review_posted(marker, [{"body": "an unrelated review"}, {"body": None}]) is False
- assert _review_posted(marker, [{"body": _review_marker("rep-1", "other-sha")}]) is False
+ bot = {"user": {"login": "posthog[bot]", "type": "Bot"}}
+ assert _review_posted(marker, [{"body": f"body text\n\n{marker}", **bot}]) is True
+ assert _review_posted(marker, [{"body": "an unrelated review", **bot}, {"body": None, **bot}]) is False
+ assert _review_posted(marker, [{"body": _review_marker("rep-1", "other-sha"), **bot}]) is False
+ assert (
+ _review_posted(marker, [{"body": f"pasted: {marker}", "user": {"login": "prankster", "type": "User"}}]) is False
+ )
+ assert _review_posted(marker, [{"body": f"no user field: {marker}"}]) is False
+ # With the app's bot login configured, another installed bot's pasted marker must not match either.
+ with override_settings(REVIEWHOG_GITHUB_BOT_LOGIN="posthog[bot]"):
+ assert _review_posted(marker, [{"body": marker, **bot}]) is True
+ assert _review_posted(marker, [{"body": marker, "user": {"login": "rogue[bot]", "type": "Bot"}}]) is False
def test_review_already_posted_proceeds_when_readback_fails() -> None:
diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.py
index 70a1a7c15b61..374efc309117 100644
--- a/products/review_hog/backend/tests/test_reviews_api.py
+++ b/products/review_hog/backend/tests/test_reviews_api.py
@@ -5,6 +5,8 @@ from posthog.test.base import APIBaseTest
from django.utils import timezone
+from social_django.models import UserSocialAuth
+
from posthog.models import Team, User
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
@@ -148,6 +150,25 @@ class TestRecentReviewsAPI(APIBaseTest):
assert rows[0]["published"] is False
assert "perspective_selection" not in rows[0] # detail-only payload — the list stays lean
+ def test_mine_scope_includes_reviews_of_prs_i_authored(self) -> None:
+ # The incident this guards: a review a teammate triggers on your PR lands under THEIR
+ # acting_user, so without the author_login match it never reaches your "For you" tab — the
+ # findings are effectively invisible to you. The match rides the viewer's linked GitHub
+ # login (case-insensitively); without a linked login the old acting-user-only behavior holds.
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self._report(pr_number=1, acting_user=other, author_login="OctoCat")
+ self._report(pr_number=2, acting_user=other, author_login="someone-else")
+ self._report(pr_number=3, acting_user=self.user)
+
+ # No linked GitHub identity: only reviews where I'm the acting user.
+ assert {r["pr_number"] for r in self.client.get(self.url).json()["results"]} == {3}
+
+ # Linked identity (stored casing differs from the stamped login): authored PRs join the
+ # scope — for the list AND the perspective_stats aggregation, which share the filter.
+ UserSocialAuth.objects.create(user=self.user, provider="github", uid="gh-1", extra_data={"login": "octocat"})
+ assert {r["pr_number"] for r in self.client.get(self.url).json()["results"]} == {1, 3}
+ assert self.client.get(f"{self.url}perspective_stats/").json()["report_count"] == 2
+
def test_list_scope_everyone_covers_the_whole_project(self) -> None:
# The "Entire project" switch: everyone-scope must include teammates' reviews but never
# another team's (tenant isolation), and a bad scope value must 400 — proving the params
@@ -321,8 +342,12 @@ class TestRecentReviewsAPI(APIBaseTest):
def test_retrieve_splits_findings_and_returns_the_published_body(self) -> None:
# The drawer's contract: valid findings (most urgent first, validator override applied),
- # dismissed ones separately, unjudged ones in neither, and the published body verbatim.
- report = self._report(pr_number=7, acting_user=self.user, report_markdown="## Review body")
+ # dismissed ones separately, unjudged ones in neither, the published body verbatim, and the
+ # run's stored threshold (what the drawer buckets by — the viewer's setting is only a
+ # fallback for pre-column rows).
+ report = self._report(
+ pr_number=7, acting_user=self.user, report_markdown="## Review body", run_urgency_threshold="should_fix"
+ )
self._finding(report, "1-low", priority=IssuePriority.CONSIDER)
self._finding(report, "1-high", priority=IssuePriority.MUST_FIX, adjusted=IssuePriority.SHOULD_FIX)
self._finding(report, "1-noise", priority=IssuePriority.SHOULD_FIX, is_valid=False)
@@ -333,6 +358,7 @@ class TestRecentReviewsAPI(APIBaseTest):
assert res.status_code == 200
detail = res.json()
assert detail["report_markdown"] == "## Review body"
+ assert detail["run_urgency_threshold"] == "should_fix"
assert [f["title"] for f in detail["findings"]] == ["title 1-high", "title 1-low"]
high = detail["findings"][0]
assert (high["effective_priority"], high["reviewer_priority"]) == ("should_fix", "must_fix")
diff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.py
index b8ec755e80ca..3753b486fa61 100644
--- a/products/review_hog/backend/tests/test_status_comment.py
+++ b/products/review_hog/backend/tests/test_status_comment.py
@@ -124,6 +124,33 @@ class TestRenderFinalBody:
assert fragment not in body, f"unexpected {fragment!r} in:\n{body}"
assert status_marker("rid") in body
+ @parameterized.expand(
+ [
+ # Whose settings gated the run must be named truthfully: blaming "the author's" settings
+ # for a requester-gated run is the exact misattribution this wording exists to fix, and
+ # the defensive default variant has no settings page to point at.
+ ("author", 'the author\'s "Should fix" urgency threshold in their ReviewHog settings'),
+ ("override", 'the requester\'s "Should fix" urgency threshold in their ReviewHog settings'),
+ ("default", 'the default "Should fix" urgency threshold,'),
+ # An unknown future value must degrade to the author wording, not crash the comment.
+ ("mystery", 'the author\'s "Should fix" urgency threshold in their ReviewHog settings'),
+ ]
+ )
+ def test_held_back_sentence_attributes_the_gating_threshold(self, resolved_from: str, expected: str) -> None:
+ body = render_final_body(
+ "rid",
+ counts={IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 0, IssuePriority.CONSIDER: 2},
+ published_count=0,
+ held_back_count=2,
+ threshold=IssuePriority.SHOULD_FIX,
+ review_url=None,
+ resolved_from=resolved_from,
+ report_url="https://ph.test/project/1/code_review?review=rid",
+ )
+ assert f"2 findings stayed below {expected}" in body, body
+ # Held-back findings are otherwise invisible to the author — the comment must not dead-end.
+ assert "[View them in PostHog](https://ph.test/project/1/code_review?review=rid)" in body
+
@patch(f"{_MODULE}.random.choice", return_value=("https://example.test/dog.png", "A happy dog"))
def test_uses_the_randomly_selected_clean_review_media(self, mock_choice: MagicMock) -> None:
body = render_final_body(
@@ -331,6 +358,9 @@ class TestFinalizeStatusComment(BaseTest):
assert "Found **1 must fix**, **0 should fix**, **2 consider**" in body
assert "Published 1 finding ([view the review](https://g/review))" in body
assert '2 findings stayed below the author\'s "Should fix" urgency threshold' in body
+ # The held-back link into the app. `?review=<report id>` is a permanent public contract
+ # (baked into GitHub comments) — the frontend's URL sync accepts exactly this param.
+ assert f"/project/{self.team.id}/code_review?review={report_id})" in body
def test_failed_edit_rewrites_the_comment_as_failed(
self, mock_request: MagicMock, mock_integration: MagicMock
diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.py
index febad550bd8f..1e96aa44b013 100644
--- a/products/review_hog/backend/tests/test_temporal_workflow.py
+++ b/products/review_hog/backend/tests/test_temporal_workflow.py
@@ -23,6 +23,7 @@ from products.review_hog.backend.temporal.activities import (
AppendCodeReviewArtefactInput,
BuildBodyInput,
DedupResult,
+ FinalizeStatusCommentInput,
LoadBlindSpotsInput,
LoadedBlindSpotsSkillDTO,
LoadedPerspectiveDTO,
@@ -95,6 +96,9 @@ async def _run_full_review_pr_workflow(
publish_calls: list[int] = []
# Each code_review receipt appended to the signals report, as (outcome, review_url).
receipt_calls: list[tuple[str, str | None]] = []
+ # The outcome edit of the PR status comment, as (urgency_threshold, resolved_from, review_url) —
+ # all three must be the resolve/publish values, or the comment misattributes the gate.
+ finalize_status_calls: list[tuple[str, str, str | None]] = []
# The urgency threshold each downstream consumer received (must be the resolve snapshot's value).
threshold_calls: list[tuple[str, str]] = []
# The user id the parent threads into the perspective / blind-spots / validation loads (should be
@@ -124,12 +128,14 @@ async def _run_full_review_pr_workflow(
@activity.defn(name="resolve_acting_user_activity")
async def resolve_acting_user(input) -> ResolveActingUserResult:
- # A non-default threshold, so the threading asserts can't pass on the dataclass defaults.
+ # Non-default threshold and resolved_from, so the threading asserts can't pass on the
+ # dataclass defaults.
return ResolveActingUserResult(
acting_user_id=acting_user_id,
review_labeled_prs=review_labeled_prs,
urgency_threshold="must_fix",
review_inbox_prs=review_inbox_prs,
+ resolved_from="override",
)
@activity.defn(name="sync_review_skills_activity")
@@ -215,6 +221,19 @@ async def _run_full_review_pr_workflow(
receipt_calls.append((input.outcome, input.review_url))
return None
+ @activity.defn(name="post_status_comment_activity")
+ async def post_status(input) -> None:
+ return None
+
+ @activity.defn(name="finalize_status_comment_activity")
+ async def finalize_status(input: FinalizeStatusCommentInput) -> None:
+ finalize_status_calls.append((input.urgency_threshold, input.resolved_from, input.review_url))
+ return None
+
+ @activity.defn(name="fail_status_comment_activity")
+ async def fail_status(input) -> None:
+ return None
+
result: str | None = None
failed = False
task_queue = str(uuid.uuid4())
@@ -244,6 +263,9 @@ async def _run_full_review_pr_workflow(
build_body,
publish_act,
append_receipt,
+ post_status,
+ finalize_status,
+ fail_status,
],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
@@ -279,6 +301,7 @@ async def _run_full_review_pr_workflow(
"receipts": receipt_calls,
"load_user_ids": load_user_ids,
"thresholds": threshold_calls,
+ "finalize_status": finalize_status_calls,
}
@@ -355,6 +378,10 @@ async def test_review_pr_workflow_publishes_only_when_publish_true():
# The acting user's threshold snapshot (not the dataclass default) reaches both consumers, so
# body counts and posted comments gate on the same set.
assert recorded["thresholds"] == [("body", "must_fix"), ("publish", "must_fix")]
+ # The outcome edit gets the same snapshot PLUS whose threshold it was (resolved_from) and the
+ # posted review's URL — dropping any of these reverts the comment to blaming the author's
+ # settings or linking nowhere.
+ assert recorded["finalize_status"] == [("must_fix", "override", _REVIEW_URL)]
@pytest.mark.asyncio
diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsx
index fa826c21cc29..2adfc3188697 100644
--- a/products/review_hog/frontend/CodeReviewScene.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.tsx
@@ -775,8 +775,8 @@ function DrawerPublishedTab(): JSX.Element {
return (
<div className="text-sm text-secondary">
{isPublished
- ? 'Nothing crossed your urgency threshold — no comments were posted to the pull request.'
- : "Nothing crossed your urgency threshold, and this review hasn't been published to the pull request."}
+ ? "Nothing crossed the review's urgency threshold — no comments were posted to the pull request."
+ : "Nothing crossed the review's urgency threshold, and this review hasn't been published to the pull request."}
</div>
)
}
@@ -784,8 +784,8 @@ function DrawerPublishedTab(): JSX.Element {
<div className="flex flex-col gap-2">
{!isPublished && (
<p className="m-0 text-xs text-secondary">
- This review hasn't been published to the pull request yet — these findings crossed your urgency
- threshold, but no comments have been posted.
+ This review hasn't been published to the pull request yet — these findings crossed the review's
+ urgency threshold, but no comments have been posted.
</p>
)}
<div className="flex flex-col divide-y divide-primary">
@@ -807,14 +807,15 @@ function DrawerBelowThresholdTab(): JSX.Element {
if (!reviewFindingsSplit.belowThreshold.length) {
return (
<div className="text-sm text-secondary">
- Nothing was held back — every validated finding crossed your urgency threshold.
+ Nothing was held back — every validated finding crossed the review's urgency threshold.
</div>
)
}
return (
<div className="flex flex-col gap-2">
<p className="m-0 text-xs text-secondary">
- Validated as real, but under the bar you set — kept here instead of the pull request.
+ Validated as real, but under the urgency bar this review ran with — kept here instead of the pull
+ request.
</p>
<div className="flex flex-col divide-y divide-primary">
{reviewFindingsSplit.belowThreshold.map((finding, i) => (
@@ -993,7 +994,13 @@ function ReviewDetailDrawer(): JSX.Element {
tabs={[
{
key: 'published',
- label: `Published${reviewFindingsSplit ? ` (${reviewFindingsSplit.published.length})` : ''}`,
+ // "Published" is a claim about the PR — only make it when the review
+ // actually posted; findings a store-only run kept above the bar read
+ // "Kept". `review` falls back to the list row, so a published review
+ // doesn't flash "Kept" while its detail loads.
+ label: `${review?.published ? 'Published' : 'Kept'}${
+ reviewFindingsSplit ? ` (${reviewFindingsSplit.published.length})` : ''
+ }`,
content: <DrawerPublishedTab />,
},
{
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 77ffc6dfc7dc..c096bfb14ed4 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -204,16 +204,6 @@ 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
@@ -227,6 +217,16 @@ 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
@@ -392,6 +392,12 @@ export interface ReviewDetailApi {
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.
+ *
+ * * `must_fix` - must_fix
+ * * `should_fix` - should_fix
+ * * `consider` - consider */
+ run_urgency_threshold: ReviewIssuePriorityEnumApi | null
/** The latest turn's validated findings, most urgent first. */
findings: ReviewFindingApi[]
/** The latest turn's findings the validator dismissed, with its reasoning. */
@@ -500,7 +506,7 @@ export type ReviewHogReviewsListParams = {
*/
limit?: number
/**
- * Whose reviews to list: `mine` for reviews of the requesting user's pull requests (the default), `everyone` for every review on this project.
+ * Whose reviews to list: `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.
*
* * `mine` - mine
* * `everyone` - everyone
@@ -518,7 +524,7 @@ export const ReviewHogReviewsListScope = {
export type ReviewHogReviewsPerspectiveStatsRetrieveParams = {
/**
- * Whose reviews to aggregate: `mine` for reviews of the requesting user's pull requests (the default), `everyone` for every review on this project.
+ * 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.
*
* * `mine` - mine
* * `everyone` - everyone
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
index 3e250b098c83..49bcfe38485a 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
@@ -1,6 +1,8 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { urls } from 'scenes/urls'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -8,6 +10,20 @@ import { ReviewHogReviewsListScope } from 'products/review_hog/frontend/generate
import { MAX_REVIEWS_LIMIT, REVIEWS_PAGE_SIZE, reviewHogSettingsLogic } from './reviewHogSettingsLogic'
+/** A minimal review detail: only the fields the drawer selectors read. */
+function reviewDetail(id: string, runUrgencyThreshold: string | null): Record<string, any> {
+ return {
+ id,
+ published: false,
+ run_urgency_threshold: runUrgencyThreshold,
+ findings: [
+ { title: 'blocker', effective_priority: 'must_fix' },
+ { title: 'recommended', effective_priority: 'should_fix' },
+ ],
+ dismissed_findings: [],
+ }
+}
+
// More project-wide reviews than the API's maximum limit, so both "Show more" growth and its
// ceiling are reachable.
const everyoneReviews = Array.from({ length: MAX_REVIEWS_LIMIT + REVIEWS_PAGE_SIZE }, (_, i) => ({
@@ -254,6 +270,93 @@ describe('reviewHogSettingsLogic', () => {
await expectLogic(logic).toMatchValues({ reviewsLimit: REVIEWS_PAGE_SIZE })
})
+ it('buckets drawer findings by the stored run threshold, with the viewer proxy only for old rows', async () => {
+ // The run gated at must_fix while the viewer's own setting (mocked above) is should_fix.
+ // Bucketing by the viewer's setting would show the held-back should_fix finding as
+ // published — the exact lie the stored snapshot exists to fix.
+ useMocks({
+ get: {
+ '/api/projects/:team_id/review_hog/reviews/r-stamped/': () => [
+ 200,
+ reviewDetail('r-stamped', 'must_fix'),
+ ],
+ '/api/projects/:team_id/review_hog/reviews/r-old/': () => [200, reviewDetail('r-old', null)],
+ },
+ })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadSettingsSuccess'])
+
+ logic.actions.openReviewDetailById('r-stamped')
+ await expectLogic(logic).toDispatchActions(['loadReviewDetailSuccess'])
+ expect(logic.values.reviewFindingsSplit?.published.map((f) => f.title)).toEqual(['blocker'])
+ expect(logic.values.reviewFindingsSplit?.belowThreshold.map((f) => f.title)).toEqual(['recommended'])
+
+ // A pre-column row (null stored threshold) keeps the old viewer-settings approximation.
+ logic.actions.openReviewDetailById('r-old')
+ await expectLogic(logic).toDispatchActions(['loadReviewDetailSuccess'])
+ expect(logic.values.reviewFindingsSplit?.published.map((f) => f.title)).toEqual(['blocker', 'recommended'])
+ expect(logic.values.reviewFindingsSplit?.belowThreshold).toEqual([])
+ })
+
+ it('opens a review from ?review= and mirrors drawer state back to the URL', async () => {
+ // ?review=<report id> is a permanent public contract: PR status comments bake this exact
+ // param into their "View them in PostHog" links, so renaming the param or dropping the URL
+ // sync silently dead-ends every held-back-findings link already posted to GitHub.
+ useMocks({
+ get: {
+ '/api/projects/:team_id/review_hog/reviews/r-9/': () => [200, reviewDetail('r-9', null)],
+ },
+ })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadRecentReviewsSuccess'])
+
+ router.actions.push(urls.codeReview(), { review: 'r-9' })
+ await expectLogic(logic)
+ .toDispatchActions(['openReviewDetailById', 'loadReviewDetailSuccess'])
+ // No list row on a deep link — the drawer must render from the loaded detail alone.
+ .toMatchValues({ reviewDrawerOpen: true, openedReview: null })
+ expect(logic.values.reviewDetail?.id).toBe('r-9')
+
+ // A repeat location event for the same review (e.g. the open's own URL write-back) must not
+ // re-dispatch into the already-open drawer and reload the detail forever.
+ await expectLogic(logic, () =>
+ router.actions.push(urls.codeReview(), { review: 'r-9' })
+ ).toNotHaveDispatchedActions(['openReviewDetailById'])
+
+ // Closing removes the param in place (replace, not push), so back doesn't reopen the drawer.
+ logic.actions.closeReviewDrawer()
+ expect(logic.values.reviewDrawerOpen).toBe(false)
+ expect(router.values.searchParams.review).toBeUndefined()
+
+ // And navigation that drops the param closes an open drawer — the URL and the visible
+ // report must never disagree.
+ router.actions.push(urls.codeReview(), { review: 'r-9' })
+ await expectLogic(logic).toDispatchActions(['openReviewDetailById'])
+ router.actions.push(urls.codeReview(), {})
+ expect(logic.values.reviewDrawerOpen).toBe(false)
+ })
+
+ it('closes a deep-linked drawer when the review fails to load', async () => {
+ // A stale ?review= link (deleted report, wrong project) has no list row to fall back on —
+ // without the failure path the drawer would sit open on skeletons forever.
+ useMocks({
+ get: {
+ '/api/projects/:team_id/review_hog/reviews/r-gone/': () => [404, { detail: 'Not found.' }],
+ },
+ })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadRecentReviewsSuccess'])
+
+ router.actions.push(urls.codeReview(), { review: 'r-gone' })
+ await expectLogic(logic).toDispatchActions([
+ 'openReviewDetailById',
+ 'loadReviewDetailFailure',
+ 'closeReviewDrawer',
+ ])
+ expect(logic.values.reviewDrawerOpen).toBe(false)
+ expect(router.values.searchParams.review).toBeUndefined()
+ })
+
it('stops "Show more" at the API\'s maximum limit', async () => {
logic.mount()
await expectLogic(logic).toDispatchActions([
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.ts
index acb9688808e5..7be156f61d8d 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts
@@ -134,6 +134,7 @@ export interface reviewHogSettingsLogicValues {
initialLoadFailed: boolean
moreReviewsAvailable: boolean
openedReview: ReviewRecentReviewApi | null
+ openedReviewId: string | null
perspectiveScoreboard: PerspectiveScore[] | null
perspectiveStats: ReviewPerspectiveStatsApi | null
perspectiveStatsLoading: boolean
@@ -293,6 +294,9 @@ export interface reviewHogSettingsLogicActions {
openReviewDetail: (review: ReviewRecentReviewApi) => {
review: ReviewRecentReviewApi
}
+ openReviewDetailById: (reviewId: string) => {
+ reviewId: string
+ }
patchPerspectiveLocally: (
skillName: string,
enabled: boolean
@@ -423,6 +427,10 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
viewSkill: (skill: ViewedSkill) => ({ skill }),
closeSkillDrawer: true,
openReviewDetail: (review: ReviewRecentReviewApi) => ({ review }),
+ // Opens the drawer for a review with no list row in hand — the `?review=` deep-link path
+ // (PR status comments bake these links into GitHub). The drawer renders from the loaded
+ // detail alone.
+ openReviewDetailById: (reviewId: string) => ({ reviewId }),
closeReviewDrawer: true,
openPipelineDetail: true,
closePipelineDetail: true,
@@ -495,8 +503,14 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
reviewDetail: [
null as ReviewDetailApi | null,
{
- loadReviewDetail: async (reviewId: string) =>
- await reviewHogReviewsRetrieve(currentProjectId(), reviewId),
+ loadReviewDetail: async (reviewId: string, breakpoint) => {
+ const response = await reviewHogReviewsRetrieve(currentProjectId(), reviewId)
+ // A newer open (row click, ?review= navigation) dispatched a fresh load
+ // mid-flight — drop this stale response so out-of-order responses can't
+ // attach the wrong review's findings to the drawer.
+ breakpoint()
+ return response
+ },
},
],
perspectiveStats: [
@@ -556,20 +570,35 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
},
],
// The clicked list row: the drawer header renders from it instantly while the detail loads.
+ // Null on a deep-linked open (no row in hand) — the drawer then renders from the detail alone.
openedReview: [
null as ReviewRecentReviewApi | null,
{
openReviewDetail: (_, { review }) => review,
+ openReviewDetailById: () => null,
+ },
+ ],
+ // The review the drawer is showing (or loading), by id — set synchronously by both open
+ // paths, so the URL sync can tell "this location event is my own write-back" apart from a
+ // genuinely new deep link before the detail has loaded.
+ openedReviewId: [
+ null as string | null,
+ {
+ openReviewDetail: (_, { review }) => review.id,
+ openReviewDetailById: (_, { reviewId }) => reviewId,
+ closeReviewDrawer: () => null,
},
],
reviewDetail: {
// Clear the previous review's detail so opening another row never flashes stale findings.
openReviewDetail: () => null,
+ openReviewDetailById: () => null,
},
reviewDrawerOpen: [
false,
{
openReviewDetail: () => true,
+ openReviewDetailById: () => true,
closeReviewDrawer: () => false,
},
],
@@ -585,6 +614,7 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
{
setReviewDrawerTab: (_, { tab }) => tab,
openReviewDetail: () => 'published' as ReviewDrawerTab,
+ openReviewDetailById: () => 'published' as ReviewDrawerTab,
},
],
expandedReviewIds: [
@@ -719,8 +749,10 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
// offering it would send a limit the server rejects.
(recentReviewsPage?.has_more ?? false) && reviewsLimit < MAX_REVIEWS_LIMIT,
],
- // Splits the detail's valid findings by the CURRENT threshold — a close-enough proxy for
- // what the run published (the run's own threshold snapshot isn't stored).
+ // Splits the detail's valid findings by the threshold the run actually gated on
+ // (`run_urgency_threshold`, stamped at finalize). Only rows that predate the stamp fall
+ // back to the viewer's current setting — an approximation that can misbucket when the
+ // run's acting user or their settings differ from the viewer's.
reviewFindingsSplit: [
(s) => [s.reviewDetail, s.settings],
(
@@ -730,7 +762,8 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
if (!reviewDetail) {
return null
}
- const thresholdRank = REVIEW_PRIORITY_RANK[settings?.urgency_threshold ?? 'consider']
+ const threshold = reviewDetail.run_urgency_threshold ?? settings?.urgency_threshold ?? 'consider'
+ const thresholdRank = REVIEW_PRIORITY_RANK[threshold]
return {
published: reviewDetail.findings.filter(
(f) => REVIEW_PRIORITY_RANK[f.effective_priority] >= thresholdRank
@@ -879,6 +912,17 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
openReviewDetail: ({ review }) => {
actions.loadReviewDetail(review.id)
},
+ openReviewDetailById: ({ reviewId }) => {
+ actions.loadReviewDetail(reviewId)
+ },
+ loadReviewDetailFailure: () => {
+ // Only the deep-link path has no list row keeping the drawer meaningful — a failed
+ // load there (stale link, deleted report) would strand an open drawer of skeletons.
+ if (values.reviewDrawerOpen && !values.openedReview) {
+ lemonToast.error("That review couldn't be opened. The link may be stale, or the review deleted.")
+ actions.closeReviewDrawer()
+ }
+ },
submitTriggerReview: async () => {
if (values.triggeringReview) {
// A request is already in flight — the disabled button can't stop an Enter keypress
@@ -943,17 +987,34 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
// can be shared via a link; the default scope keeps the URL clean. The auto-default deliberately
// does NOT write the URL: hydrating from a link marks the scope as chosen (below), so mirroring
// the fallback would silently upgrade it into a permanent explicit choice on reload.
- actionToUrl(({ values }) => ({
- setReviewsScope: (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => [
+ // The drawer mirrors to `?review=<report id>` the same way — a PERMANENT PUBLIC CONTRACT (PR
+ // status comments bake these links into GitHub, where they are never re-edited). Always
+ // `replace`, never push, so opening/closing the drawer doesn't stack history entries.
+ actionToUrl(({ values }) => {
+ const withReviewParam = (
+ review: string | undefined
+ ): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => [
router.values.location.pathname,
- {
- ...router.values.searchParams,
- reviews_scope: values.reviewsScope === ReviewHogReviewsListScope.Mine ? undefined : values.reviewsScope,
- },
+ { ...router.values.searchParams, review },
router.values.hashParams,
{ replace: true },
- ],
- })),
+ ]
+ return {
+ setReviewsScope: (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => [
+ router.values.location.pathname,
+ {
+ ...router.values.searchParams,
+ reviews_scope:
+ values.reviewsScope === ReviewHogReviewsListScope.Mine ? undefined : values.reviewsScope,
+ },
+ router.values.hashParams,
+ { replace: true },
+ ],
+ openReviewDetail: ({ review }) => withReviewParam(review.id),
+ openReviewDetailById: ({ reviewId }) => withReviewParam(reviewId),
+ closeReviewDrawer: () => withReviewParam(undefined),
+ }
+ }),
urlToAction(({ actions, values }) => ({
[urls.codeReview()]: (_, searchParams) => {
@@ -964,6 +1025,17 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
) {
actions.setReviewsScope(parsed)
}
+ // ?review=<report id>: open that review's drawer. `openedReviewId` (set synchronously by
+ // both open paths) makes the guard hold before the detail loads, so the open's own URL
+ // write-back — a repeat location event with the same param — can't re-dispatch forever.
+ const reviewParam = searchParams.review
+ if (typeof reviewParam === 'string' && reviewParam && reviewParam !== values.openedReviewId) {
+ actions.openReviewDetailById(reviewParam)
+ } else if (!reviewParam && values.reviewDrawerOpen) {
+ // Navigation that drops the param (back/forward, a pasted URL without it) closes
+ // the drawer — otherwise the URL and the visible report disagree.
+ actions.closeReviewDrawer()
+ }
},
})),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f55ec07d84cb..381a1f8604fa 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -59202,16 +59202,6 @@ 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
@@ -59226,6 +59216,16 @@ 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
@@ -59392,6 +59392,12 @@ export namespace Schemas {
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.
+ *
+ * * `must_fix` - must_fix
+ * * `should_fix` - should_fix
+ * * `consider` - consider */
+ run_urgency_threshold: ReviewIssuePriorityEnum | null;
/** The latest turn's validated findings, most urgent first. */
findings: ReviewFinding[];
/** The latest turn's findings the validator dismissed, with its reasoning. */
@@ -78502,7 +78508,7 @@ export namespace Schemas {
*/
limit?: number;
/**
- * Whose reviews to list: `mine` for reviews of the requesting user's pull requests (the default), `everyone` for every review on this project.
+ * Whose reviews to list: `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.
*
* * `mine` - mine
* * `everyone` - everyone
@@ -78521,7 +78527,7 @@ export namespace Schemas {
export type ReviewHogReviewsPerspectiveStatsRetrieveParams = {
/**
- * Whose reviews to aggregate: `mine` for reviews of the requesting user's pull requests (the default), `everyone` for every review on this project.
+ * 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.
*
* * `mine` - mine
* * `everyone` - everyone