:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(review-hog): condense review comments to a p-level line and one paragraph (#113966)
Julian Bez1c9c60e22016
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 610318442b23..2b30d3b83fa2 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -306,11 +306,9 @@ priority, and the main session first on ties, before anything persists. Every mutimes the cap, and P2 and then P3 findings fill the slots left under the cap, `flash_max_findings(parts)` (4 plus 2 perlens part past the first, up to 10). No validator runs, so dedup writes anaccept-as-found verdict per survivor. P0/P1 store as `must_fix`, P2 as `should_fix`, P3 as `consider`, and the-finding's `reported_priority` keeps the reviewer's P0-P3, so P0 and P1 stay apart for analysis. Findings publish-inline; an-optional `suggestion_code` posts as a GitHub suggestion block only when the inline comment covers exactly the finding's-range and the code is at most `SUGGESTION_CODE_MAX_CHARS` long. The block's fence is longer than any backtick run in the-code, so the code cannot close it early. A PR past the lens part cap gets one line in the status comment that says the review ran in larger parts+finding's `reported_priority` keeps the reviewer's P0-P3, so P0 and P1 stay apart for analysis. One exception: a dedup survivor takes a more severe duplicate's level when both fold into the same stored priority (a P0 merged into a P1); the `dropped_finding` record keeps the duplicate's own level. Findings publish+inline. An+optional `suggestion_code` is stored on the finding but never posted. A PR past the lens part cap gets one line in the status comment that says the review ran in larger parts(`ReviewMeta.lens_chunks_capped`). The note goes there because a clean turn posts no review.Every finding the turn drops after scope cleaning persists as a `dropped_finding` artefact (`DroppedFindingArtefact`,@@ -429,7 +427,10 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /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`.+ An inline comment is one plain-text line, `**P{n} · {title}**`, then one paragraph with the issue and its fix (a pipeline finding's `suggestion` joins the body with one space), then the hidden `REVIEW_HOG_FINDING_MARKER`. No GitHub suggestion block is posted.+ A single-agent finding shows its `reported_priority` while that level still folds into the effective priority; otherwise `must_fix` shows P1, `should_fix` P2, and `consider` P3 (`display_level`).+ The body's Other-findings section uses the same heading, then the file and lines, then the same paragraph.+ 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.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.diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.mdindex 4183bd1836a1..23d48860de17 100644--- a/products/review_hog/DECISIONS.md+++ b/products/review_hog/DECISIONS.md@@ -198,6 +198,25 @@ read `FINAL_REPORT.md` there first (config glossary + coverage matrix + ranking)rate drops materially (toward ≤50%) on frozen-PR evals with the valid-finding set intact (item 5'scoverage matrix as the guard); kill if valid findings drop with the noise.+### ✅ BUILT 2026-10-08 — inline finding comments: one P-level heading and one paragraph++- **What.** An inline comment is `**P{n} · {title}**`, then one paragraph with the issue and its fix, then the hidden+ marker. A pipeline finding's `suggestion` joins its body with one space. The `### {title}` heading, the+ "Should fix · category" line, the "Suggested fix" header, and the GitHub suggestion block are gone. The body's+ "Other findings" section uses the same heading, then the file and lines, then the same paragraph, with no collapsed+ blocks and no category.+- **Why.** Every published finding is meant to be fixed, so a "should fix" label adds nothing, and the category does+ not change what the author does. Coding agents read most of these comments and apply the fix from the wording, so+ the suggestion block added length without value. `suggestion_code` stays stored on the finding for a later UI. The+ comment stays plain text, so it reads the same in email notifications.+- **P level.** A single-agent finding shows its own P0-P3 while that level still folds into the effective priority+ (validator override first, as before). A validator override or a dedup survivor raised by a more severe duplicate+ shows the mapped level instead: `must_fix` P1, `should_fix` P2, `consider` P3. Pipeline findings always map.+- **Matching.** `find_finding_comment` accepts the whole first line as `**P{n} · {title}**` for P0-P3 or as the old+ `### {title}`, so comments already on open PRs still match. The level is not checked, because it can change after+ publish. The resolution stage finds ReviewHog threads by the hidden marker, and the body-only fallback copies the+ comment text, so neither depends on the heading.+### ✅ BUILT 2026-10-08 — Flash v2: lens sessions, one short prioritized list, any PR size- **What.** A single-agent turn runs the main session and two lens sessions (performance and reliability, contractsdiff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.pyindex 7c1ca67fb99e..29df31a1d877 100644--- a/products/review_hog/backend/reviewer/constants.py+++ b/products/review_hog/backend/reviewer/constants.py@@ -1,3 +1,4 @@+import reimport loggingfrom dataclasses import dataclass, replacefrom datetime import timedelta@@ -6,7 +7,7 @@ from typing import TYPE_CHECKING, Finalfrom posthog.dataclasses import frozen-from products.review_hog.backend.reviewer.models.issues_review import IssuePriority+from products.review_hog.backend.reviewer.models.issues_review import IssuePriority, ReportedPriorityfrom products.review_hog.backend.reviewer.review_design import (REVIEW_DESIGN_PIPELINE,REVIEW_DESIGN_REASON_DEFAULT,@@ -447,6 +448,61 @@ PRIORITY_LABELS = {}+STORED_PRIORITY_BY_REPORTED: dict[ReportedPriority, IssuePriority] = {+ "P0": IssuePriority.MUST_FIX,+ "P1": IssuePriority.MUST_FIX,+ "P2": IssuePriority.SHOULD_FIX,+ "P3": IssuePriority.CONSIDER,+}++_DISPLAY_LEVEL_BY_PRIORITY: dict[IssuePriority, ReportedPriority] = {+ IssuePriority.MUST_FIX: "P1",+ IssuePriority.SHOULD_FIX: "P2",+ IssuePriority.CONSIDER: "P3",+}++# Most severe first. Storage folds P0 and P1 into `must_fix`, so only the reported level ranks them apart.+REPORTED_LEVELS: tuple[ReportedPriority, ...] = ("P0", "P1", "P2", "P3")+++def display_level(priority: IssuePriority, reported: ReportedPriority | None) -> ReportedPriority:+ """The P0-P3 level a published finding leads with, for its effective `priority`.++ The reviewer's own level applies only while it still folds into `priority`. A validator override+ or a dedup survivor that absorbed a more severe duplicate changes the priority, and then the+ reported level would show a severity that the finding no longer has.+ """+ if reported is not None and STORED_PRIORITY_BY_REPORTED[reported] == priority:+ return reported+ return _DISPLAY_LEVEL_BY_PRIORITY[priority]+++def finding_heading(title: str, level: ReportedPriority) -> str:+ """The first line of a published finding.++ The outcome sweep (`find_finding_comment`) matches a finding to its inline comment by this line.+ """+ return f"**{level} · {title}**"+++_MARKDOWN_BLOCK_START = re.compile(r"^\s*(```|~~~|[-*+] |\d+[.)] |>|#|\|)")+++def finding_text(body: str, suggestion: str) -> str:+ """The issue and its fix as one paragraph. A single-agent finding has no suggestion text, because its+ body already ends with the fix.++ A pipeline issue or fix can be Markdown with code blocks or lists, which a space would run into the+ other text, so those keep a paragraph break.+ """+ body, suggestion = body.strip(), suggestion.strip()+ if not suggestion:+ return body+ if "\n" in body or "\n" in suggestion or _MARKDOWN_BLOCK_START.match(suggestion):+ return f"{body}\n\n{suggestion}"+ return f"{body} {suggestion}"++def published_priorities_for(threshold: IssuePriority) -> set[IssuePriority]:"""Priorities at or above the acting user's urgency threshold — the set that gates publishing.diff --git a/products/review_hog/backend/reviewer/models/single_agent_review.py b/products/review_hog/backend/reviewer/models/single_agent_review.pyindex f932cd56b3a6..d457f256f9e2 100644--- a/products/review_hog/backend/reviewer/models/single_agent_review.py+++ b/products/review_hog/backend/reviewer/models/single_agent_review.py@@ -25,14 +25,17 @@ class SingleAgentFinding(BaseModel):description=("One paragraph of about 300-400 characters: the trigger (the input, state, or environment the"" problem needs), the consequence, and the anchor (the function, call site, or invariant involved)."- " End with at most one short clause on the fix direction."+ " End with one short clause on the fix direction, so a reader can act on the comment alone."+ ' State the problem as a fact without hedging (no "may" or "could potentially"), in active voice,'+ " with identifiers in backticks, and no opener or closing summary."))suggestion_code: str | None = Field(default=None,description=("Only when the fix is a small replacement you are certain of: the exact new code for line_start"- " to line_end, with the original indentation. Null otherwise."+ " to line_end, with the original indentation. Null otherwise. It is stored, not posted, so the body"+ " must still state the fix."),)diff --git a/products/review_hog/backend/reviewer/outcomes/comment_signal.py b/products/review_hog/backend/reviewer/outcomes/comment_signal.pyindex b9fbce942c09..e9e2193ccb17 100644--- a/products/review_hog/backend/reviewer/outcomes/comment_signal.py+++ b/products/review_hog/backend/reviewer/outcomes/comment_signal.py@@ -1,7 +1,7 @@"""The engagement signal: did a finding's inline comment get a reply or a reaction?-ReviewHog's published comments lead with ``### {finding.title}`` and anchor to the finding's file, so-a finding maps to its posted comment exactly by (path, title) — no stored comment id, and robust to+ReviewHog's published comments lead with a heading that holds ``finding.title`` and anchor to the+finding's file, so a finding maps to its posted comment exactly by (path, title) — no stored comment id, and robust toline drift after review (the match is on body content, not position). The one``GET /pulls/{n}/comments`` list carries both an ``in_reply_to_id`` per comment and a ``reactions``summary, so replies and reactions are read without any extra call or GraphQL.@@ -10,7 +10,11 @@ summary, so replies and reactions are read without any extra call or GraphQL.from typing import Anyfrom 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.constants import (+ LEGACY_FLASH_MODE_MESSAGE_PREFIX,+ REPORTED_LEVELS,+ finding_heading,+)from products.review_hog.backend.reviewer.tools.github_client import is_app_bot_author@@ -24,11 +28,13 @@ def find_finding_comment() -> dict[str, Any] | None:"""The review comment ReviewHog posted for ``finding``, matched by path + exact heading, or None.- The whole first line must equal ``### {title}`` — a prefix match would pair "Foo" with a comment- headed "### Foobar". First match wins if two findings in a file share a title (rare); the outcome- is the same engaged/not signal either way.+ The whole first line must equal ``**P{n} · {title}**`` for any P level, or ``### {title}`` for+ comments published before the P-level heading. A prefix match would pair "Foo" with a comment+ headed "Foobar". The level is not checked, because a validator override can change it after+ publish. First match wins if two findings in a file share a title (rare); the outcome is the same+ engaged/not signal either way."""- heading = f"### {finding.title}"+ headings = {f"### {finding.title}"} | {finding_heading(finding.title, level) for level in REPORTED_LEVELS}for comment in review_comments:if comment.get("path") != finding.file:continue@@ -36,7 +42,7 @@ def find_finding_comment(# 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:+ if first_line in headings:return commentreturn Nonediff --git a/products/review_hog/backend/reviewer/prompts/single_agent_review/prompt.jinja b/products/review_hog/backend/reviewer/prompts/single_agent_review/prompt.jinjaindex 82cc4c59e6a9..9cd85c340881 100644--- a/products/review_hog/backend/reviewer/prompts/single_agent_review/prompt.jinja+++ b/products/review_hog/backend/reviewer/prompts/single_agent_review/prompt.jinja@@ -53,8 +53,8 @@ For each finding:- `title`: at most 80 characters, imperative, without a `[P#]` tag.- `priority`: "P0", "P1", "P2", or "P3", with the meanings from the review guidelines.- `file`, `line_start`, `line_end`: the file path relative to the repository root, and the shortest line range at the head commit that shows the problem. Keep the range on the diff and under 10 lines. Set `line_end` to null for a single line.-- `body`: one paragraph of about 300-400 characters. Name the trigger (the input, state, or environment the problem needs), the consequence, and the anchor (the function, call site, or invariant involved). End with at most one short clause on the fix direction. Do not add a separate suggestion section.-- `suggestion_code`: only when the fix is a small replacement you are certain of, the exact new code for lines `line_start` to `line_end`, with the original indentation. Otherwise null.+- `body`: one paragraph of about 300-400 characters. Name the trigger (the input, state, or environment the problem needs), the consequence, and the anchor (the function, call site, or invariant involved). End with one short clause on the fix direction, so a reader can act on the comment alone. State the problem as a fact without hedging (no "may" or "could potentially"), in active voice, with identifiers in backticks, and no opener or closing summary. Do not add a separate suggestion section.+- `suggestion_code`: only when the fix is a small replacement you are certain of, the exact new code for lines `line_start` to `line_end`, with the original indentation. Otherwise null. It is stored, not posted, so the body must still state the fix.Return an empty findings list when nothing qualifies. Reply with only one JSON object that matches this schema. Do not wrap it in code fences and do not add prose.diff --git a/products/review_hog/backend/reviewer/prompts/single_agent_review/schema.json b/products/review_hog/backend/reviewer/prompts/single_agent_review/schema.jsonindex d7903fce4323..9bf36d5df561 100644--- a/products/review_hog/backend/reviewer/prompts/single_agent_review/schema.json+++ b/products/review_hog/backend/reviewer/prompts/single_agent_review/schema.json@@ -43,7 +43,7 @@"title": "Line End"},"body": {- "description": "One paragraph of about 300-400 characters: the trigger (the input, state, or environment the problem needs), the consequence, and the anchor (the function, call site, or invariant involved). End with at most one short clause on the fix direction.",+ "description": "One paragraph of about 300-400 characters: the trigger (the input, state, or environment the problem needs), the consequence, and the anchor (the function, call site, or invariant involved). End with one short clause on the fix direction, so a reader can act on the comment alone. State the problem as a fact without hedging (no \"may\" or \"could potentially\"), in active voice, with identifiers in backticks, and no opener or closing summary.","title": "Body","type": "string"},@@ -57,7 +57,7 @@}],"default": null,- "description": "Only when the fix is a small replacement you are certain of: the exact new code for line_start to line_end, with the original indentation. Null otherwise.",+ "description": "Only when the fix is a small replacement you are certain of: the exact new code for line_start to line_end, with the original indentation. Null otherwise. It is stored, not posted, so the body must still state the fix.","title": "Suggestion Code"}},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.pyindex 0487df7f3f6e..984b0e152433 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@@ -26,28 +26,32 @@ def _finding(title: str = "Off-by-one", file: str = "f.py") -> ReviewIssueFindinclass TestFindFindingComment:@parameterized.expand([- ("current_layout", "### Off-by-one\n\n**Must fix** · bug"),+ ("p_level_heading", "**P1 · Off-by-one**\n\nloop runs one short"),+ ("p_level_heading_other_level", "**P3 · Off-by-one**"),+ ("old_heading", "### Off-by-one\n\n**Must fix** · bug"),("old_flash_banner", f"{LEGACY_FLASH_MODE_MESSAGE_PREFIX}### Off-by-one\n\n"),])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": body}]assert find_finding_comment(finding=_finding(), review_comments=comments) == comments[0]def test_no_match_on_different_path(self):- comments: list[dict[str, Any]] = [{"id": 1, "path": "other.py", "body": "### Off-by-one"}]+ comments: list[dict[str, Any]] = [{"id": 1, "path": "other.py", "body": "**P1 · Off-by-one**"}]assert find_finding_comment(finding=_finding(), review_comments=comments) is None- def test_no_match_on_different_title(self):- comments: list[dict[str, Any]] = [{"id": 1, "path": "f.py", "body": "### Something else"}]- assert find_finding_comment(finding=_finding(), review_comments=comments) is None-- def test_no_match_when_title_is_a_prefix_of_the_heading(self):- # "Off-by-one" must not claim the comment for "Off-by-one in pagination" — a prefix match- # would attribute one thread's engagement to a different finding.- comments: list[dict[str, Any]] = [{"id": 1, "path": "f.py", "body": "### Off-by-one in pagination\n\nbody"}]+ @parameterized.expand(+ [+ ("different_title", "**P1 · Something else**"),+ # "Off-by-one" must not claim the comment for "Off-by-one in pagination", because a prefix+ # match would attribute one thread's engagement to a different finding.+ ("title_is_a_prefix", "**P1 · Off-by-one in pagination**\n\nbody"),+ ("title_is_a_prefix_old_heading", "### Off-by-one in pagination\n\nbody"),+ ("level_outside_p0_to_p3", "**P4 · Off-by-one**"),+ ]+ )+ def test_no_match_unless_the_whole_first_line_is_the_heading(self, _name: str, body: str):+ comments: list[dict[str, Any]] = [{"id": 1, "path": "f.py", "body": body}]assert find_finding_comment(finding=_finding(), review_comments=comments) is Nonediff --git a/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.py b/products/review_hog/backend/reviewer/tests/test_prepare_validation_markdown.pyindex 20712fbb5e3c..2c80db0fad03 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@@ -132,11 +132,9 @@ def test_other_findings_section_membership(assert ("Membership marker finding" in body) is expected_in_section-def test_off_diff_finding_sections_lead_with_description() -> None:- # The off-diff section must render its collapsed blocks in the same deliberate reading order as- # the inline comment (description first, then verdict, then fix). The two renderers are separate- # templates, so the inline-comment order test can't catch _render_off_diff_section flipping back- # to validation-first.+def test_off_diff_finding_uses_the_inline_comment_heading() -> None:+ # The off-diff section is a separate renderer from the inline comment, so it can drift back to the+ # old heading, category line, or collapsed blocks without the inline comment tests failing.issue = Issue(id="1-1-1",title="Off-diff finding",@@ -155,7 +153,7 @@ def test_off_diff_finding_sections_lead_with_description() -> None:published_priorities=_SHOULD_FIX_PUBLISHED,)- positions = [- body.index(f"<summary><strong>{label}</strong></summary>") for label in ("Issue description", "Suggested fix")- ]- assert positions == sorted(positions)+ section = body.split(+ "_Valid issues on this PR's files that sit on lines GitHub won't let us comment on inline._\n\n"+ )[1]+ assert section == "**P2 · Off-diff finding**\n\n`src/auth.py:240`\n\nproblem fix\n"diff --git a/products/review_hog/backend/reviewer/tests/test_publish_review.py b/products/review_hog/backend/reviewer/tests/test_publish_review.pyindex 7f8e095c6ae0..4002c0e55409 100644--- a/products/review_hog/backend/reviewer/tests/test_publish_review.py+++ b/products/review_hog/backend/reviewer/tests/test_publish_review.py@@ -10,12 +10,11 @@ from posthog.egress.github.transport import GitHubRateLimitErrorfrom products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdictfrom products.review_hog.backend.reviewer.constants import published_priorities_forfrom 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.models.issues_review import IssuePriority, LineRange, ReportedPriorityfrom products.review_hog.backend.reviewer.tools.github_client import GitHubAPIErrorfrom products.review_hog.backend.reviewer.tools.github_threads import REVIEW_HOG_FINDING_MARKERfrom products.review_hog.backend.reviewer.tools.publish_review import (FALLBACK_BODY_MAX_CHARS,- SUGGESTION_CODE_MAX_CHARS,ReviewComment,_build_inline_comments,_format_issue_comment,@@ -494,77 +493,86 @@ class TestPublishReviewGate:assert len(comments) == expected_countif expected_count:- assert "**Should fix**" in comments[0]["body"] # the emitted comment displays the effective priority+ assert comments[0]["body"].startswith("**P2 · Off-diff finding**")- @parameterized.expand(- [- ("range_fully_on_the_diff", {240, 241, 242}, True),- # The end line is off the diff, so the comment covers only line 240. GitHub would apply- # the three-line replacement to that one line and corrupt the file.- ("range_partly_off_the_diff", {240}, False),- ]- )- def test_suggestion_block_posts_only_when_the_comment_covers_the_finding_range(- self, _name: str, diff_line_numbers: set[int], expect_suggestion: bool- ) -> None:+ def test_suggestion_code_is_not_posted(self) -> None:finding = _finding().model_copy(- update={- "lines": [LineRange(start=240, end=242)],- "suggestion": "",- "suggestion_code": "a = 1\nb = 2\nc = 3",- }+ update={"lines": [LineRange(start=240, end=242)], "suggestion": "", "suggestion_code": "a = 1\nb = 2"})comments = _build_inline_comments(- [(finding, _verdict())], {"src/auth.py": diff_line_numbers}, _SHOULD_FIX_PUBLISHED+ [(finding, _verdict())], {"src/auth.py": {240, 241, 242}}, _SHOULD_FIX_PUBLISHED)assert len(comments) == 1- assert ("```suggestion\na = 1\nb = 2\nc = 3\n```" in comments[0]["body"]) is expect_suggestion- assert "**Suggested fix**" not in comments[0]["body"]+ assert "```" not in comments[0]["body"] and "a = 1" not in comments[0]["body"]class TestFormatIssueComment:@parameterized.expand([- (IssuePriority.MUST_FIX, "**Must fix**"),- (IssuePriority.SHOULD_FIX, "**Should fix**"),- (IssuePriority.CONSIDER, "**Consider**"),+ ("pipeline_must_fix", IssuePriority.MUST_FIX, None, None, "P1"),+ ("pipeline_should_fix", IssuePriority.SHOULD_FIX, None, None, "P2"),+ ("pipeline_consider", IssuePriority.CONSIDER, None, None, "P3"),+ ("single_agent_p0", IssuePriority.MUST_FIX, "P0", None, "P0"),+ ("single_agent_p1", IssuePriority.MUST_FIX, "P1", None, "P1"),+ ("single_agent_p2", IssuePriority.SHOULD_FIX, "P2", None, "P2"),+ ("single_agent_p3", IssuePriority.CONSIDER, "P3", None, "P3"),+ ("validator_lowers_a_p0", IssuePriority.MUST_FIX, "P0", IssuePriority.SHOULD_FIX, "P2"),+ ("validator_raises_a_p3", IssuePriority.CONSIDER, "P3", IssuePriority.MUST_FIX, "P1"),+ ("raised_by_dedup", IssuePriority.MUST_FIX, "P3", None, "P1"),])- def test_severity_line_tracks_priority(self, priority: IssuePriority, label: str) -> None:- body = _format_issue_comment(_finding(priority=priority), _verdict())+ def test_heading_shows_the_p_level_and_title(+ self,+ _name: str,+ priority: IssuePriority,+ reported: ReportedPriority | None,+ adjusted: IssuePriority | None,+ level: str,+ ) -> None:+ finding = _finding(priority=priority).model_copy(update={"reported_priority": reported})- assert f"{label} · bug" in body+ body = _format_issue_comment(finding, _verdict(adjusted_priority=adjusted))- def test_layout_is_title_severity_issue_fix_without_validator_notes(self) -> None:- finding = _finding()- body = _format_issue_comment(finding, _verdict())+ assert body.split("\n", 1)[0] == f"**{level} · Off-diff finding**"- 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_layout_is_heading_issue_fix_without_category_or_validator_notes(self) -> None:+ body = _format_issue_comment(_finding(), _verdict())++ assert body == f"**P2 · Off-diff finding**\n\nproblem fix\n\n{REVIEW_HOG_FINDING_MARKER}"+ assert "bug" not in body and "reason" not in body@parameterized.expand([- ("plain_code", "x = 1", "```"),- ("code_with_a_fence", 'DOC = """\n```python\nx = 1\n```\n"""', "````"),- ("code_with_a_longer_fence", "`````", "``````"),- ("code_over_the_size_cap", "x" * (SUGGESTION_CODE_MAX_CHARS + 1), None),+ ("plain_prose", "The cache misses.", "Key it by team.", "The cache misses. Key it by team."),+ (+ "fix_opens_a_code_block",+ "The cache misses.",+ "```py\nkey = team\n```",+ "The cache misses.\n\n```py\nkey = team\n```",+ ),+ (+ "fix_is_a_list",+ "The cache misses.",+ "- key by team\n- add a test",+ "The cache misses.\n\n- key by team\n- add a test",+ ),+ (+ "issue_ends_with_a_code_block",+ "Here:\n```\nx = 1\n```",+ "Remove it.",+ "Here:\n```\nx = 1\n```\n\nRemove it.",+ ),])- def test_suggestion_block_holds_the_whole_code(self, _name: str, code: str, fence: str | None) -> None:- # A backtick run in the code would close a shorter fence early, and GitHub would offer a cut-off- # replacement. An oversized suggestion is skipped, but the finding still posts.- finding = _finding().model_copy(update={"suggestion": "", "suggestion_code": code})-- body = _format_issue_comment(finding, _verdict(), with_suggestion_code=True)-- assert finding.body in body- if fence is None:- assert "suggestion\n" not in body- else:- assert f"\n{fence}suggestion\n{code}\n{fence}\n" in body+ def test_fix_joins_the_issue_without_breaking_markdown_blocks(+ self, _name: str, issue: str, suggestion: str, expected: str+ ) -> None:+ finding = _finding().model_copy(update={"body": issue, "suggestion": suggestion})++ body = _format_issue_comment(finding, _verdict())++ assert body == f"**P2 · Off-diff finding**\n\n{expected}\n\n{REVIEW_HOG_FINDING_MARKER}"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 markerdiff --git a/products/review_hog/backend/reviewer/tests/test_single_agent_review.py b/products/review_hog/backend/reviewer/tests/test_single_agent_review.pyindex 3dc4caa0907c..959951d91eac 100644--- a/products/review_hog/backend/reviewer/tests/test_single_agent_review.py+++ b/products/review_hog/backend/reviewer/tests/test_single_agent_review.py@@ -297,18 +297,20 @@ class TestDedupeFlashFindings:@pytest.mark.asyncio@pytest.mark.parametrize(- "survivor_level,duplicate_level,filler_source",+ "survivor_level,duplicate_level,filler_source,posted_level",[pytest.param(("P1", IssuePriority.MUST_FIX),("P0", IssuePriority.MUST_FIX),SINGLE_AGENT_SOURCE,+ "P0",id="lens_p0_into_main_p1_behind_main_p1s",),pytest.param(("P3", IssuePriority.CONSIDER),("P1", IssuePriority.MUST_FIX),_LENS_SOURCE,+ "P3",id="lens_p1_into_main_p3_behind_lens_p1s",),],@@ -319,6 +321,7 @@ class TestDedupeFlashFindings:survivor_level: tuple[ReportedPriority, IssuePriority],duplicate_level: tuple[ReportedPriority, IssuePriority],filler_source: str,+ posted_level: ReportedPriority,) -> None:# Storage folds P0 and P1 into must-fix and the order inside it reads the P level, so a survivor# ranked at its own level can be cut by the must-fix ceiling behind findings less severe than@@ -336,7 +339,8 @@ class TestDedupeFlashFindings:pr_metadata, [*fillers, survivor, duplicate], _flash_dedup(("2002-1-99", "2000-1-99")))- assert (selection.kept[0].id, selection.kept[0].reported_priority) == ("2000-1-99", survivor_level[0])+ # Within one stored priority the survivor takes the duplicate's level, so its comment leads with P0.+ assert (selection.kept[0].id, selection.kept[0].reported_priority) == ("2000-1-99", posted_level)dropped = {drop.issue.id: drop.issue.reported_priority for drop in selection.dropped}assert dropped["2002-1-99"] == duplicate_level[0]diff --git a/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py b/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.pyindex 286c1a94648e..725976b7e684 100644--- a/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py+++ b/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py@@ -8,7 +8,14 @@ in full in the "Other findings" section below the tally, because the body is theappear at all."""-from products.review_hog.backend.reviewer.constants import PRIORITIES_BY_URGENCY, PRIORITY_LABELS, effective_priority+from products.review_hog.backend.reviewer.constants import (+ PRIORITIES_BY_URGENCY,+ PRIORITY_LABELS,+ display_level,+ effective_priority,+ finding_heading,+ finding_text,+)from products.review_hog.backend.reviewer.diff_position import (build_diff_line_map,find_diff_position,@@ -113,37 +120,15 @@ def _render_off_diff_section(findings: list[tuple[Issue, IssueValidation]]) -> l]for issue, validation in findings:priority = effective_priority(issue.priority, validation.adjusted_priority)- meta = [f"**Priority:** {priority.value}", f"**File:** `{issue.file}:{format_line_ranges(issue.lines)}`"]- if validation.category:- meta.append(f"**Category:** {validation.category}")+ level = display_level(priority, issue.reported_priority)lines.extend([- f"### {issue.title}",- "",- " | ".join(meta),- "",- "<details>",- "<summary><strong>Issue description</strong></summary>",- "<br>",+ finding_heading(issue.title, level),"",- issue.issue,+ f"`{issue.file}:{format_line_ranges(issue.lines)}`","",- "</details>",+ finding_text(issue.issue, issue.suggestion),"",])- # A single-agent finding has no suggestion text: its description ends with the fix direction.- if issue.suggestion.strip():- lines.extend(- [- "<details>",- "<summary><strong>Suggested fix</strong></summary>",- "<br>",- "",- issue.suggestion,- "",- "</details>",- "",- ]- )return linesdiff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.pyindex 1a57db1881be..14953cbf3f94 100644--- a/products/review_hog/backend/reviewer/tools/publish_review.py+++ b/products/review_hog/backend/reviewer/tools/publish_review.py@@ -11,10 +11,12 @@ from products.review_hog.backend.models import ReviewReportfrom products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdictfrom products.review_hog.backend.reviewer.constants import (LEGACY_FLASH_MODE_MESSAGE_PREFIX,- PRIORITY_LABELS,REVIEW_MODE_FLASH,REVIEW_MODE_FULL,+ display_level,effective_priority,+ finding_heading,+ finding_text,published_priorities_for,)from products.review_hog.backend.reviewer.diff_position import build_diff_line_map, find_diff_position@@ -35,9 +37,6 @@ 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-# The reviewer only writes replacement code for a small fix, so a longer suggestion is a rewrite that-# does not belong in a one-click suggestion. It also keeps the comment far below GitHub's 65,536 characters.-SUGGESTION_CODE_MAX_CHARS = 4_000class ReviewComment(TypedDict, total=False):@@ -263,61 +262,29 @@ def publish_review(return PublishOutcome(posted=True, review_url=review_url)-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:- meta += f" · {category.replace('_', ' ')}"- return meta---def _suggestion_block(code: str) -> str:- """A GitHub suggestion block with a fence longer than any backtick run in the code.-- A run of three or more backticks in the code would otherwise close the block early, and GitHub would- offer only the code before it as the replacement.- """- longest_run = max((len(run) for run in re.findall(r"`+", code)), default=0)- fence = "`" * max(3, longest_run + 1)- return f"{fence}suggestion\n{code}\n{fence}"---def _format_issue_comment(- finding: ReviewIssueFinding, verdict: ValidationVerdict, *, with_suggestion_code: bool = False-) -> str:- """Format a finding + its verdict as an inline comment body: title, severity, issue, fix.+def _format_issue_comment(finding: ReviewIssueFinding, verdict: ValidationVerdict) -> str:+ """Format a finding + its verdict as an inline comment body: the P level and title, then the issue+ and its fix in one paragraph.+ The comment is plain text, so it reads the same in the PR and in email notifications.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+ reviews API returns it as `validator_note`. The heading must stay the first line, because theoutcome sweep (`find_finding_comment`) matches a finding to its comment by that line.- A single-agent finding has no suggestion text, and may carry replacement code instead, which- `with_suggestion_code` posts as a GitHub suggestion block up to `SUGGESTION_CODE_MAX_CHARS`.+ The finding's `suggestion_code` is not posted, because the readers apply the fix from the wording."""priority = effective_priority(finding.priority, verdict.adjusted_priority)- lines = [f"### {finding.title}", "", _finding_meta_line(priority, verdict.category), "", finding.body, ""]- if finding.suggestion.strip():- lines.extend(["**Suggested fix**", "", finding.suggestion, ""])- code = finding.suggestion_code- if with_suggestion_code and code is not None and len(code) <= SUGGESTION_CODE_MAX_CHARS:- lines.extend([_suggestion_block(code), ""])- # Hidden marker so the resolution stage recognizes this as one of ReviewHog's own threads.- lines.append(REVIEW_HOG_FINDING_MARKER)+ level = display_level(priority, finding.reported_priority)+ lines = [+ finding_heading(finding.title, level),+ "",+ finding_text(finding.body, finding.suggestion),+ "",+ # Hidden marker so the resolution stage recognizes this as one of ReviewHog's own threads.+ REVIEW_HOG_FINDING_MARKER,+ ]return "\n".join(lines)-def _covers_whole_range(finding: ReviewIssueFinding, start_line: int, end_line: int | None) -> bool:- """Whether the inline comment spans exactly the finding's single line range.-- GitHub applies a suggestion block to the commented lines, so replacement code written for the- finding's range is only safe to post when the comment covers that same range.- """- if len(finding.lines) != 1:- return False- line_range = finding.lines[0]- return start_line == line_range.start and (end_line or start_line) == (line_range.end or line_range.start)--def _build_inline_comments(valid_findings: list[tuple[ReviewIssueFinding, ValidationVerdict]],diff_lines: dict[str, set[int]],@@ -339,9 +306,7 @@ def _build_inline_comments(start_line, end_line = positioncomment = ReviewComment(path=finding.file,- body=_format_issue_comment(- finding, verdict, with_suggestion_code=_covers_whole_range(finding, start_line, end_line)- ),+ body=_format_issue_comment(finding, verdict),side="RIGHT",)diff --git a/products/review_hog/backend/reviewer/tools/single_agent_review.py b/products/review_hog/backend/reviewer/tools/single_agent_review.pyindex f56a6901f16f..157e5faa7d81 100644--- a/products/review_hog/backend/reviewer/tools/single_agent_review.py+++ b/products/review_hog/backend/reviewer/tools/single_agent_review.py@@ -24,7 +24,9 @@ from products.review_hog.backend.reviewer.constants import (FLASH_LENSES,FLASH_MUST_FIX_CAP_MULTIPLIER,FLASH_PROMPT_DIFF_MAX_CHARS,+ REPORTED_LEVELS,SINGLE_AGENT_SOURCE,+ STORED_PRIORITY_BY_REPORTED,flash_max_findings,priority_rank,)@@ -57,13 +59,6 @@ _LEADING_HTML_COMMENT = re.compile(r"\A\s*<!--.*?-->\s*", re.S)# runs, so only a value of this shape may reach it._COMMIT_SHA = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")-_STORED_PRIORITY = {- "P0": IssuePriority.MUST_FIX,- "P1": IssuePriority.MUST_FIX,- "P2": IssuePriority.SHOULD_FIX,- "P3": IssuePriority.CONSIDER,-}-def load_prompt_file(path: Path) -> str:"""A prompt file as the model receives it."""@@ -220,7 +215,7 @@ def issues_from_review(review: SingleAgentReview, *, pass_number: int, chunk_id:suggestion="",# A reversed range does not say which lines the suggestion replaces, so it would post on the wrong ones.suggestion_code=None if reversed_range else finding.suggestion_code or None,- priority=_STORED_PRIORITY[finding.priority],+ priority=STORED_PRIORITY_BY_REPORTED[finding.priority],reported_priority=finding.priority,is_directly_related_to_changes=True,source_perspective=source,@@ -242,21 +237,22 @@ class FlashSelection:dedup_fell_back: bool = False-# Most severe first. Storage folds P0 and P1 into `must_fix`, so the reported level ranks them apart.-_REPORTED_LEVELS: tuple[ReportedPriority, ...] = ("P0", "P1", "P2", "P3")--def _reported_level(issue: Issue) -> int:"""The reviewer's P level as a number that grows with severity, 0 for a finding without one."""reported = issue.reported_priority- return len(_REPORTED_LEVELS) - _REPORTED_LEVELS.index(reported) if reported is not None else 0+ return len(REPORTED_LEVELS) - REPORTED_LEVELS.index(reported) if reported is not None else 0+++def _level_priority(level: int) -> ReportedPriority | None:+ """The P level that `_reported_level` encodes as `level`, None for 0."""+ return REPORTED_LEVELS[len(REPORTED_LEVELS) - level] if level else Nonedef _flash_order(main: list[Issue], lens: list[Issue], group_levels: Mapping[str, int] | None = None) -> list[Issue]:"""Highest priority first, P0 before P1, then the main findings before the lens findings, then session order.`group_levels` gives a dedup survivor the highest P level of its duplicate group, so a survivor that- absorbed a P0 ranks as a P0 although its own `reported_priority` stays what its session reported.+ absorbed a P0 ranks as a P0 even when its `reported_priority` keeps its session's level."""levels = group_levels or {}return sorted(@@ -457,8 +453,10 @@ def _raise_survivors(kept: list[Issue], duplicates: list[Duplicate]) -> dict[strDedup keeps the most complete statement of a problem, not the most severe one, so a lens P1 thatrepeats a main P3 would otherwise post as the P3, or not at all once the cap cuts it.- Returns the highest P level of each survivor's duplicate group, for `_flash_order`. The survivor's- `reported_priority` keeps its own session's level, which the turn stats count.+ Returns the highest P level of each survivor's duplicate group, for `_flash_order`. A survivor whose+ duplicate reported a more severe level of the same stored priority, such as a P0 merged into a P1,+ takes that level, so its comment leads with it; the turn stats count both levels as must-fix.+ Across stored priorities the survivor keeps its session's level, which the turn stats count."""kept_by_id = {issue.id: issue for issue in kept}group_levels: dict[str, int] = {}@@ -477,6 +475,17 @@ def _raise_survivors(kept: list[Issue], duplicates: list[Duplicate]) -> dict[strduplicate.issue.id,)survivor.priority = duplicate.issue.priority+ for survivor_id, level in group_levels.items():+ survivor = kept_by_id[survivor_id]+ best = _level_priority(level)+ own = survivor.reported_priority+ if (+ best is not None+ and own is not None+ and level > _reported_level(survivor)+ and STORED_PRIORITY_BY_REPORTED[best] == STORED_PRIORITY_BY_REPORTED[own]+ ):+ survivor.reported_priority = bestreturn group_levels