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): react while reviewing, drop the Standard status comment (#115294)

Julian Bez8b3ef11b9fc0
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 2bbf9e36b973..de0d7bc2bbaa 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -458,7 +458,14 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /
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**
+ suppress the publish or clobber a stranger's comment.
+ **Reactions:** once a publishing turn passes every gate, the workflow puts a 👀 on the PR (`add_review_reaction_activity`) and removes it by the returned reaction id when the turn ends, on success, failure, or cancellation (the `finally` around the review stages).
+ Both calls are fail-open and gated by the `reviewhog-pr-reactions-2026-10` patch.
+ Stamphog lists `posthog[bot]` in its trusted reviewer bots, so it waits while that 👀 is fresh.
+ **Standard turns post no status comment** (the same patch): the 👀 shows the turn runs, and the outcome is the review, a 👍 on the PR when nothing is publishable, or one failure comment per head (`post_failure_comment`, hidden `reviewhog:failed` marker) posted by `fail_status_comment_activity`.
+ A later publish with findings, in either mode, first removes the app's own 👍 (`remove_own_pr_reactions`, matched with `is_app_bot_author`).
+ Status comments that earlier turns left on the PR stay as they are, and a Standard turn never refreshes them.
+ On the publish path of a **Deep** turn a live **status comment**
(`reviewer/status_comment.py`) is posted at kickoff as one table with a row per step of the turn's review design,
edited as the steps fill in, and rewritten with the
outcome: the full found counts, what was published, and — when the urgency threshold held findings back —
@@ -476,7 +483,8 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /
The outcome sweep (`find_finding_comment`) matches a finding to its comment by the whole first line, for any P level and for the older `### {title}` heading.
A reply or reaction counts as engagement unless ReviewHog's own app left it (`engagement_method`), so the resolution stage's 👀 queue marker never marks a finding `reacted`.
The validator's argumentation stays out of GitHub; the reviews API returns it as `validator_note`.
- When every publishable finding posts inline, the review body is only the hidden publish marker, because the tally repeats the comments.
+ When every publishable finding posts inline, a Deep review body is only the hidden publish marker, because the tally repeats the comments.
+ A Standard review body then carries one summary line instead (`render_review_summary`, "PostHog Review · Standard · reviewed `abc1234`: 1 Must fix."), because Standard has no status comment.
The body-only fallback always posts the full body.
The workflow captures one **`reviewhog_review_started`** product-analytics event per turn that passed every
gate (`track_review_started_activity`) and, after the publish stage, one **`reviewhog_review_completed`** per
diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.py
index fe3fa95ae0a6..57e5fda89d81 100644
--- a/products/review_hog/backend/reviewer/status_comment.py
+++ b/products/review_hog/backend/reviewer/status_comment.py
@@ -195,9 +195,18 @@ def report_deep_link(team_id: int, report_id: str) -> str:
return f"{settings.SITE_URL}/project/{team_id}/code-review?review={report_id}"
-def _header(review_mode: str, verb: str, head_sha: str | None) -> str:
+def _title(review_mode: str, verb: str, head_sha: str | None) -> str:
target = f"`{head_sha[:7]}`" if head_sha else "this pull request"
- return f"### PostHog Review · {_MODE_NAMES.get(review_mode, 'Deep')} · {verb} {target}"
+ return f"PostHog Review · {_MODE_NAMES.get(review_mode, 'Deep')} · {verb} {target}"
+
+
+def _header(review_mode: str, verb: str, head_sha: str | None) -> str:
+ return f"### {_title(review_mode, verb, head_sha)}"
+
+
+def failure_marker(report_id: str, head_sha: str) -> str:
+ """The hidden marker of a Standard turn's failure comment, so a head gets at most one."""
+ return f"<!-- reviewhog:failed:{report_id}:{head_sha} -->"
def _table_row(step: str, status: str, result: str) -> str:
@@ -303,6 +312,11 @@ def _priority_counts(counts: dict[IssuePriority, int], priorities: Collection[Is
)
+def render_review_summary(review_mode: str, head_sha: str | None, counts: dict[IssuePriority, int]) -> str:
+ """The one-line summary a Standard review body opens with, because Standard posts no status comment."""
+ return f"**{_title(review_mode, 'reviewed', head_sha)}**: {_priority_counts(counts, PRIORITIES_BY_URGENCY)}."
+
+
def render_final_body(
report_id: str,
*,
@@ -634,8 +648,11 @@ def maybe_refresh_status_comment(
Called after pipeline activities persist progress artefacts. The debounce is an atomic claim on
`status_comment_edited_at`, so the concurrent fan-out's calls collapse to one edit per interval;
- a run without a status comment (eval / CLI / branch target) bails on the same claim.
+ a run without a status comment (eval / CLI / branch target) bails on the same claim. A Standard
+ turn never edits it, because the report can still carry the comment of an earlier turn.
"""
+ if review_mode == REVIEW_MODE_FLASH:
+ return
try:
now = timezone.now()
claimed = (
@@ -740,6 +757,34 @@ def fail_status_comment(team_id: int, report_id: str, *, run_index: int, review_
logger.exception("Could not mark the ReviewHog status comment as failed")
+def post_failure_comment(team_id: int, report_id: str, *, review_mode: str = REVIEW_MODE_FLASH) -> None:
+ """Tell the PR that a Standard turn failed, once per head, because Standard posts no status comment."""
+ try:
+ report = ReviewReport.objects.for_team(team_id).filter(id=report_id).first()
+ if report is None or report.pr_number is None or not report.head_sha:
+ return
+ auth = _auth(team_id, report.repository)
+ if auth is None:
+ return
+ token, installation_id = auth
+ owner, repo = _split_repository(report.repository)
+ marker = failure_marker(report_id, report.head_sha)
+ if _find_marker_comment(owner, repo, report.pr_number, marker, token=token, installation_id=installation_id):
+ return
+ body = "\n".join(
+ [
+ _header(review_mode, "couldn't review", report.head_sha),
+ "",
+ "Something went wrong and the review didn't finish. Push a new commit to run it again.",
+ "",
+ marker,
+ ]
+ )
+ _post_comment(owner, repo, report.pr_number, body, token=token, installation_id=installation_id)
+ except Exception:
+ logger.exception("Could not post the ReviewHog failure comment")
+
+
def update_resolution_status_comment(
team_id: int, report_id: str, row: str, *, integration_row_id: int | None = None
) -> None:
diff --git a/products/review_hog/backend/reviewer/tests/test_github_client.py b/products/review_hog/backend/reviewer/tests/test_github_client.py
index 124bcd856795..afe9957b51cb 100644
--- a/products/review_hog/backend/reviewer/tests/test_github_client.py
+++ b/products/review_hog/backend/reviewer/tests/test_github_client.py
@@ -1,8 +1,15 @@
+import pytest
from unittest.mock import MagicMock, patch
from posthog.egress.limiter.policies import Priority
-from products.review_hog.backend.reviewer.tools.github_client import github_api_request
+from products.review_hog.backend.reviewer.tools.github_client import (
+ GitHubAPIError,
+ add_pr_reaction,
+ github_api_request,
+ remove_own_pr_reactions,
+ remove_pr_reaction,
+)
_MODULE = "products.review_hog.backend.reviewer.tools.github_client"
@@ -16,3 +23,50 @@ def test_requests_ride_the_normal_priority_lane() -> None:
github_api_request("GET", "/repos/o/r", token="t", endpoint="/repos/{owner}/{repo}")
assert mock_transport.call_args.kwargs["priority"] is Priority.NORMAL
+
+
+def test_add_pr_reaction_fails_open() -> None:
+ # The reaction is a signal on the PR. A GitHub error here must never fail the review activity.
+ with patch(f"{_MODULE}.github_api_request", side_effect=GitHubAPIError("no", status=403)):
+ assert add_pr_reaction("o/r", 7, "eyes", token="t") is None
+
+
+def test_remove_own_pr_reactions_deletes_only_the_apps_reactions_and_fails_open() -> None:
+ reactions = [
+ {"id": 1, "content": "+1", "user": {"login": "octocat", "type": "User"}},
+ {"id": 2, "content": "+1", "user": {"login": "greptile-apps[bot]", "type": "Bot"}},
+ {"id": 3, "content": "+1", "user": {"login": "posthog[bot]", "type": "Bot"}},
+ {"id": 4, "content": "+1", "user": {"login": "posthog[bot]", "type": "Bot"}},
+ ]
+ with (
+ patch(f"{_MODULE}.github_api_get_paginated", return_value=iter(reactions)) as mock_paginated,
+ patch(f"{_MODULE}.posthog_app_login", return_value="posthog[bot]"),
+ patch(f"{_MODULE}.github_api_request", side_effect=[GitHubAPIError("boom", status=500), None]) as mock_request,
+ ):
+ remove_own_pr_reactions("o/r", 7, "+1", token="t")
+
+ assert mock_paginated.call_args.kwargs["params"] == {"content": "+1"}
+ # The first delete fails and the second one still runs.
+ assert [c.args for c in mock_request.call_args_list] == [
+ ("DELETE", "/repos/o/r/issues/7/reactions/3"),
+ ("DELETE", "/repos/o/r/issues/7/reactions/4"),
+ ]
+
+
+ "status, raises",
+ [
+ # A 5xx must reach the activity so Temporal retries it, or the 👀 stays on the PR.
+ (502, True),
+ (404, False),
+ (403, False),
+ ],
+)
+def test_remove_pr_reaction_raises_only_transient_errors(status: int, raises: bool) -> None:
+ error = GitHubAPIError("boom", status=status)
+ with patch(f"{_MODULE}.github_api_request", side_effect=error):
+ if raises:
+ with pytest.raises(GitHubAPIError):
+ remove_pr_reaction("o/r", 7, 3, token="t")
+ else:
+ remove_pr_reaction("o/r", 7, 3, token="t")
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 9543e1022256..8e9680b5748c 100644
--- a/products/review_hog/backend/reviewer/tests/test_publish_review.py
+++ b/products/review_hog/backend/reviewer/tests/test_publish_review.py
@@ -1,3 +1,4 @@
+from collections.abc import Iterator
from typing import Any
import pytest
@@ -27,6 +28,8 @@ _PAGINATED = "products.review_hog.backend.reviewer.tools.publish_review.github_a
_REPORT = "products.review_hog.backend.reviewer.tools.publish_review.ReviewReport"
_LOAD_FINDINGS = "products.review_hog.backend.reviewer.tools.publish_review.load_valid_findings"
_POST = "products.review_hog.backend.reviewer.tools.publish_review._post_github_review"
+_ADD_REACTION = "products.review_hog.backend.reviewer.tools.publish_review.add_pr_reaction"
+_REMOVE_REACTIONS = "products.review_hog.backend.reviewer.tools.publish_review.remove_own_pr_reactions"
# The should_fix threshold: publishes should_fix and must_fix, drops consider. These tests use it to
# exercise the publish gate, not the default (consider), which publishes everything.
@@ -303,6 +306,13 @@ def _verdict(adjusted_priority: IssuePriority | None = None) -> ValidationVerdic
class TestPublishReviewGate:
+ @pytest.fixture(autouse=True)
+ def _reactions(self) -> Iterator[None]:
+ with patch(_ADD_REACTION) as add_reaction, patch(_REMOVE_REACTIONS) as remove_reactions:
+ self.add_reaction = add_reaction
+ self.remove_reactions = remove_reactions
+ yield
+
def _wire_report(self, mock_report_cls: MagicMock) -> None:
mock_report = MagicMock()
mock_report.report_markdown = "# PostHog Review"
@@ -312,9 +322,18 @@ class TestPublishReviewGate:
[
# A valid finding on an off-diff line resolves zero inline comments, but the review (its body
# carries it in the "Other findings" section) must still post, not be silently dropped.
- ("all_off_diff", [240], 0, False),
- ("mixed", [1, 240], 1, False),
- ("all_inline", [1], 1, True),
+ ("all_off_diff", [240], 0, "full", None),
+ ("mixed", [1, 240], 1, "full", None),
+ ("all_inline", [1], 1, "full", ""),
+ # Standard has no status comment, so its review body always says which turn it is.
+ (
+ "standard_all_inline",
+ [1],
+ 1,
+ "flash",
+ "**PostHog Review · Standard · reviewed `sha`**: 1 Should fix.\n\n",
+ ),
+ ("standard_mixed", [1, 240], 1, "flash", None),
]
)
@patch(_POST)
@@ -325,7 +344,8 @@ class TestPublishReviewGate:
_name: str,
finding_lines: list[int],
expected_comments: int,
- expect_marker_only: bool,
+ review_mode: str,
+ inline_prefix: str | None,
mock_report_cls: MagicMock,
mock_load: MagicMock,
mock_post: MagicMock,
@@ -356,6 +376,7 @@ class TestPublishReviewGate:
token="t",
head_sha="sha",
published_priorities=_SHOULD_FIX_PUBLISHED,
+ review_mode=review_mode,
)
assert outcome.posted is True
@@ -363,16 +384,28 @@ class TestPublishReviewGate:
assert len(mock_post.call_args.args[4]) == expected_comments
marker = mock_post.call_args.kwargs["marker"]
assert marker in mock_post.call_args.args[3]
- assert mock_post.call_args.kwargs["inline_body"] == (marker if expect_marker_only else None)
+ expected_inline_body = None if inline_prefix is None else f"{inline_prefix}{marker}"
+ assert mock_post.call_args.kwargs["inline_body"] == expected_inline_body
+ # A 👍 from an earlier clean turn must not sit next to these findings.
+ assert self.remove_reactions.call_args.args == ("o/r", 1, "+1")
+ self.add_reaction.assert_not_called()
+ @parameterized.expand([("deep", "full", []), ("standard_reacts", "flash", [("o/r", 1, "+1")])])
@patch(_POST)
@patch(_LOAD_FINDINGS)
@patch(_REPORT)
def test_skips_when_only_consider_findings(
- self, mock_report_cls: MagicMock, mock_load: MagicMock, mock_post: MagicMock
+ self,
+ _name: str,
+ review_mode: str,
+ expected_reactions: list[tuple[str, int, str]],
+ mock_report_cls: MagicMock,
+ mock_load: MagicMock,
+ mock_post: MagicMock,
) -> None:
# Below the should_fix threshold: a run whose only valid finding is `consider` has
# nothing publishable, so it posts nothing (guards the off-diff fix against over-surfacing).
+ # A clean Standard turn has no status comment, so its 👍 is the only sign that it ran.
self._wire_report(mock_report_cls)
mock_load.return_value = [(_finding(priority=IssuePriority.CONSIDER), _verdict())]
@@ -387,10 +420,12 @@ class TestPublishReviewGate:
token="t",
head_sha="sha",
published_priorities=_SHOULD_FIX_PUBLISHED,
+ review_mode=review_mode,
)
assert outcome.posted is False
mock_post.assert_not_called()
+ assert [c.args for c in self.add_reaction.call_args_list] == expected_reactions
@parameterized.expand(
[
diff --git a/products/review_hog/backend/reviewer/tools/github_client.py b/products/review_hog/backend/reviewer/tools/github_client.py
index 59c1c03d1639..8033ee50e984 100644
--- a/products/review_hog/backend/reviewer/tools/github_client.py
+++ b/products/review_hog/backend/reviewer/tools/github_client.py
@@ -156,3 +156,80 @@ def github_api_get_paginated(
if len(items) < _PER_PAGE:
return
page += 1
+
+
+_REACTIONS_ENDPOINT = "/repos/{owner}/{repo}/issues/{issue_number}/reactions"
+
+
+def add_pr_reaction(
+ repository: str, pr_number: int, content: str, *, token: str, installation_id: str | None = None
+) -> int | None:
+ """React on the PR itself and return the reaction id, or None when GitHub refuses or fails.
+
+ Fail-open: a reaction only tells people on the PR what the review is doing, so a failure is
+ logged and never fails or retries the calling activity. GitHub returns the existing reaction
+ when the app already reacted with `content`, so a retried activity gets the same id back.
+ """
+ try:
+ response = github_api_request(
+ "POST",
+ f"/repos/{repository}/issues/{pr_number}/reactions",
+ token=token,
+ installation_id=installation_id,
+ endpoint=_REACTIONS_ENDPOINT,
+ json={"content": content},
+ )
+ reaction_id = response.json().get("id")
+ except Exception:
+ logger.warning("Could not add the %s reaction to %s#%s", content, repository, pr_number, exc_info=True)
+ return None
+ return reaction_id if isinstance(reaction_id, int) else None
+
+
+def remove_pr_reaction(
+ repository: str, pr_number: int, reaction_id: int, *, token: str, installation_id: str | None = None
+) -> None:
+ """Delete one reaction from the PR. A 404 means it is already gone.
+
+ A transient error raises, so the calling activity retries it and no stale reaction stays on the
+ PR. Any other error is logged and dropped, because a retry can not get past it.
+ """
+ try:
+ github_api_request(
+ "DELETE",
+ f"/repos/{repository}/issues/{pr_number}/reactions/{reaction_id}",
+ token=token,
+ installation_id=installation_id,
+ endpoint=f"{_REACTIONS_ENDPOINT}/{{reaction_id}}",
+ )
+ except Exception as e:
+ if is_transient_github_error(e):
+ raise
+ if not (isinstance(e, GitHubAPIError) and e.status == 404):
+ logger.warning("Could not remove reaction %s from %s#%s", reaction_id, repository, pr_number, exc_info=True)
+
+
+def remove_own_pr_reactions(
+ repository: str, pr_number: int, content: str, *, token: str, installation_id: str | None = None
+) -> None:
+ """Delete every `content` reaction the app left on the PR, and no one else's. Fail-open."""
+ try:
+ own_ids = [
+ reaction["id"]
+ for reaction in github_api_get_paginated(
+ f"/repos/{repository}/issues/{pr_number}/reactions",
+ token=token,
+ installation_id=installation_id,
+ endpoint=_REACTIONS_ENDPOINT,
+ params={"content": content},
+ )
+ if is_app_bot_author(reaction.get("user"))
+ ]
+ except Exception:
+ logger.warning("Could not read the %s reactions on %s#%s", content, repository, pr_number, exc_info=True)
+ return
+ for reaction_id in own_ids:
+ try:
+ remove_pr_reaction(repository, pr_number, reaction_id, token=token, installation_id=installation_id)
+ except Exception:
+ logger.warning("Could not remove reaction %s from %s#%s", reaction_id, repository, pr_number, exc_info=True)
diff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.py
index c5d7bfcfb170..444c2c94d16f 100644
--- a/products/review_hog/backend/reviewer/tools/publish_review.py
+++ b/products/review_hog/backend/reviewer/tools/publish_review.py
@@ -1,5 +1,6 @@
import re
import logging
+from collections import Counter
from dataclasses import dataclass
from typing import Any, Required, TypedDict
@@ -24,12 +25,15 @@ from products.review_hog.backend.reviewer.models.github_meta import PRFile
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.persistence import load_pr_snapshot, load_valid_findings
from products.review_hog.backend.reviewer.review_state import published_heads_by_mode, review_already_published
+from products.review_hog.backend.reviewer.status_comment import render_review_summary
from products.review_hog.backend.reviewer.tools.github_client import (
GitHubAPIError,
+ add_pr_reaction,
github_api_get_paginated,
github_api_request,
is_app_bot_author,
is_transient_github_error,
+ remove_own_pr_reactions,
)
from products.review_hog.backend.reviewer.tools.github_threads import REVIEW_HOG_FINDING_MARKER
from products.review_hog.backend.reviewer.tools.redaction import redact_secrets
@@ -220,18 +224,29 @@ def publish_review(
# publishable finding on an off-diff line has no inline anchor but is surfaced in the body's
# "Other findings" section, so the body must still post rather than dropping the whole review. The
# validator's priority override wins over the reviewer's, so the gate reads the effective priority.
- publishable = [
- finding
- for finding, verdict in valid_findings
- if effective_priority(finding.priority, verdict.adjusted_priority) in published_priorities
+ priorities = [
+ effective_priority(finding.priority, verdict.adjusted_priority) for finding, verdict in valid_findings
]
+ publishable = [priority for priority in priorities if priority in published_priorities]
+ repository = f"{owner}/{repo}"
if not publishable:
logger.info("No publishable issues found, skipping review")
+ # A clean Standard turn posts nothing, so the 👍 is the only sign that the review ran.
+ if review_mode == REVIEW_MODE_FLASH:
+ add_pr_reaction(repository, pr_number, "+1", token=token, installation_id=installation_id)
return PublishOutcome(posted=False)
+ # An earlier clean turn's 👍 would sit next to this turn's findings and contradict them.
+ remove_own_pr_reactions(repository, pr_number, "+1", token=token, installation_id=installation_id)
# When every publishable finding has its own inline comment, the body's tally repeats what the
- # comments already show, so the review posts only the hidden marker with them.
- inline_body = marker if len(comments) == len(publishable) else None
+ # comments already show. A Deep review then posts only the hidden marker. A Standard review keeps
+ # a one-line summary, because it has no status comment to connect the comments to the turn.
+ inline_body = None
+ if len(comments) == len(publishable):
+ inline_body = marker
+ if review_mode == REVIEW_MODE_FLASH:
+ summary = render_review_summary(review_mode, head_sha, Counter(publishable))
+ inline_body = f"{summary}\n\n{marker}"
logger.info(f"Review: {len(body)} chars body, {len(comments)} inline comments")
review_url = _post_github_review(
diff --git a/products/review_hog/backend/temporal/__init__.py b/products/review_hog/backend/temporal/__init__.py
index c3ebe5faf7a0..fa2c4f689e59 100644
--- a/products/review_hog/backend/temporal/__init__.py
+++ b/products/review_hog/backend/temporal/__init__.py
@@ -1,4 +1,5 @@
from products.review_hog.backend.temporal.activities import (
+ add_review_reaction_activity,
append_code_review_artefact_activity,
build_body_activity,
coordinator_review_activity,
@@ -15,6 +16,7 @@ from products.review_hog.backend.temporal.activities import (
post_status_comment_activity,
publish_review_activity,
record_turn_marker_activity,
+ remove_review_reaction_activity,
remove_trigger_label_activity,
resolve_acting_user_activity,
review_chunk_activity,
@@ -80,6 +82,8 @@ ACTIVITIES = [
post_status_comment_activity,
finalize_status_comment_activity,
fail_status_comment_activity,
+ add_review_reaction_activity,
+ remove_review_reaction_activity,
track_review_completed_activity,
track_review_failed_activity,
track_review_started_activity,
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index e0b3c1c64c1f..4bc314f06841 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -134,6 +134,7 @@ from products.review_hog.backend.reviewer.status_comment import (
fail_status_comment,
finalize_status_comment,
maybe_refresh_status_comment,
+ post_failure_comment,
)
from products.review_hog.backend.reviewer.telemetry import review_event_uuid, review_routing_properties
from products.review_hog.backend.reviewer.tools.coordinator_review import (
@@ -141,7 +142,12 @@ from products.review_hog.backend.reviewer.tools.coordinator_review import (
CoordinatorUnit,
coordinator_prompt,
)
-from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
+from products.review_hog.backend.reviewer.tools.github_client import (
+ GitHubAPIError,
+ add_pr_reaction,
+ github_api_request,
+ remove_pr_reaction,
+)
from products.review_hog.backend.reviewer.tools.github_meta import (
PRFetcher,
PRFilter,
@@ -642,6 +648,21 @@ class StatusCommentInput:
review_design: str = REVIEW_DESIGN_PIPELINE
# The failed turn, for the failure edit. None in payloads from before the field existed.
run_index: int | None = None
+ # False when Temporal retries the turn after this failure. A Standard turn posts its failure
+ # comment only on the last attempt, so a retry that succeeds leaves no stale notice on the PR.
+ last_attempt: bool = True
+ # A Standard run that started before the reactions patch has a status comment to mark as failed.
+ uses_status_comment: bool = True
+
+
+@frozen
+class ReviewReactionInput:
+ """The 👀 a publishing turn keeps on the PR while it runs. `reaction_id` is set only for the removal."""
+
+ team_id: int
+ repository: str
+ pr_number: int
+ reaction_id: int | None = None
# --- Setup activities ------------------------------------------------------------------------------
@@ -2408,7 +2429,14 @@ async def finalize_status_comment_activity(input: FinalizeStatusCommentInput) ->
raise _wait_for_github_reset(error) from error
-def _fail_run(team_id: int, report_id: str, review_mode: str = REVIEW_MODE_FULL, run_index: int | None = None) -> None:
+def _fail_run(
+ team_id: int,
+ report_id: str,
+ review_mode: str = REVIEW_MODE_FULL,
+ run_index: int | None = None,
+ last_attempt: bool = True,
+ uses_status_comment: bool = True,
+) -> None:
# The idle write comes first so a GitHub failure below can't skip it: on publishing runs
# finalize defers going idle to the publish stage, so a run dying between finalize and publish
# would otherwise sit ACTIVE (reading as in-progress in the UI) until the staleness cutoff.
@@ -2429,23 +2457,78 @@ def _fail_run(team_id: int, report_id: str, review_mode: str = REVIEW_MODE_FULL,
review_mode=review_mode,
head_sha=report.head_sha,
)
- fail_status_comment(team_id, report_id, run_index=run_index, review_mode=review_mode)
+ # A Standard turn has no status comment to mark as failed, so it says so in a comment of its own.
+ if review_mode == REVIEW_MODE_FLASH and not uses_status_comment:
+ if last_attempt:
+ post_failure_comment(team_id, report_id, review_mode=review_mode)
+ else:
+ fail_status_comment(team_id, report_id, run_index=run_index, review_mode=review_mode)
@activity.defn
@scoped_temporal()
@close_db_connections
async def fail_status_comment_activity(input: StatusCommentInput) -> None:
- """Return the dead run's report to rest and rewrite the status comment as failed.
+ """Return the dead run's report to rest and tell the PR: the status comment of a Deep turn shows
+ the failure, and a Standard turn posts one failure comment per head.
The idle write lives in this activity rather than as its own workflow command so in-flight
histories replay unchanged (new unconditional commands break replay determinism).
"""
await database_sync_to_async(_fail_run, thread_sensitive=False)(
- input.team_id, input.report_id, input.review_mode, input.run_index
+ input.team_id,
+ input.report_id,
+ input.review_mode,
+ input.run_index,
+ input.last_attempt,
+ input.uses_status_comment,
+ )
+
+
+# --- The PR's "review in progress" reaction ----------------------------------------------------------
+
+
+def _add_eyes_reaction(input: ReviewReactionInput) -> int | None:
+ try:
+ token, installation_id = _installation_auth(input.team_id, input.repository)
+ except Exception:
+ logger.warning("No GitHub auth for %s; skipping the review reaction", input.repository, exc_info=True)
+ return None
+ return add_pr_reaction(input.repository, input.pr_number, "eyes", token=token, installation_id=installation_id)
+
+
+def _remove_eyes_reaction(input: ReviewReactionInput) -> None:
+ if input.reaction_id is None:
+ return
+ try:
+ token, installation_id = _installation_auth(input.team_id, input.repository)
+ except Exception:
+ logger.warning("No GitHub auth for %s; leaving the review reaction", input.repository, exc_info=True)
+ return
+ remove_pr_reaction(
+ input.repository, input.pr_number, input.reaction_id, token=token, installation_id=installation_id
)
+@scoped_temporal()
+@close_db_connections
+async def add_review_reaction_activity(input: ReviewReactionInput) -> int | None:
+ """Put a 👀 on the PR while the turn runs, the way other review bots do. Returns the reaction id.
+
+ Stamphog waits while a trusted review bot has a fresh 👀 on the PR. Fail-open: never raises.
+ """
+ return await database_sync_to_async(_add_eyes_reaction, thread_sensitive=False)(input)
+
+
+@scoped_temporal()
+@close_db_connections
+async def remove_review_reaction_activity(input: ReviewReactionInput) -> None:
+ """Remove the turn's 👀 by the id the add returned. Raises only on a transient GitHub error, so Temporal retries it."""
+ await database_sync_to_async(_remove_eyes_reaction, thread_sensitive=False)(input)
+
+
# --- The signals report's code_review receipt --------------------------------------------------------
# `IssuePriority` values map 1:1 onto the CodeReviewCounts fields (the enum mirrors the threshold choices).
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index fb9ac2b5636e..35c6c78382b8 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -68,6 +68,7 @@ from products.review_hog.backend.temporal.activities import (
ResolveActingUserInput,
ReviewChunkInput,
ReviewMeta,
+ ReviewReactionInput,
SandboxStageInput,
SelectPerspectivesInput,
StatusCommentInput,
@@ -78,6 +79,7 @@ from products.review_hog.backend.temporal.activities import (
ValidateChunkInput,
ValidateChunkResult,
ValidateIntegrationInput,
+ add_review_reaction_activity,
append_code_review_artefact_activity,
build_body_activity,
coordinator_review_activity,
@@ -94,6 +96,7 @@ from products.review_hog.backend.temporal.activities import (
post_status_comment_activity,
publish_review_activity,
record_turn_marker_activity,
+ remove_review_reaction_activity,
remove_trigger_label_activity,
resolve_acting_user_activity,
review_chunk_activity,
@@ -174,6 +177,12 @@ def _non_retryable_cause(exc: BaseException | None) -> ApplicationError | None:
return None
+def _out_of_attempts() -> bool:
+ info = workflow.info()
+ retry = info.retry_policy
+ return retry is None or (retry.maximum_attempts > 0 and info.attempt >= retry.maximum_attempts)
+
+
@dataclass
class ReviewPerspectivesInputs(SandboxStageInput):
chunk_ids: list[int]
@@ -431,14 +440,7 @@ class ReviewPRWorkflow:
non_retryable = True
raise ApplicationError(str(e), non_retryable=True, type=cause.type) from e
finally:
- info = workflow.info()
- retry = info.retry_policy
- terminal = (
- completed
- or non_retryable
- or retry is None
- or (retry.maximum_attempts > 0 and info.attempt >= retry.maximum_attempts)
- )
+ terminal = completed or non_retryable or _out_of_attempts()
if (
workflow.patched("remove-reviewhog-trigger-label-2026-08")
and terminal
@@ -648,11 +650,14 @@ class ReviewPRWorkflow:
# One gate, three consumers: the status comment, finalize's deferred idle write, and the
# stage-7 publish dispatch all key off "this run publishes to a PR".
publishes_to_pr = inputs.publish and meta.pr_number is not None
+ # The patch keeps a history from before the reactions on its old command sequence.
+ reacts = workflow.patched("reviewhog-pr-reactions-2026-10")
# The PR's live status comment: posted once every gate has passed, refreshed by the pipeline
# activities as they persist progress, and rewritten with the outcome below. Publish-path
# only — eval / CLI / branch-target runs keep zero GitHub footprint. Best-effort throughout:
- # a status comment must never cost a review.
- status_comment = publishes_to_pr
+ # a status comment must never cost a review. A Standard turn has none: its 👀 shows that it
+ # runs, and its review, 👍, or failure comment shows the outcome.
+ status_comment = publishes_to_pr and not (reacts and inputs.review_mode == REVIEW_MODE_FLASH)
if status_comment:
try:
await workflow.execute_activity(
@@ -669,6 +674,9 @@ class ReviewPRWorkflow:
except ActivityError:
workflow.logger.warning("Could not post the status comment; continuing without it")
+ eyes_reaction_id: int | None = None
+ if reacts and publishes_to_pr and meta.pr_number is not None:
+ eyes_reaction_id = await self._add_eyes_reaction(inputs.team_id, repository, meta.pr_number)
publish_result: PublishResult | None = None
marker: ReviewHogMarker | None = None
flash_sessions: FlashSessionStats | None = None
@@ -809,11 +817,12 @@ class ReviewPRWorkflow:
workflow.logger.info("No PR to publish to (branch target); the review is stored only")
else:
workflow.logger.info("Publishing disabled for this run (publish=False)")
- except Exception:
+ except Exception as e:
# A dead run must not read as forever in progress on the PR or in the Code review UI
# (the activity also returns the report to rest, covering a publish that died with the
# idle write still deferred); best-effort so the edit can never mask the original error.
- if status_comment:
+ # A Standard turn without a status comment still needs the idle write and its failure comment.
+ if publishes_to_pr:
try:
await workflow.execute_activity(
fail_status_comment_activity,
@@ -823,6 +832,8 @@ class ReviewPRWorkflow:
review_mode=inputs.review_mode,
review_design=review_design,
run_index=meta.run_index,
+ last_attempt=_non_retryable_cause(e) is not None or _out_of_attempts(),
+ uses_status_comment=status_comment,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -856,6 +867,10 @@ class ReviewPRWorkflow:
except Exception:
workflow.logger.exception("Could not capture the review-failed analytics event")
raise
+ finally:
+ # Also on cancellation, which is not an Exception, so a stopped turn leaves no 👀 behind.
+ if eyes_reaction_id is not None and meta.pr_number is not None:
+ await self._remove_eyes_reaction(inputs.team_id, repository, meta.pr_number, eyes_reaction_id)
posted = publish_result is not None and publish_result.posted
# One analytics event per finalized turn (the review-level count dashboards aggregate);
@@ -1127,6 +1142,33 @@ class ReviewPRWorkflow:
retry_policy=_RETRY,
)
+ @staticmethod
+ async def _add_eyes_reaction(team_id: int, repository: str, pr_number: int) -> int | None:
+ try:
+ return await workflow.execute_activity(
+ add_review_reaction_activity,
+ ReviewReactionInput(team_id=team_id, repository=repository, pr_number=pr_number),
+ start_to_close_timeout=_QUICK_TIMEOUT,
+ retry_policy=_RETRY,
+ )
+ except ActivityError:
+ workflow.logger.warning("Could not add the review reaction; continuing without it")
+ return None
+
+ @staticmethod
+ async def _remove_eyes_reaction(team_id: int, repository: str, pr_number: int, reaction_id: int) -> None:
+ try:
+ await workflow.execute_activity(
+ remove_review_reaction_activity,
+ ReviewReactionInput(
+ team_id=team_id, repository=repository, pr_number=pr_number, reaction_id=reaction_id
+ ),
+ start_to_close_timeout=_QUICK_TIMEOUT,
+ retry_policy=_RETRY,
+ )
+ except ActivityError:
+ workflow.logger.warning("Could not remove the review reaction")
+
@staticmethod
async def _append_code_review_receipt(
inputs: ReviewPRWorkflowInputs,
diff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.py
index 1977212e777b..9c5ca5616458 100644
--- a/products/review_hog/backend/tests/test_status_comment.py
+++ b/products/review_hog/backend/tests/test_status_comment.py
@@ -30,6 +30,7 @@ from products.review_hog.backend.reviewer.status_comment import (
_splice_resolution_row,
ensure_status_comment,
fail_status_comment,
+ failure_marker,
finalize_status_comment,
maybe_refresh_status_comment,
render_final_body,
@@ -399,6 +400,16 @@ class TestMaybeRefreshStatusComment(BaseTest):
report.refresh_from_db()
assert report.status_comment_edited_at is not None and report.status_comment_edited_at > before
+ def test_a_standard_turn_leaves_an_earlier_status_comment_alone(
+ self, mock_request: MagicMock, mock_integration: MagicMock
+ ) -> None:
+ _wire_auth(mock_integration)
+ report = self._report(comment_id=555, edited_ago=timedelta(minutes=5))
+
+ maybe_refresh_status_comment(self.team.id, str(report.id), review_mode=REVIEW_MODE_FLASH)
+
+ mock_request.assert_not_called()
+
@patch(_INTEGRATION)
@patch(_REQUEST)
@@ -727,3 +738,84 @@ class TestFailRun(BaseTest):
assert [(m.outcome, m.reason, m.run_index, m.review_mode, m.head_sha) for m in markers] == [
("failed", "review_failed", expected_run_index, "flash", report.head_sha)
]
+
+
+class TestFailedTurnNotice(BaseTest):
+ @parameterized.expand(
+ [
+ (
+ "standard_posts_a_failure_comment",
+ REVIEW_MODE_FLASH,
+ False,
+ False,
+ True,
+ ["/repos/o/r/issues/123/comments"],
+ [],
+ ),
+ # An activity retry finds the comment it already posted for this head.
+ ("standard_posts_once_per_head", REVIEW_MODE_FLASH, False, True, True, [], []),
+ # Temporal retries the turn, and a retry that succeeds must not sit next to a failure notice.
+ ("standard_waits_for_the_last_attempt", REVIEW_MODE_FLASH, False, False, False, [], []),
+ # A Standard turn never edits the status comment an earlier Deep turn left on the report.
+ (
+ "deep_edits_the_status_comment",
+ REVIEW_MODE_FULL,
+ True,
+ False,
+ True,
+ [],
+ ["/repos/o/r/issues/comments/555"],
+ ),
+ # A Standard run that started before the reactions path posted a status comment of its own.
+ (
+ "legacy_standard_edits_its_status_comment",
+ REVIEW_MODE_FLASH,
+ True,
+ False,
+ True,
+ [],
+ ["/repos/o/r/issues/comments/555"],
+ ),
+ ]
+ )
+ @patch(_INTEGRATION)
+ @patch(_PAGINATED)
+ @patch(_REQUEST)
+ def test_failed_turn_tells_the_pr_once(
+ self,
+ _name: str,
+ review_mode: str,
+ uses_status_comment: bool,
+ already_posted: bool,
+ last_attempt: bool,
+ expected_posts: list[str],
+ expected_patches: list[str],
+ mock_request: MagicMock,
+ mock_paginated: MagicMock,
+ mock_integration: MagicMock,
+ ) -> None:
+ _wire_auth(mock_integration)
+ report_id = upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata())
+ report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
+ report.status_comment_id = 555
+ report.head_sha = "sha-1"
+ report.save(update_fields=["status_comment_id", "head_sha"])
+ marker = failure_marker(report_id, "sha-1")
+ existing = [{"id": 9, "body": f"x\n{marker}", "user": {"login": "posthog[bot]", "type": "Bot"}}]
+ mock_paginated.return_value = iter(existing if already_posted else [])
+
+ _fail_run(
+ self.team.id,
+ report_id,
+ review_mode=review_mode,
+ last_attempt=last_attempt,
+ uses_status_comment=uses_status_comment,
+ )
+
+ assert _posts(mock_request) == expected_posts
+ assert _patches(mock_request) == expected_patches
+ if expected_posts:
+ body = mock_request.call_args.kwargs["json"]["body"]
+ assert body.startswith("### PostHog Review · Standard · couldn't review `sha-1`")
+ assert "Push a new commit to run it again." in body
+ assert body.endswith(marker)
diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.py
index dd59db767624..268f94917adb 100644
--- a/products/review_hog/backend/tests/test_temporal_workflow.py
+++ b/products/review_hog/backend/tests/test_temporal_workflow.py
@@ -55,6 +55,7 @@ from products.review_hog.backend.temporal.activities import (
ResolveActingUserResult,
ReviewChunkInput,
ReviewMeta,
+ ReviewReactionInput,
SandboxStageInput,
SelectPerspectivesInput,
StatusCommentInput,
@@ -139,6 +140,7 @@ async def _run_full_review_pr_workflow(
meta_pr_number: int | None = 7,
empty_diff: bool = False,
fail_dedup: bool = False,
+ retryable_dedup_failures: int = 0,
selection: PerspectiveSelectionDTO | None = None,
fail_selection: bool = False,
fail_review_units: frozenset[tuple[int, int]] = frozenset(),
@@ -182,7 +184,6 @@ async def _run_full_review_pr_workflow(
# 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]] = []
- status_capped_parts: list[int | 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
@@ -344,11 +345,16 @@ async def _run_full_review_pr_workflow(
coordinator_calls.append(input.lens_chunk_count)
return CoordinatorReviewResult(lens_failures=coordinator_lens_failures)
+ dedup_attempts: list[int] = []
+
@activity.defn(name="dedup_activity")
async def dedup(input: SandboxStageInput) -> DedupResult:
_saw_design("dedup", input.review_design)
if fail_dedup:
raise ApplicationError("sandbox layer down", non_retryable=True)
+ dedup_attempts.append(1)
+ if len(dedup_attempts) <= retryable_dedup_failures:
+ raise ApplicationError("sandbox busy")
# Two survivors in two different chunks, so validate fans out one warm session per chunk.
flash_stats = _FLASH_TURN_STATS if input.review_design == "single_agent" else None
return DedupResult(issue_ids=["1-1-1", "1-2-1"], flash_stats=flash_stats)
@@ -400,13 +406,28 @@ async def _run_full_review_pr_workflow(
_saw_mode("status", input.review_mode)
finalize_status_calls.append((input.urgency_threshold, input.resolved_from, input.review_url))
marker_calls["status"] = input.marker
- status_capped_parts.append(input.capped_lens_parts)
return None
+ # Each failure edit as (review_mode, last_attempt, uses_status_comment).
+ fail_status_calls: list[tuple[str, bool, bool]] = []
+
@activity.defn(name="fail_status_comment_activity")
- async def fail_status(input) -> None:
+ async def fail_status(input: StatusCommentInput) -> None:
+ fail_status_calls.append((input.review_mode, input.last_attempt, input.uses_status_comment))
return None
+ # The PR's 👀 while the turn runs, as ("add",) and ("remove", reaction_id).
+ reaction_calls: list[tuple[str] | tuple[str, int | None]] = []
+
+ @activity.defn(name="add_review_reaction_activity")
+ async def add_reaction(input: ReviewReactionInput) -> int:
+ reaction_calls.append(("add",))
+ return 42
+
+ @activity.defn(name="remove_review_reaction_activity")
+ async def remove_reaction(input: ReviewReactionInput) -> None:
+ reaction_calls.append(("remove", input.reaction_id))
+
# Records the analytics events' run_index and the turn's trigger — the completion-rate
# denominator and the per-tier split rely on them; all three captures are swallowed best-effort
# in the workflow, so without these stubs deleting any of them would leave every test green.
@@ -478,6 +499,8 @@ async def _run_full_review_pr_workflow(
post_status,
finalize_status,
fail_status,
+ add_reaction,
+ remove_reaction,
track_failed,
track_completed,
track_started,
@@ -534,7 +557,6 @@ async def _run_full_review_pr_workflow(
"load_user_ids": load_user_ids,
"thresholds": threshold_calls,
"finalize_status": finalize_status_calls,
- "status_capped_parts": status_capped_parts,
"track_failed": track_failed_calls,
"track_completed": track_completed_calls,
"track_flash": track_flash_calls,
@@ -551,6 +573,8 @@ async def _run_full_review_pr_workflow(
"started_coordinator": started_coordinator,
"gate": gate_calls,
"status_posts": status_posts,
+ "fail_status": fail_status_calls,
+ "reactions": reaction_calls,
}
@@ -558,6 +582,8 @@ async def _run_full_review_pr_workflow(
async def test_review_pr_workflow_runs_all_stages_and_fans_out():
recorded = await _run_full_review_pr_workflow(publish=False)
assert recorded["result"] == "rep-1"
+ # An eval / CLI run keeps zero GitHub footprint.
+ assert recorded["reactions"] == []
# Review fans out per (perspective × chunk), then the always-on blind-spot check adds one unit
# per chunk; validate fans out one warm session per chunk.
wave = [c for c in recorded["review"] if not c[2]]
@@ -639,6 +665,9 @@ async def test_review_pr_workflow_publishes_only_when_publish_true():
assert recorded["finalize_status"] == [("must_fix", "override", _REVIEW_URL)]
# The marker recorded at turn start reaches the completed event and the comment footer intact.
assert recorded["markers"] == {"track": _TURN_MARKER, "status": _TURN_MARKER}
+ # A Deep turn keeps its status comment and also shows 👀 until it ends, removed by the id it got.
+ assert recorded["status_posts"] == ["rep-1"]
+ assert recorded["reactions"] == [("add",), ("remove", 42)]
@pytest.mark.asyncio
@@ -648,10 +677,37 @@ async def test_review_pr_workflow_removes_label_trigger_after_completion():
@pytest.mark.asyncio
-async def test_review_pr_workflow_removes_label_trigger_after_failure():
- recorded = await _run_full_review_pr_workflow(publish=True, trigger_source="label", fail_dedup=True)
[email protected]("review_mode", ["full", "flash"])
+async def test_review_pr_workflow_removes_label_trigger_after_failure(review_mode: str):
+ recorded = await _run_full_review_pr_workflow(
+ publish=True, trigger_source="label", fail_dedup=True, review_mode=review_mode
+ )
assert recorded["failed"] is True
assert recorded["remove_label"] == [7]
+ # A Standard turn has no status comment, but its failure still returns the report to rest and
+ # tells the PR. A dead turn must not leave its 👀 behind either.
+ assert recorded["fail_status"] == [(review_mode, True, review_mode == "full")]
+ assert recorded["reactions"] == [("add",), ("remove", 42)]
+
+
+ "dedup_failures, expected_failed, expected_fail_status",
+ [
+ # The second attempt succeeds, so the first attempt's failure must not tell the PR.
+ (5, False, [("flash", False, False)]),
+ (10, True, [("flash", False, False), ("flash", True, False)]),
+ ],
+)
+async def test_review_pr_workflow_reports_a_failure_only_on_the_last_attempt(
+ dedup_failures: int, expected_failed: bool, expected_fail_status: list[tuple[str, bool, bool]]
+):
+ # Dedup runs up to five activity attempts, so five failures fail one workflow attempt.
+ recorded = await _run_full_review_pr_workflow(
+ publish=True, review_mode="flash", retryable_dedup_failures=dedup_failures, workflow_max_attempts=2
+ )
+ assert recorded["failed"] is expected_failed
+ assert recorded["fail_status"] == expected_fail_status
@pytest.mark.asyncio
@@ -729,15 +785,19 @@ async def test_review_pr_workflow_flash_turn_threads_its_mode_and_never_chains_r
# Flash publishes every kept finding, whatever the acting user's threshold says.
assert {threshold for _, threshold in recorded["thresholds"]} == {"consider"}
assert recorded["modes"] == {
- stage: {"flash"} for stage in ("fetch", "select", "review", "validate", "publish", "status", "track")
+ stage: {"flash"} for stage in ("fetch", "select", "review", "validate", "publish", "track")
}
+ # A Standard turn posts no status comment: the 👀 shows that it runs, the review shows the outcome.
+ assert recorded["status_posts"] == []
+ assert recorded["finalize_status"] == []
+ assert recorded["reactions"] == [("add",), ("remove", 42)]
assert recorded["efforts"] == {stage: {effort} for stage in ("review", "validate", "track")}
@pytest.mark.asyncio
async def test_review_pr_workflow_single_agent_design_replaces_chunking_review_and_validation():
recorded = await _run_full_review_pr_workflow(
- publish=True, review_mode="flash", review_design="single_agent", lens_chunk_count=2, lens_chunks_capped=True
+ publish=True, review_mode="flash", review_design="single_agent", lens_chunk_count=2
)
assert recorded["single_agent"] == ["single_agent"]
@@ -749,8 +809,6 @@ async def test_review_pr_workflow_single_agent_design_replaces_chunking_review_a
]
# A lens session on the sandbox timeout would hold the main findings back for up to an hour.
assert set(recorded["lens_timeouts"]) == {FLASH_LENS_SESSION_TIMEOUT}
- # The large-PR note lives only in the status comment, so the turn must hand it the part count.
- assert recorded["status_capped_parts"] == [2]
assert recorded["split"] == []
assert recorded["review"] == []
assert recorded["validate"] == []
@@ -842,7 +900,8 @@ async def test_automatic_reviews_recheck_consent_and_skip_completed_or_closed_pr
)
assert bool(recorded["review"]) is expected_review
assert bool(recorded["publish"]) is expected_review
- assert bool(recorded["status_posts"]) is expected_review
+ # A skipped turn leaves no 👀 on the PR.
+ assert recorded["reactions"] == ([("add",), ("remove", 42)] if expected_review else [])
@pytest.mark.asyncio
@@ -881,7 +940,7 @@ async def test_push_gate_judges_only_automatic_follow_ups(
)
assert recorded["gate"] == expected_gate
assert bool(recorded["review"] or recorded["single_agent"]) is expected_review
- assert bool(recorded["status_posts"]) is expected_review
+ assert recorded["reactions"] == ([("add",), ("remove", 42)] if expected_review else [])
assert bool(recorded["track_started"]) is expected_review
@@ -896,6 +955,7 @@ async def test_review_pr_workflow_early_exits_when_already_published():
assert recorded["validate"] == []
assert recorded["publish"] == []
assert recorded["track_started"] == [] # a skipped turn never counts as started
+ assert recorded["reactions"] == []
@pytest.mark.asyncio
diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.py
index 42a4dad150a0..c6635dee1254 100644
--- a/products/stamphog/backend/temporal/constants.py
+++ b/products/stamphog/backend/temporal/constants.py
@@ -31,6 +31,8 @@ STAMPHOG_TRUSTED_REACTOR_BOTS = frozenset(
"copilot-pull-request-reviewer[bot]",
"greptile-apps[bot]",
"hex-security-app[bot]",
+ # PostHog Review, which posts as the PostHog GitHub App.
+ "posthog[bot]",
"veria-ai[bot]",
}
)
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 8b31ddc860cc..d0037e2c205d 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -1626,7 +1626,10 @@ def test_post_verdict_skips_when_the_base_moved_under_the_run(
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
-def test_bot_eyes_on_a_later_reactions_page_still_counts_as_in_flight(team, stamphog_chain: StamphogChain) -> None:
[email protected]("bot_login", ["greptile-apps[bot]", "posthog[bot]"])
+def test_bot_eyes_on_a_later_reactions_page_still_counts_as_in_flight(
+ team, stamphog_chain: StamphogChain, bot_login: str
+) -> None:
# Anyone can react on a public PR, so an author could bury the trusted bot's fresh 👀 past the
# first page with junk reactions; a first-page-only fetch would treat the bot as absent and let
# stamphog approve while that reviewer is still mid-review.
@@ -1639,14 +1642,14 @@ def test_bot_eyes_on_a_later_reactions_page_still_counts_as_in_flight(team, stam
)
now_iso = timezone.now().strftime("%Y-%m-%dT%H:%M:%SZ")
junk = [{"user": {"login": f"rando-{i}"}, "content": "heart", "created_at": now_iso} for i in range(100)]
- eyes = {"user": {"login": "greptile-apps[bot]"}, "content": "eyes", "created_at": now_iso}
+ eyes = {"user": {"login": bot_login}, "content": "eyes", "created_at": now_iso}
stamphog_chain.recorder.pr_reactions[(REPO, 115)] = [*junk, eyes]
result = _run_activity(
list_in_flight_reviewer_bots, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id)
)
- assert result["in_flight"] == ["greptile-apps[bot]"]
+ assert result["in_flight"] == [bot_login]
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
diff --git a/products/stamphog/packages/pr-approval-agent/README.md b/products/stamphog/packages/pr-approval-agent/README.md
index 0a4bb59d27b9..a074a3a74dd3 100644
--- a/products/stamphog/packages/pr-approval-agent/README.md
+++ b/products/stamphog/packages/pr-approval-agent/README.md
@@ -111,7 +111,7 @@ Tier classification
│
▼
Wait for in-flight bot reviews (skipped when gates already denied)
- - Reviewer bots (greptile, hex-security, codex) put 👀 on the PR while
+ - Reviewer bots (greptile, hex-security, codex, PostHog Review) put 👀 on the PR while
reviewing and swap it for a verdict reaction minutes later; the review is
triggered at the same moment, so an 👀 at fetch time is a race, not a
lasting state
diff --git a/products/stamphog/packages/pr-approval-agent/github.py b/products/stamphog/packages/pr-approval-agent/github.py
index 8a9bbaefbe25..c3ccc57e1863 100644
--- a/products/stamphog/packages/pr-approval-agent/github.py
+++ b/products/stamphog/packages/pr-approval-agent/github.py
@@ -95,6 +95,8 @@ TRUSTED_REACTOR_BOTS = {
"copilot-pull-request-reviewer[bot]",
"greptile-apps[bot]",
"hex-security-app[bot]",
+ # PostHog Review, which posts as the PostHog GitHub App.
+ "posthog[bot]",
"veria-ai[bot]",
}
diff --git a/products/stamphog/packages/pr-approval-agent/test_github.py b/products/stamphog/packages/pr-approval-agent/test_github.py
index 60896399981f..a8bbeafd4862 100644
--- a/products/stamphog/packages/pr-approval-agent/test_github.py
+++ b/products/stamphog/packages/pr-approval-agent/test_github.py
@@ -285,6 +285,7 @@ def test_reaction_emoji_normalizes_rest_and_graphql(content: str, expected: str)
pytest.param("ghost", False, id="deleted-user"),
pytest.param("", False, id="empty-login"),
pytest.param("greptile-apps[bot]", True, id="allowlisted-bot"),
+ pytest.param("posthog[bot]", True, id="posthog-review-bot"),
pytest.param("inkeep[bot]", False, id="unlisted-bot"),
pytest.param("teammate", True, id="org-member"),
pytest.param("outsider", False, id="external-non-member"),