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): trim the text ReviewHog posts on pull requests (#112415)

Julian Bez0eb76f984922
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index dd39bde464ab..65ed43623fde 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -260,7 +260,7 @@ Both review modes instruct the agent to fetch pinned review and validation skill
The agent can fetch referenced bundled files with `skill-file-get`.
On the configured internal project, choose **Review in Flash mode** from the review menu to run it for one turn without changing the PR's full-review configuration.
Flash requests preserve an existing report's review tier, including when they join a running review.
-Flash labels its GitHub messages with `FLASH MODE - Faster, but stupid, use regular ReviewHog for a heavy review` and never starts comment resolution.
+Flash marks its status comment header as `PostHog Review (flash)`, skips the clean-review media, and never starts comment resolution.
**Review all your PRs in Flash mode** is off by default and shown only on the configured internal project.
Turn it on in Code review to review PRs you author in `PostHog/posthog` when they open or receive new commits, including drafts.
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 2d70a85b1490..07f240283347 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -349,9 +349,14 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /
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).
- Every message a **flash** turn writes — the status comment in each of its states, the promo comment, the
- review body, and each inline comment — opens with `FLASH MODE - Faster, but stupid, use regular ReviewHog for a heavy review` + newline (`message_prefix_for_mode`), applied
- in `_post_github_review` and the status-comment renderers before redaction.
+ The status comment header of a **flash** turn, in each of its states, names `PostHog Review (flash)` instead of `PostHog Review`.
+ A clean flash turn shows the plain line "Nothing worth raising." and never the clean-review media; a full turn follows the `celebrate_clean_reviews` setting.
+ Flash comments posted before reviewhog-flash-1-1 open with a banner line (`LEGACY_FLASH_MODE_MESSAGE_PREFIX`); the publish-idempotency scan and the outcome comment matcher still recognize it.
+ The promo, the review body, and the inline comments carry no flash label, so one review shows the label once.
+ An inline comment holds the title, a plain-text severity line, the issue, and the suggested fix, then the hidden `REVIEW_HOG_FINDING_MARKER`.
+ 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.
+ 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
finalized turn (published or stored), carrying repository / PR / trigger / finding-count / PR-size properties
diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.py
index 584c26e5776d..f9225f352f1b 100644
--- a/products/review_hog/backend/reviewer/constants.py
+++ b/products/review_hog/backend/reviewer/constants.py
@@ -69,8 +69,8 @@ REVIEW_MODE_FLASH = "flash"
# Bump a mode's (major, minor) with a pipeline or design change. Prompt, skill, and model pin edits
# change the turn fingerprint (`reviewer/fingerprint.py`) instead.
REVIEWHOG_VERSIONS: dict[str, tuple[int, int]] = {
- REVIEW_MODE_FULL: (1, 0),
- REVIEW_MODE_FLASH: (1, 0),
+ REVIEW_MODE_FULL: (1, 1),
+ REVIEW_MODE_FLASH: (1, 1),
}
@@ -88,13 +88,9 @@ FLASH_ARM = ReviewArm(
initial_permission_mode="full-access",
)
-# Every GitHub message a flash turn writes (status comment, promo, review body, inline comments)
-# starts with this, so a reader can tell a flash review from a full one at a glance.
-FLASH_MODE_MESSAGE_PREFIX = "FLASH MODE - Faster, but stupid, use regular ReviewHog for a heavy review\n"
-
-
-def message_prefix_for_mode(review_mode: str) -> str:
- return FLASH_MODE_MESSAGE_PREFIX if review_mode == REVIEW_MODE_FLASH else ""
+# Flash comments posted before reviewhog-flash-1-1 open with this banner. Comments on old pull
+# requests keep it, so the matchers that read them back still remove it.
+LEGACY_FLASH_MODE_MESSAGE_PREFIX = "FLASH MODE - Faster, but stupid, use regular ReviewHog for a heavy review\n"
def flash_arm_for_effort(reasoning_effort: str) -> ReviewArm:
diff --git a/products/review_hog/backend/reviewer/outcomes/comment_signal.py b/products/review_hog/backend/reviewer/outcomes/comment_signal.py
index e363557312f0..b9fbce942c09 100644
--- a/products/review_hog/backend/reviewer/outcomes/comment_signal.py
+++ b/products/review_hog/backend/reviewer/outcomes/comment_signal.py
@@ -10,6 +10,7 @@ summary, so replies and reactions are read without any extra call or GraphQL.
from typing import Any
from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding
+from products.review_hog.backend.reviewer.constants import LEGACY_FLASH_MODE_MESSAGE_PREFIX
from products.review_hog.backend.reviewer.tools.github_client import is_app_bot_author
@@ -31,7 +32,10 @@ def find_finding_comment(
for comment in review_comments:
if comment.get("path") != finding.file:
continue
- first_line = (comment.get("body") or "").split("\n", 1)[0].rstrip()
+ # Flash comments posted before reviewhog-flash-1-1 open with the flash banner line, so the
+ # banner is removed before the title check.
+ body = (comment.get("body") or "").removeprefix(LEGACY_FLASH_MODE_MESSAGE_PREFIX)
+ first_line = body.split("\n", 1)[0].rstrip()
if first_line == heading:
return comment
return None
diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.py
index e3db4e0c181f..23dbafc21315 100644
--- a/products/review_hog/backend/reviewer/status_comment.py
+++ b/products/review_hog/backend/reviewer/status_comment.py
@@ -31,9 +31,9 @@ from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.constants import (
PRIORITIES_BY_URGENCY,
PRIORITY_LABELS,
+ REVIEW_MODE_FLASH,
REVIEW_MODE_FULL,
effective_priority,
- message_prefix_for_mode,
published_priorities_for,
)
from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarker
@@ -157,6 +157,10 @@ 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 _product_name(review_mode: str) -> str:
+ return "PostHog Review (flash)" if review_mode == REVIEW_MODE_FLASH else "PostHog Review"
+
+
def _plural(count: int, noun: str) -> str:
return f"{count} {noun}" if count == 1 else f"{count} {noun}s"
@@ -169,9 +173,9 @@ def render_in_progress_body(
done = progress.get("done") if progress else None
total = progress.get("total") if progress else None
counter = f" · {done}/{total}" if done is not None and total else ""
- return message_prefix_for_mode(review_mode) + "\n".join(
+ return "\n".join(
[
- "### \U0001f994 PostHog Review is reviewing this pull request",
+ f"### \U0001f994 {_product_name(review_mode)} is reviewing this pull request",
"",
f"**{label}{counter}**",
"",
@@ -211,8 +215,11 @@ def render_final_body(
found_line = "Found " + ", ".join(
f"**{counts[priority]} {PRIORITY_LABELS[priority]}**" for priority in PRIORITIES_BY_URGENCY
)
- lines = ["### \U0001f994 PostHog Review reviewed this pull request", ""]
- if found_total == 0 and celebrate_clean_reviews:
+ lines = [f"### \U0001f994 {_product_name(review_mode)} reviewed this pull request", ""]
+ # A flash turn is the quick pass, so a clean one gets a plain line instead of the celebration.
+ if found_total == 0 and review_mode == REVIEW_MODE_FLASH:
+ lines.append("Nothing worth raising.")
+ elif found_total == 0 and celebrate_clean_reviews:
media_url, media_alt = random.choice(_NO_ISSUES_MEDIA)
lines.extend(
[
@@ -245,7 +252,7 @@ def render_final_body(
lines.extend(["", status_marker(report_id)])
if marker is not None:
lines.append(marker.hidden_comment())
- return message_prefix_for_mode(review_mode) + "\n".join(lines)
+ return "\n".join(lines)
def render_resolution_progress_section(*, done: int, total: int, fixed: int, left_for_you: int) -> str:
@@ -323,9 +330,9 @@ def _splice_resolution_section(body: str, section: str) -> str:
def render_failed_body(report_id: str, *, review_mode: str = REVIEW_MODE_FULL) -> str:
- return message_prefix_for_mode(review_mode) + "\n".join(
+ return "\n".join(
[
- "### \U0001f994 PostHog Review couldn't finish this review",
+ f"### \U0001f994 {_product_name(review_mode)} couldn't finish this review",
"",
"The review run failed partway. It will run again on the next push to this pull request.",
"",
diff --git a/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py b/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py
index 82b1b14958ee..0487df7f3f6e 100644
--- a/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py
+++ b/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py
@@ -2,7 +2,10 @@ from typing import Any
from django.test import override_settings
+from parameterized import parameterized
+
from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding
+from products.review_hog.backend.reviewer.constants import LEGACY_FLASH_MODE_MESSAGE_PREFIX
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority, LineRange
from products.review_hog.backend.reviewer.outcomes.comment_signal import engagement_method, find_finding_comment
@@ -21,10 +24,16 @@ def _finding(title: str = "Off-by-one", file: str = "f.py") -> ReviewIssueFindin
class TestFindFindingComment:
- def test_matches_by_path_and_title_heading(self):
+ @parameterized.expand(
+ [
+ ("current_layout", "### Off-by-one\n\n**Must fix** · bug"),
+ ("old_flash_banner", f"{LEGACY_FLASH_MODE_MESSAGE_PREFIX}### Off-by-one\n\n![badge](x)"),
+ ]
+ )
+ def test_matches_by_path_and_title_heading(self, _name: str, body: str):
# ReviewHog's comment body leads with "### {title}"; matching on that + path is how a finding
# maps to its posted comment without a stored id, and it must survive extra body content.
- comments: list[dict[str, Any]] = [{"id": 1, "path": "f.py", "body": "### Off-by-one\n\n![badge](x)"}]
+ comments: list[dict[str, Any]] = [{"id": 1, "path": "f.py", "body": body}]
assert find_finding_comment(finding=_finding(), review_comments=comments) == comments[0]
def test_no_match_on_different_path(self):
diff --git a/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.py b/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.py
index d7d054aff18b..20712fbb5e3c 100644
--- a/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.py
+++ b/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.py
@@ -156,7 +156,6 @@ def test_off_diff_finding_sections_lead_with_description() -> None:
)
positions = [
- body.index(f"<summary><strong>{label}</strong></summary>")
- for label in ("Issue description", "Why we think it's a valid issue", "Suggested fix")
+ body.index(f"<summary><strong>{label}</strong></summary>") for label in ("Issue description", "Suggested fix")
]
assert positions == sorted(positions)
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 d4a101b7b7df..8cd1de8999f5 100644
--- a/products/review_hog/backend/reviewer/tests/test_publish_review.py
+++ b/products/review_hog/backend/reviewer/tests/test_publish_review.py
@@ -8,11 +8,13 @@ from parameterized import parameterized
from posthog.egress.github.transport import GitHubRateLimitError
from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdict
-from products.review_hog.backend.reviewer.constants import FLASH_MODE_MESSAGE_PREFIX, published_priorities_for
+from products.review_hog.backend.reviewer.constants import published_priorities_for
+from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRFileUpdate
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority, LineRange
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
from products.review_hog.backend.reviewer.tools.github_threads import REVIEW_HOG_FINDING_MARKER
from products.review_hog.backend.reviewer.tools.publish_review import (
+ FALLBACK_BODY_MAX_CHARS,
ReviewComment,
_build_inline_comments,
_format_issue_comment,
@@ -95,41 +97,6 @@ class TestPostGithubReview:
assert payload["commit_id"] == "deadbeef"
assert payload["comments"] == comments
- def test_message_prefix_opens_the_promo_the_body_and_every_inline_comment(
- self, mock_request: MagicMock, mock_paginated: MagicMock
- ) -> None:
- # A flash review is labeled on every message it writes. A prefix applied to the body alone
- # would leave inline comments indistinguishable from a full review's, and one applied after
- # redaction would bypass the credential scrub on the prefixed text.
- _wire_readbacks(mock_paginated)
- comments: list[ReviewComment] = [
- {"path": "a.py", "body": "first", "side": "RIGHT", "line": 1},
- {"path": "b.py", "body": "second", "side": "RIGHT", "line": 2},
- ]
-
- _post_github_review(
- "o",
- "r",
- 1,
- "body",
- comments,
- token="t",
- head_sha="",
- post_promo=True,
- marker="m",
- promo_marker="pm",
- message_prefix=FLASH_MODE_MESSAGE_PREFIX,
- )
-
- (promo,) = _promo_posts(mock_request)
- assert promo["body"].startswith(f"{FLASH_MODE_MESSAGE_PREFIX}PostHog Review alpha")
- (payload,) = _review_posts(mock_request)
- assert payload["body"] == f"{FLASH_MODE_MESSAGE_PREFIX}body"
- assert [c["body"] for c in payload["comments"]] == [
- f"{FLASH_MODE_MESSAGE_PREFIX}first",
- f"{FLASH_MODE_MESSAGE_PREFIX}second",
- ]
-
def test_credential_shapes_are_scrubbed_before_posting(
self, mock_request: MagicMock, mock_paginated: MagicMock
) -> None:
@@ -237,7 +204,14 @@ class TestPostGithubReview:
# 422 = GitHub rejected the comment payload itself; a retry would hit the same wall, so the
# review must still land as body-only rather than failing the publish forever.
_wire_readbacks(mock_paginated)
- comments: list[ReviewComment] = [{"path": "a.py", "body": "x", "side": "RIGHT", "line": 1}]
+ comments: list[ReviewComment] = [
+ {
+ "path": "a.py",
+ "body": f"### Token leaks into logs\n\nThe token is logged.\n\n{REVIEW_HOG_FINDING_MARKER}",
+ "side": "RIGHT",
+ "line": 1,
+ }
+ ]
def request(method: str, path: str, **kwargs: Any) -> MagicMock:
if method == "POST" and path.endswith("/reviews") and "comments" in (kwargs.get("json") or {}):
@@ -247,12 +221,80 @@ class TestPostGithubReview:
mock_request.side_effect = request
_post_github_review(
- "o", "r", 1, "body", comments, token="t", head_sha="", post_promo=False, marker="m", promo_marker="pm"
+ "o",
+ "r",
+ 1,
+ "body\n\nm",
+ comments,
+ token="t",
+ head_sha="",
+ post_promo=False,
+ marker="m",
+ promo_marker="pm",
+ inline_body="m",
)
first, second = _review_posts(mock_request)
assert first["comments"] == comments
+ assert first["body"] == "m"
assert "comments" not in second
+ # The inline-only findings must survive in the fallback body, or the review posts a bare tally.
+ assert second["body"].startswith("body\n\nm")
+ assert "### Token leaks into logs" in second["body"]
+ assert "The token is logged." in second["body"]
+ assert REVIEW_HOG_FINDING_MARKER not in second["body"]
+
+ def _fallback_body(self, mock_request: MagicMock, mock_paginated: MagicMock, comments: list[ReviewComment]) -> str:
+ _wire_readbacks(mock_paginated)
+
+ def request(method: str, path: str, **kwargs: Any) -> MagicMock:
+ if method == "POST" and path.endswith("/reviews") and "comments" in (kwargs.get("json") or {}):
+ raise GitHubAPIError("GitHub API POST returned 422: Unprocessable Entity", status=422)
+ return MagicMock()
+
+ mock_request.side_effect = request
+ _post_github_review(
+ "o",
+ "r",
+ 1,
+ "body\n\nm",
+ comments,
+ token="t",
+ head_sha="",
+ post_promo=False,
+ marker="m",
+ promo_marker="pm",
+ inline_body="m",
+ )
+ _first, second = _review_posts(mock_request)
+ return second["body"]
+
+ def test_fallback_renders_a_path_with_backticks_inside_a_longer_fence(
+ self, mock_request: MagicMock, mock_paginated: MagicMock
+ ) -> None:
+ comments: list[ReviewComment] = [
+ {"path": "a`` **x**.py", "body": "finding", "side": "RIGHT", "line": 3},
+ {"path": "`edge`", "body": "finding", "side": "RIGHT", "line": 4},
+ ]
+
+ body = self._fallback_body(mock_request, mock_paginated, comments)
+
+ assert "```a`` **x**.py:3```" in body
+ assert "`` `edge`:4 ``" in body
+
+ def test_fallback_body_stays_under_the_limit_and_reports_omitted_findings(
+ self, mock_request: MagicMock, mock_paginated: MagicMock
+ ) -> None:
+ comments: list[ReviewComment] = [
+ {"path": f"f{i}.py", "body": "x" * 10_000, "side": "RIGHT", "line": i} for i in range(10)
+ ]
+
+ body = self._fallback_body(mock_request, mock_paginated, comments)
+
+ assert len(body) <= FALLBACK_BODY_MAX_CHARS
+ assert "`f0.py:0`" in body
+ assert "`f9.py:9`" not in body
+ assert "5 more finding(s) left out" in body
def test_skips_when_a_review_with_our_marker_is_already_present(
self, mock_request: MagicMock, mock_paginated: MagicMock
@@ -305,16 +347,42 @@ class TestPublishReviewGate:
mock_report.report_markdown = "# PostHog Review"
mock_report_cls.objects.for_team.return_value.get.return_value = mock_report
+ @parameterized.expand(
+ [
+ # 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),
+ ]
+ )
@patch(_POST)
@patch(_LOAD_FINDINGS)
@patch(_REPORT)
- def test_posts_body_when_all_publishable_findings_are_off_diff(
- self, mock_report_cls: MagicMock, mock_load: MagicMock, mock_post: MagicMock
+ def test_review_body_depends_on_which_findings_post_inline(
+ self,
+ _name: str,
+ finding_lines: list[int],
+ expected_comments: int,
+ expect_marker_only: bool,
+ mock_report_cls: MagicMock,
+ mock_load: MagicMock,
+ mock_post: MagicMock,
) -> None:
- # A valid should_fix 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.
self._wire_report(mock_report_cls)
- mock_load.return_value = [(_finding(), _verdict())]
+ mock_load.return_value = [
+ (_finding().model_copy(update={"lines": [LineRange(start=line, end=line)]}), _verdict())
+ for line in finding_lines
+ ]
+ pr_files = [
+ PRFile(
+ filename="src/auth.py",
+ status="modified",
+ additions=1,
+ deletions=0,
+ changes=[PRFileUpdate(type="addition", new_start_line=1, new_end_line=1, code="x")],
+ )
+ ]
outcome = publish_review(
owner="o",
@@ -323,7 +391,7 @@ class TestPublishReviewGate:
team_id=1,
report_id="rep",
run_index=1,
- pr_files=[],
+ pr_files=pr_files,
token="t",
head_sha="sha",
post_promo=False,
@@ -332,7 +400,10 @@ class TestPublishReviewGate:
assert outcome.posted is True
mock_post.assert_called_once()
- assert mock_post.call_args.args[4] == [] # body-only post: no inline comments resolved
+ 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)
@patch(_POST)
@patch(_LOAD_FINDINGS)
@@ -422,48 +493,30 @@ class TestPublishReviewGate:
assert len(comments) == expected_count
if expected_count:
- assert "should_fix" in comments[0]["body"] # the emitted comment displays the effective priority
+ assert "**Should fix**" in comments[0]["body"] # the emitted comment displays the effective priority
class TestFormatIssueComment:
@parameterized.expand(
[
- (IssuePriority.MUST_FIX, "must_fix-D1242F", "must_fix"),
- (IssuePriority.SHOULD_FIX, "should_fix-E36209", "should_fix"),
- (IssuePriority.CONSIDER, "consider-0969DA", "consider"),
+ (IssuePriority.MUST_FIX, "**Must fix**"),
+ (IssuePriority.SHOULD_FIX, "**Should fix**"),
+ (IssuePriority.CONSIDER, "**Consider**"),
]
)
- def test_severity_badge_tracks_priority(self, priority: IssuePriority, badge_fragment: str, alt: str) -> None:
- # The colored severity badge is the redesign's whole point: a swapped or recolored mapping (e.g.
- # must_fix rendering blue) ships a misleading comment, and no other test pins priority→badge.
+ def test_severity_line_tracks_priority(self, priority: IssuePriority, label: str) -> None:
body = _format_issue_comment(_finding(priority=priority), _verdict())
- assert f"/badge/{badge_fragment}" in body
- # Alt text is the raw enum value, so the priority still reads when the badge image can't load.
- assert f"![{alt}]" in body
+ assert f"{label} · bug" in body
- def test_layout_is_title_then_badges_then_collapsed_sections_description_first(self) -> None:
- # Title leads, badges tag it just beneath, and all four sections stay folded — with the
- # issue description first (the deliberate reading order: claim → what it is → why it's real).
- # Catches a badge/title reorder, a re-added `Priority | Lines` meta, a section surfaced inline
- # instead of collapsed, or a template refactor flipping the order back to validation-first.
+ def test_layout_is_title_severity_issue_fix_without_validator_notes(self) -> None:
finding = _finding()
body = _format_issue_comment(finding, _verdict())
- assert body.index(f"### {finding.title}") < body.index("![should_fix]") < body.index("<details>")
- positions = [
- body.index(f"<summary><strong>{label}</strong></summary>")
- for label in (
- "Issue description",
- "Why we think it's a valid issue",
- "Suggested fix",
- "Prompt to fix with AI (copy-paste)",
- )
- ]
- assert positions == sorted(positions)
- # Problem and fix stay inside <details>, not surfaced above the first one.
- assert finding.body not in body[: body.index("<details>")]
- assert "**Priority:**" not in body and "**Lines:**" not in body
+ assert body.split("\n", 1)[0] == f"### {finding.title}"
+ assert body.index("**Should fix**") < body.index(finding.body) < body.index("**Suggested fix**")
+ assert "reason" not in body
+ assert "<details>" not in body and "![" not in body
def test_carries_the_self_detection_marker_for_the_resolution_stage(self) -> None:
# The resolution stage's `_source_rank` recognizes ReviewHog's own threads by this hidden marker
diff --git a/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py b/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py
index 5f0e3b21c9b9..e6e50bc6a5d5 100644
--- a/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py
+++ b/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py
@@ -131,14 +131,6 @@ def _render_off_diff_section(findings: list[tuple[Issue, IssueValidation]]) -> l
"</details>",
"",
"<details>",
- "<summary><strong>Why we think it's a valid issue</strong></summary>",
- "<br>",
- "",
- validation.argumentation,
- "",
- "</details>",
- "",
- "<details>",
"<summary><strong>Suggested fix</strong></summary>",
"<br>",
"",
diff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.py
index df9c94ccc192..5e5e5985e05f 100644
--- a/products/review_hog/backend/reviewer/tools/publish_review.py
+++ b/products/review_hog/backend/reviewer/tools/publish_review.py
@@ -1,3 +1,4 @@
+import re
import logging
from dataclasses import dataclass
from typing import Any, Required, TypedDict
@@ -9,10 +10,11 @@ from posthog.egress.github.transport import GitHubRateLimitError
from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdict
from products.review_hog.backend.reviewer.constants import (
+ LEGACY_FLASH_MODE_MESSAGE_PREFIX,
+ PRIORITY_LABELS,
REVIEW_MODE_FLASH,
REVIEW_MODE_FULL,
effective_priority,
- message_prefix_for_mode,
published_priorities_for,
)
from products.review_hog.backend.reviewer.diff_position import build_diff_line_map, find_diff_position
@@ -31,6 +33,9 @@ from products.review_hog.backend.reviewer.tools.redaction import redact_secrets
logger = logging.getLogger(__name__)
+# GitHub rejects a review body over 65,536 characters; the margin covers the closing line.
+FALLBACK_BODY_MAX_CHARS = 60_000
+
class ReviewComment(TypedDict, total=False):
"""One inline comment in the `POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews` body."""
@@ -231,6 +236,10 @@ def publish_review(
logger.info("No publishable issues found, skipping review")
return PublishOutcome(posted=False)
+ # 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
+
logger.info(f"Review: {len(body)} chars body, {len(comments)} inline comments")
review_url = _post_github_review(
owner,
@@ -244,124 +253,47 @@ def publish_review(
marker=marker,
promo_marker=_promo_marker(report_id),
installation_id=installation_id,
- message_prefix=message_prefix_for_mode(review_mode),
+ inline_body=inline_body,
legacy_marker=_review_marker(report_id, head_sha),
review_mode=review_mode,
)
return PublishOutcome(posted=True, review_url=review_url)
-# Severity badge (label, shields.io hex color) per priority. The badge is a shields.io image, so its
-# alt text is the raw enum value: the priority still reads in email digests and when images are
-# blocked, and screen readers announce it. Colors track a red → orange → blue calm-down scale.
-_PRIORITY_BADGE: dict[IssuePriority, tuple[str, str]] = {
- IssuePriority.MUST_FIX: ("must fix", "D1242F"),
- IssuePriority.SHOULD_FIX: ("should fix", "E36209"),
- IssuePriority.CONSIDER: ("consider", "0969DA"),
-}
-# Neutral grey for the category chip — it's context, not severity, so it shouldn't compete for color.
-_CATEGORY_BADGE_COLOR = "656D76"
-
-
-def _shields_badge(label: str, color: str, *, alt: str) -> str:
- """One shields.io badge as a markdown image. A literal space in `label` is encoded as `_` (shields
- renders `_` back as a space); `alt` is what shows when the image can't load (email, blocked, a11y).
- """
- return f"![{alt}](https://img.shields.io/badge/{label.replace(' ', '_')}-{color})"
-
-
-def _finding_badge_line(priority: IssuePriority, category: str | None) -> str:
- """The colored severity (+ optional category) badge line leading an inline finding comment."""
- label, color = _PRIORITY_BADGE[priority]
- badges = [_shields_badge(label, color, alt=priority.value)]
+def _finding_meta_line(priority: IssuePriority, category: str | None) -> str:
+ """The severity (+ optional category) line under the title, in plain text so it reads the same
+ in the PR, in email notifications, and with images blocked."""
+ meta = f"**{PRIORITY_LABELS[priority].capitalize()}**"
if category:
- # `code_quality` renders as "code quality" — shields already turns a single `_` into a space.
- badges.append(_shields_badge(category, _CATEGORY_BADGE_COLOR, alt=category))
- return " ".join(badges)
+ meta += f" · {category.replace('_', ' ')}"
+ return meta
def _format_issue_comment(finding: ReviewIssueFinding, verdict: ValidationVerdict) -> str:
- """Format a finding + its verdict as an inline comment body.
+ """Format a finding + its verdict as an inline comment body: title, severity, issue, fix.
- Leads with the title, then a line of colored severity/category badges (replacing the old
- `Priority | Category | Lines` text meta); four collapsed sections follow, the issue description
- first — the reading order is claim (title) → what the issue is (description) → why it's real
- (validation) → fix / AI prompt for whoever wants more. Line refs are omitted from
- the top — the comment is anchored inline and the lines live in the AI prompt.
+ The validator's argumentation stays out of the comment. It is stored on the verdict and the
+ reviews API returns it as `validator_note`. The title must stay the first line, because the
+ outcome sweep (`find_finding_comment`) matches a finding to its comment by that line.
"""
priority = effective_priority(finding.priority, verdict.adjusted_priority)
-
- lines = [
- f"### {finding.title}",
- "",
- _finding_badge_line(priority, verdict.category),
- "",
- "<details>",
- "<summary><strong>Issue description</strong></summary>",
- "<br>",
- "",
- finding.body,
- "",
- "</details>",
- "",
- "<details>",
- "<summary><strong>Why we think it's a valid issue</strong></summary>",
- "<br>",
- "",
- verdict.argumentation,
- "",
- "</details>",
- "",
- "<details>",
- "<summary><strong>Suggested fix</strong></summary>",
- "<br>",
- "",
- finding.suggestion,
- "",
- "</details>",
- "",
- "<details>",
- "<summary><strong>Prompt to fix with AI (copy-paste)</strong></summary>",
- "<br>",
- "",
- "```",
- "## Context",
- ]
-
- for lr in finding.lines:
- if lr.end is None or lr.end == lr.start:
- lines.append(f"@{finding.file}#L{lr.start}")
- else:
- lines.append(f"@{finding.file}#L{lr.start}-{lr.end}")
-
- lines.extend(
+ return "\n".join(
[
+ f"### {finding.title}",
"",
- "<issue_description>",
- finding.body,
- "</issue_description>",
+ _finding_meta_line(priority, verdict.category),
"",
- "<issue_validation>",
- verdict.argumentation,
- "</issue_validation>",
+ finding.body,
"",
- "## Task",
- "Investigate the issue and solve it",
+ "**Suggested fix**",
"",
- "<potential_solution>",
finding.suggestion,
- "</potential_solution>",
- "```",
- "",
- "</details>",
"",
# Hidden marker so the resolution stage recognizes this as one of ReviewHog's own threads.
REVIEW_HOG_FINDING_MARKER,
]
)
- return "\n".join(lines)
-
def _build_inline_comments(
valid_findings: list[tuple[ReviewIssueFinding, ValidationVerdict]],
@@ -427,9 +359,7 @@ def _review_already_posted(
or (
legacy_marker is not None
and legacy_marker in (review.get("body") or "")
- and (review.get("body") or "").startswith(
- ("FLASH MODE\n", message_prefix_for_mode(REVIEW_MODE_FLASH))
- )
+ and (review.get("body") or "").startswith(("FLASH MODE\n", LEGACY_FLASH_MODE_MESSAGE_PREFIX))
== (review_mode == REVIEW_MODE_FLASH)
)
)
@@ -470,6 +400,40 @@ def _promo_already_posted(
return True
+def _code_span(text: str) -> str:
+ """`text` as a Markdown code span whose fence is longer than any backtick run inside it."""
+ longest_run = max((len(run) for run in re.findall(r"`+", text)), default=0)
+ fence = "`" * (longest_run + 1)
+ # CommonMark strips one space on each side, so padding keeps an edge backtick from merging with the fence.
+ padding = " " if text.startswith("`") or text.endswith("`") else ""
+ return f"{fence}{padding}{text}{padding}{fence}"
+
+
+def _with_inline_findings(body: str, comments: list[ReviewComment]) -> str:
+ """`body` plus the inline comments written out, for the body-only fallback.
+
+ The stored body lists only the off-diff findings, so without this section a fallback post would
+ drop every finding that was meant to go inline. GitHub rejects a review body over 65,536
+ characters, so the section stops at `FALLBACK_BODY_MAX_CHARS` and says how many findings it left out.
+ """
+ if not comments:
+ return body
+ lines = [body, "", "## Findings on the changed lines", ""]
+ size = sum(len(line) + 1 for line in lines)
+ for index, comment in enumerate(comments):
+ # The thread marker belongs only on a real review thread, so the fallback leaves it out.
+ comment_body = comment["body"].replace(REVIEW_HOG_FINDING_MARKER, "").rstrip()
+ entry = [f"{_code_span(f'{comment["path"]}:{comment.get("line", "")}')}", "", comment_body, ""]
+ entry_size = sum(len(line) + 1 for line in entry)
+ if size + entry_size > FALLBACK_BODY_MAX_CHARS:
+ omitted = len(comments) - index
+ lines.append(f"{omitted} more finding(s) left out because the review body is too long.")
+ break
+ lines.extend(entry)
+ size += entry_size
+ return "\n".join(lines)
+
+
def _post_github_review(
owner: str,
repo: str,
@@ -483,14 +447,16 @@ def _post_github_review(
marker: str,
promo_marker: str,
installation_id: str | None = None,
- message_prefix: str = "",
+ inline_body: str | None = None,
legacy_marker: str | None = None,
review_mode: str = REVIEW_MODE_FULL,
) -> str | None:
"""Post the review to GitHub as a PR review, pinned to the reviewed `head_sha`.
- `message_prefix` opens every message this post writes (the promo comment, the review body, each
- inline comment), so a flash review is labeled as one wherever it shows up on the PR.
+ `inline_body` replaces `body` when the review posts together with its inline comments. The
+ body-only fallback posts the full `body` plus the text of every inline comment, because without
+ the comments the body is the only place the review shows anything. Both bodies must carry
+ `marker` for the idempotency check.
Returns the posted review's permalink, or None on the marker-found idempotency skip.
"""
# Idempotency: if our own review for this (report, head) is already on the PR — we posted it but
@@ -518,7 +484,7 @@ def _post_github_review(
installation_id=installation_id,
endpoint="/repos/{owner}/{repo}/issues/{issue_number}/comments",
json={
- "body": f"{message_prefix}PostHog Review alpha \U0001f994 "
+ "body": "PostHog Review alpha \U0001f994 "
"If you find any issues helpful - "
'please reply "valid", "invalid", etc., '
f"for evaluation purposes \U0001f64f\n\n{promo_marker}"
@@ -530,10 +496,12 @@ def _post_github_review(
# the probe isolates an unresolvable commit (stale/unreachable head) from a comment-positioning
# failure, so we post unpinned rather than failing (or dropping the inline comments).
# The review and validation sandboxes hold live tokens, and the model text arrives here unfiltered.
- body, redacted = redact_secrets(f"{message_prefix}{body}")
+ body, redacted = redact_secrets(body)
+ inline_body, count = redact_secrets(inline_body if inline_body is not None else body)
+ redacted += count
scrubbed: list[ReviewComment] = []
for comment in comments:
- comment_body, count = redact_secrets(f"{message_prefix}{comment['body']}")
+ comment_body, count = redact_secrets(comment["body"])
redacted += count
scrubbed.append({**comment, "body": comment_body})
comments = scrubbed
@@ -567,7 +535,7 @@ def _post_github_review(
if comments:
try:
- review_url = _create_review({**review_payload, "comments": comments})
+ review_url = _create_review({**review_payload, "body": inline_body, "comments": comments})
logger.info(f"Review posted with {len(comments)} inline comments")
return review_url
except GitHubAPIError as e:
@@ -576,6 +544,7 @@ def _post_github_review(
if e.status != 422:
raise
logger.warning(f"Failed to post review with inline comments: {e}. Posting review body only.")
+ review_payload["body"] = _with_inline_findings(body, comments)
review_url = _create_review(review_payload)
logger.info("Review posted (body only)")
diff --git a/products/review_hog/backend/tests/test_publish_idempotency.py b/products/review_hog/backend/tests/test_publish_idempotency.py
index 01a5bd46688a..07f1108259e3 100644
--- a/products/review_hog/backend/tests/test_publish_idempotency.py
+++ b/products/review_hog/backend/tests/test_publish_idempotency.py
@@ -10,7 +10,7 @@ from django.test import override_settings
from parameterized import parameterized
from products.review_hog.backend.models import ReviewReport
-from products.review_hog.backend.reviewer.constants import message_prefix_for_mode
+from products.review_hog.backend.reviewer.constants import LEGACY_FLASH_MODE_MESSAGE_PREFIX
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.persistence import upsert_review_report
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
@@ -82,7 +82,7 @@ def test_review_already_posted_proceeds_when_readback_fails() -> None:
[
("full", ""),
("flash", "FLASH MODE\n"),
- ("flash", message_prefix_for_mode("flash")),
+ ("flash", LEGACY_FLASH_MODE_MESSAGE_PREFIX),
]
)
def test_legacy_markers_only_suppress_reviews_in_the_same_mode(posted_mode: str, prefix: str) -> None:
diff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.py
index e03569b890be..b98de2750e4e 100644
--- a/products/review_hog/backend/tests/test_status_comment.py
+++ b/products/review_hog/backend/tests/test_status_comment.py
@@ -9,11 +9,7 @@ from django.utils import timezone
from parameterized import parameterized
from products.review_hog.backend.models import ReviewReport
-from products.review_hog.backend.reviewer.constants import (
- FLASH_MODE_MESSAGE_PREFIX,
- REVIEW_MODE_FLASH,
- REVIEW_MODE_FULL,
-)
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarker
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
@@ -59,7 +55,7 @@ class TestRenderInProgressBody:
assert status_marker("rid") in body # the marker is what makes edit-in-place reuse possible
-class TestFlashPrefix:
+class TestFlashHeader:
@parameterized.expand(
[
("in_progress", lambda mode: render_in_progress_body("rid", None, review_mode=mode)),
@@ -78,11 +74,14 @@ class TestFlashPrefix:
("failed", lambda mode: render_failed_body("rid", review_mode=mode)),
]
)
- def test_every_status_body_opens_with_the_prefix_only_in_flash(self, _name: str, render) -> None:
- # The status comment is rewritten in every state; a state that forgot the prefix would read
+ def test_every_status_header_names_flash_only_in_flash(self, _name: str, render) -> None:
+ # The status comment is rewritten in every state; a state that forgot the label would read
# as a full review mid-run or at the end, and a full run must never carry it.
- assert render(REVIEW_MODE_FLASH).startswith(f"{FLASH_MODE_MESSAGE_PREFIX}### ")
- assert not render(REVIEW_MODE_FULL).startswith("FLASH MODE")
+ flash, full = render(REVIEW_MODE_FLASH), render(REVIEW_MODE_FULL)
+ assert flash.startswith("### \U0001f994 PostHog Review (flash) ")
+ assert full.startswith("### \U0001f994 PostHog Review ")
+ assert "(flash)" not in full
+ assert "FLASH MODE" not in flash + full
class TestRenderFinalBody:
@@ -196,10 +195,17 @@ class TestRenderFinalBody:
# 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
- @parameterized.expand([("default_on", True), ("author_opted_out", False)])
+ @parameterized.expand(
+ [
+ ("default_on", REVIEW_MODE_FULL, True, True),
+ ("author_opted_out", REVIEW_MODE_FULL, False, False),
+ # A clean flash turn never celebrates, whatever the setting says.
+ ("flash", REVIEW_MODE_FLASH, True, False),
+ ]
+ )
@patch(f"{_MODULE}.random.choice", return_value=("https://example.test/dog.png", "A happy dog"))
def test_clean_review_media_follows_the_preference(
- self, _name: str, celebrate: bool, mock_choice: MagicMock
+ self, _name: str, review_mode: str, celebrate: bool, expect_media: bool, mock_choice: MagicMock
) -> None:
body = render_final_body(
"rid",
@@ -208,16 +214,19 @@ class TestRenderFinalBody:
held_back_count=0,
threshold=IssuePriority.SHOULD_FIX,
review_url=None,
+ review_mode=review_mode,
celebrate_clean_reviews=celebrate,
)
- if celebrate:
+ if expect_media:
assert "![A happy dog](https://example.test/dog.png)" in body
mock_choice.assert_called_once()
else:
assert "dog.png" not in body
assert "Enjoy the moment" not in body
mock_choice.assert_not_called()
+ if review_mode == REVIEW_MODE_FLASH:
+ assert "Nothing worth raising." in body
def _pr_metadata(pr_number: int = 123) -> PRMetadata:
@@ -273,7 +282,7 @@ class TestEnsureStatusComment(BaseTest):
ensure_status_comment(self.team.id, str(report.id), review_mode=REVIEW_MODE_FLASH)
assert _posts(mock_request) == ["/repos/o/r/issues/123/comments"]
- assert mock_request.call_args.kwargs["json"]["body"].startswith(FLASH_MODE_MESSAGE_PREFIX)
+ assert mock_request.call_args.kwargs["json"]["body"].startswith("### \U0001f994 PostHog Review (flash) ")
report.refresh_from_db()
assert report.status_comment_id == 777
assert report.status_comment_edited_at is not None
@@ -436,7 +445,7 @@ class TestFinalizeStatusComment(BaseTest):
assert "couldn't finish this review" in body
# The entry point threads the turn's mode into the renderer; a dropped kwarg here would
# leave a dead flash run reading as a full one.
- assert body.startswith(FLASH_MODE_MESSAGE_PREFIX)
+ assert body.startswith("### \U0001f994 PostHog Review (flash) ")
class TestResolutionSection:
diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsx
index 97a42cd6f965..bf193fac9639 100644
--- a/products/review_hog/frontend/CodeReviewScene.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.tsx
@@ -750,7 +750,7 @@ function TriggerReviewSection(): JSX.Element | null {
onClick={() =>
submitTriggerReview(ReviewTriggerRequestRunModeEnumApi.Flash)
}
- tooltip="A faster, cheaper review that never resolves comments. Every message it posts is marked FLASH MODE."
+ tooltip="A faster, cheaper review that never resolves comments. Its status comment is marked as flash."
>
Review in Flash mode
</LemonButton>