: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): show the status comment as a plain step table (#114915)
Julian Bezfff6baab779a
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 583f7d12eebd..5cf8643acb3e 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -135,7 +135,7 @@ and `reviewer/progress.py::resolution_states` derives the run's state from artefresolving (delivered verdicts — `reply_posted` — counted against the queue, fresh activity), completed (a closing run note, author `RESOLUTION_RUN_NOTE_AUTHOR`), or died-partway (no note, stale).The PR-comment counters likewise count only threads whose GitHub writes landed (`delivered_outcomes`); judged-but-undelivered threads join the closing tally's "couldn't handle" count instead.The reviews API exposes it as the row's `resolution` field ("Resolving comments · 6/10" / "Resolution didn't finish · stopped at 6/10" in the scene),-the PR status comment carries a marker-delimited resolution section (`update_resolution_status_comment` — spliced into the review's comment, created on demand for standalone runs, failure-edited on the final attempt),+the PR status comment carries a "Resolve comments" row in its step table (`update_resolution_status_comment` — spliced into the review's comment, created on demand for standalone runs, failure-edited on the final attempt),with a patched workflow-level backstop (`fail_resolution_activity`, fired from `ResolvePRWorkflow`'s except) covering the deaths the activity handler can't see — prepare failures, timeouts, cancellation, worker death — by idling the report and writing the failed section from the persisted work-list,and each queued thread's opening comment gets a best-effort 👀 reaction (queue marker; never removed).The API's **busy-guard** (`temporal/client.py::workflow_running`, fail-open describe on the deterministic IDs) refuses a review request while the PR's `resolve-pr` runs and a standalone resolution while its review queue runs.@@ -455,7 +455,8 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /marker scans (`_review_already_posted` here, `_find_marker_comment` on the status comment) trust the markeronly in **app-bot** comments/reviews — on a public repo anyone can paste it, and a spoofed match wouldsuppress the publish or clobber a stranger's comment. On the publish path a live **status comment**- (`reviewer/status_comment.py`) is posted at kickoff, edited with stage progress, and rewritten with the+ (`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 theoutcome: the full found counts, what was published, and — when the urgency threshold held findings back —whose threshold it was (the author's / the requester's / the default, from `resolved_from`) plus a"View them in PostHog" deep link to the exact report (`/project/<team>/code-review?review=<report id>`,diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.pyindex 49a3a7bd49f5..8724419f7b77 100644--- a/products/review_hog/backend/api/reviews.py+++ b/products/review_hog/backend/api/reviews.py@@ -62,6 +62,7 @@ from products.review_hog.backend.reviewer.progress import (SnapshotStats,TurnMarker,TurnStats,+ finding_counts,in_progress_report_ids,latest_resolution_summaries,progress_payload,@@ -941,15 +942,7 @@ def _review_payload(latest_resolution: ResolutionSummary | None,) -> dict[str, Any]:"""The list-row payload for one report's turn at `run_index`; the detail endpoint layers findings on top."""- counts = dict.fromkeys(IssuePriority, 0)- dismissed = 0- for finding, verdict in pairs:- if verdict is None:- continue- if verdict.is_valid:- counts[effective_priority(finding.priority, verdict.adjusted_priority)] += 1- else:- dismissed += 1+ counts, dismissed = finding_counts(pairs)meta = snapshot.metareturn {"id": report.id,diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.pyindex da53af7367f4..4dae0ff0244c 100644--- a/products/review_hog/backend/reviewer/progress.py+++ b/products/review_hog/backend/reviewer/progress.py@@ -9,6 +9,7 @@ comment, so the two surfaces can never disagree.import loggingimport operator+from collections.abc import Sequencefrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom functools import reduce@@ -45,8 +46,9 @@ from products.review_hog.backend.reviewer.artefact_content import (RunOutcomeNote,ValidationVerdict,)-from products.review_hog.backend.reviewer.constants import BLIND_SPOT_PASS_NUMBER+from products.review_hog.backend.reviewer.constants import BLIND_SPOT_PASS_NUMBER, effective_priorityfrom products.review_hog.backend.reviewer.models.github_meta import PRMetadata+from products.review_hog.backend.reviewer.models.issues_review import IssuePriorityfrom products.review_hog.backend.reviewer.models.perspective_selection import ChunkPerspectiveSelectionfrom products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_SINGLE_AGENTfrom products.review_hog.backend.reviewer.skill_loader import (@@ -114,6 +116,22 @@ class TurnStats:has_turn_marker: bool = False+def finding_counts(+ pairs: Sequence[tuple[ReviewIssueFinding, ValidationVerdict | None]],+) -> tuple[dict[IssuePriority, int], int]:+ """Kept findings per effective priority, and the dismissed count. Unjudged findings count in neither."""+ counts = dict.fromkeys(IssuePriority, 0)+ dismissed = 0+ for finding, verdict in pairs:+ if verdict is None:+ continue+ if verdict.is_valid:+ counts[effective_priority(finding.priority, verdict.adjusted_priority)] += 1+ else:+ dismissed += 1+ return counts, dismissed++def _content_json() -> Cast:return Cast("content", JSONField())diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.pyindex b339c6871c80..e29f23103820 100644--- a/products/review_hog/backend/reviewer/status_comment.py+++ b/products/review_hog/backend/reviewer/status_comment.py@@ -8,7 +8,7 @@ everyone. Progress renders from the same derivation the reviews API uses (`reviethe PR comment and the UI can never disagree.The resolution stage shares the same comment (one ReviewHog voice per PR): its progress and closing-tally live in a marker-delimited section spliced in by `update_resolution_status_comment`, which+tally live in the table's "Resolve comments" row, spliced in by `update_resolution_status_comment`, whichalso creates the comment on demand for standalone resolution runs that never had a review.Every entry point here is best-effort by construction: a status comment must never fail, block, or@@ -17,7 +17,7 @@ retry a review, so all exceptions are swallowed after logging.import randomimport logging-from collections.abc import Sequence+from collections.abc import Collection, Sequencefrom dataclasses import fieldfrom datetime import timedeltafrom typing import Any@@ -28,25 +28,27 @@ from django.utils import timezonefrom posthog.dataclasses import frozenfrom posthog.models.integration import GitHubIntegration, Integration+from posthog.utils import pluralizefrom products.review_hog.backend.models import ReviewReport+from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdictfrom products.review_hog.backend.reviewer.constants import (ALREADY_RAISED_SHOWN,PRIORITIES_BY_URGENCY,PRIORITY_LABELS,REVIEW_MODE_FLASH,REVIEW_MODE_FULL,- effective_priority,finding_heading,published_priorities_for,)from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarkerfrom products.review_hog.backend.reviewer.models.issues_review import IssuePriorityfrom products.review_hog.backend.reviewer.models.thread_resolution import CommitHold-from products.review_hog.backend.reviewer.persistence import load_findings_bundle, load_valid_findings+from products.review_hog.backend.reviewer.persistence import load_findings_bundlefrom products.review_hog.backend.reviewer.progress import (SnapshotStats,TurnStats,+ finding_counts,progress_payload,snapshot_stats,turn_stats,@@ -67,20 +69,34 @@ logger = logging.getLogger(__name__)# collapses to at most one GitHub edit per interval instead of one per finished unit.STATUS_EDIT_MIN_INTERVAL = timedelta(seconds=60)-# Mirrors the frontend's `progressLabel` step mapping — the PR comment and the UI must tell the same-# story. Fetching folds into step 1 there too.-_STAGE_LABELS = {- "fetching": "Step 1/6 · Preparing the diff",- "chunking": "Step 1/6 · Splitting into chunks",- "selecting": "Step 2/6 · Picking perspectives",- "reviewing": "Step 3/6 · Running review passes",- "deduplicating": "Step 4/6 · Merging overlapping findings",- "validating": "Step 5/6 · Validating findings",- "finalizing": "Step 6/6 · Finalizing the review",- "single_agent_preparing": "Step 1/3 · Preparing the diff",- "single_agent_reviewing": "Step 2/3 · Reviewing the pull request",- "single_agent_finalizing": "Step 3/3 · Finalizing the review",+_MODE_NAMES = {REVIEW_MODE_FLASH: "Standard", REVIEW_MODE_FULL: "Deep"}++# The steps follow the frontend's `progressLabel`, so the PR comment and the UI tell the same story.+# Each `progress_payload` stage maps to the step it belongs to. Fetching folds into step 1 there too.+_PIPELINE_STEPS = (+ "Prepare the diff",+ "Pick perspectives",+ "Run review passes",+ "Merge overlapping findings",+ "Validate findings",+ "Publish",+)+_SINGLE_AGENT_STEPS = ("Prepare the diff", "Main review and lenses", "Merge and cap", "Publish")+_STEP_BY_STAGE = {+ "fetching": 0,+ "chunking": 0,+ "selecting": 1,+ "reviewing": 2,+ "deduplicating": 3,+ "validating": 4,+ "finalizing": 5,+ "single_agent_preparing": 0,+ "single_agent_reviewing": 1,+ "single_agent_finalizing": 3,}+_TABLE_HEADER = "| Step | Status | Result |"+_TABLE_DIVIDER = "|---|---|---|"+_RESOLVE_STEP = "Resolve comments"# The UI's urgency-threshold labels (`URGENCY_STOPS`), for the held-back explanation._THRESHOLD_LABELS = {@@ -99,8 +115,6 @@ _THRESHOLD_ATTRIBUTIONS = {"override": "the requester's","default": "the default",}-# Only personal thresholds live in someone's PostHog Review settings; the default variant has no page to point at.-_PERSONAL_THRESHOLD_SOURCES = frozenset({"author", "override"})# A clean review still posts a comment so silence never looks like a failed run._NO_ISSUES_MEDIA = (@@ -149,10 +163,8 @@ def status_marker(report_id: str) -> str:return f"<!-- reviewhog:status:{report_id} -->"-# Delimits the resolution stage's section within the status comment, so resolution updates splice-# their part in place without touching the review's own body above it.-RESOLUTION_SECTION_START = "<!-- reviewhog:resolution:start -->"-RESOLUTION_SECTION_END = "<!-- reviewhog:resolution:end -->"+_OLD_RESOLUTION_START = "<!-- reviewhog:resolution:start -->"+_OLD_RESOLUTION_END = "<!-- reviewhog:resolution:end -->"# GitHub-facing labels for the resolution stage's thread outcomes, in display order.# already_fixed and obsolete collapse into one bucket — the distinction matters in the DB, not to@@ -165,10 +177,15 @@ _RESOLUTION_OUTCOME_LABELS = {"escalate": "left for you",}_RESOLUTION_OUTCOME_ORDER = ("fixed", "declined", "already settled", "left for you")+_HOLD_REASONS = {+ CommitHold.STACKED: "a pull request is stacked on this branch",+ CommitHold.BRANCH_PROTECTED: "this branch is protected",+ CommitHold.MERGE_QUEUE: "this pull request was submitted to the merge queue",+}def report_deep_link(team_id: int, report_id: str) -> str:- """The app URL opening this report's review drawer — the held-back "View them in PostHog" target.+ """The app URL opening this report's review drawer — the held-back "view in PostHog" target.`?review=<report id>` is a permanent public contract (baked into GitHub comments that never getre-edited); the frontend's Code review URL sync accepts exactly this param, so the two must keep@@ -177,12 +194,58 @@ 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 (standard)" if review_mode == REVIEW_MODE_FLASH else "PostHog Review"+def _header(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}"+++def _table_row(step: str, status: str, result: str) -> str:+ return f"| {step} | {status} | {result} |"-def _plural(count: int, noun: str) -> str:- return f"{count} {noun}" if count == 1 else f"{count} {noun}s"+def _table(rows: Sequence[tuple[str, str, str]]) -> list[str]:+ return [_TABLE_HEADER, _TABLE_DIVIDER, *(_table_row(*row) for row in rows)]+++def _review_design(snapshot: SnapshotStats, fallback: str) -> str:+ # The fetch records the turn's design in the snapshot. Before that, the caller's design applies.+ return (snapshot.review_design if snapshot.head_matched else None) or fallback+++def _step_results(+ review_design: str,+ snapshot: SnapshotStats,+ turn: TurnStats,+ pairs: Sequence[tuple[ReviewIssueFinding, ValidationVerdict | None]],+) -> list[str]:+ """The Result cell of each step before Publish. A cell stays empty until its step has a number."""+ raw = None+ if turn.perspective_issue_count is not None or turn.blind_spot_issue_count is not None:+ raw = (turn.perspective_issue_count or 0) + (turn.blind_spot_issue_count or 0)+ counts, dismissed = finding_counts(pairs)+ kept = sum(counts.values())+ files = pluralize(snapshot.files_reviewed, "file") if snapshot.files_reviewed is not None else ""+ if review_design == REVIEW_DESIGN_SINGLE_AGENT:+ # The merge and cap step persists its dropped findings as dismissed, so the kept count is its output.+ return [files, pluralize(raw, "issue") if raw is not None else "", f"{raw} → {kept}" if raw is not None else ""]++ chunks = pluralize(turn.chunk_count, "chunk") if turn.chunk_count is not None else ""+ if turn.selection_chunks is not None:+ perspective_count: int | None = len({name for chunk in turn.selection_chunks for name in chunk.perspectives})+ else:+ perspective_count = turn.perspective_count+ passes = ""+ if turn.perspective_issue_count is not None or turn.blind_spot_issue_count is not None:+ passes = pluralize(turn.perspective_issue_count or 0, "issue")+ if turn.blind_spot_issue_count:+ passes += f" (+{turn.blind_spot_issue_count} blind-spot)"+ return [+ ", ".join(part for part in (files, chunks) if part),+ pluralize(perspective_count, "perspective") if perspective_count else "",+ passes,+ f"{raw} → {len(pairs)}" if raw is not None else "",+ f"{kept} kept, {dismissed} dismissed" if kept or dismissed else "",+ ]def render_in_progress_body(@@ -191,52 +254,67 @@ def render_in_progress_body(*,review_mode: str = REVIEW_MODE_FULL,review_design: str = REVIEW_DESIGN_PIPELINE,+ head_sha: str | None = None,+ snapshot: SnapshotStats | None = None,+ turn: TurnStats | None = None,+ pairs: Sequence[tuple[ReviewIssueFinding, ValidationVerdict | None]] = (),+ failed: bool = False,) -> str:- """The running-state body: the current step (mirroring the UI), plus a one-line explainer."""+ """The running or failed body: done steps with their results, the current step, and the rest."""single_agent = review_design == REVIEW_DESIGN_SINGLE_AGENT+ steps = _SINGLE_AGENT_STEPS if single_agent else _PIPELINE_STEPS+ results = [*_step_results(review_design, snapshot or SnapshotStats(), turn or TurnStats(), pairs), ""]# The kickoff body has no progress yet. A single-agent turn starts its sessions right after the# kickoff and the next refresh waits for the first session result, so the kickoff shows the# reviewing step instead of the preparing step.- kickoff_stage = "single_agent_reviewing" if single_agent else "fetching"- label = (- _STAGE_LABELS.get(progress["review_stage"], "Review in progress") if progress else _STAGE_LABELS[kickoff_stage]- )- explainer = (- "A main reviewer and two focused reviewers read the pull request in parallel. "- "The most important findings are published back to it."- if single_agent- else "Specialist review skills read the changed code in parallel each from their own perspective, a blind-spot sweep "- "catches what they missed, and only validated findings are published back to this pull request."- )- 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 "\n".join(- [- f"### \U0001f994 {_product_name(review_mode)} is reviewing this pull request",- "",- f"**{label}{counter}**",- "",- explainer,- "",- "<sub>This comment updates as the review progresses.</sub>",- "",- status_marker(report_id),- ]+ stage = progress["review_stage"] if progress else ("single_agent_reviewing" if single_agent else "fetching")+ current = _STEP_BY_STAGE.get(stage, 0)+ done, total = (progress.get("done"), progress.get("total")) if progress else (None, None)+ rows = []+ for index, step in enumerate(steps):+ if index < current:+ rows.append((step, "done", results[index]))+ elif index > current:+ rows.append((step, "skipped" if failed else "waiting", ""))+ elif failed:+ rows.append((step, "failed", ""))+ else:+ rows.append((step, f"{done}/{total}" if done is not None and total else "running", ""))+ if failed:+ verb = "couldn't finish reviewing"+ # A push starts only a Standard review. A Deep review runs only when someone asks for it.+ retry = (+ "It runs again on the next push to this pull request."+ if review_mode == REVIEW_MODE_FLASH+ else "Ask for a Deep review again to retry."+ )+ intro = [f'The review failed at "{steps[current]}". {retry}', ""]+ else:+ verb, intro = "reviewing", []+ return "\n".join([_header(review_mode, verb, head_sha), "", *intro, *_table(rows), "", status_marker(report_id)])+++def _priority_counts(counts: dict[IssuePriority, int], priorities: Collection[IssuePriority]) -> str:+ return ", ".join(+ f"{counts[priority]} {PRIORITY_LABELS[priority].capitalize()}"+ for priority in PRIORITIES_BY_URGENCY+ if priority in priorities and counts[priority])def render_final_body(report_id: str,*,- counts: dict[IssuePriority, int],- published_count: int,- held_back_count: int,threshold: IssuePriority,review_url: str | None,+ snapshot: SnapshotStats | None = None,+ turn: TurnStats | None = None,+ pairs: Sequence[tuple[ReviewIssueFinding, ValidationVerdict | None]] = (),+ head_sha: str | None = None,resolved_from: str = "author",report_url: str | None = None,review_mode: str = REVIEW_MODE_FULL,+ review_design: str = REVIEW_DESIGN_PIPELINE,celebrate_clean_reviews: bool = True,marker: ReviewHogMarker | None = None,capped_lens_parts: int | None = None,@@ -248,7 +326,7 @@ def render_final_body(The counts always show everything the run found, even when only a subset was published, sotwo inline comments on the PR never read as "the review only found two things". The held-back- sentence attributes the gating threshold to whoever it actually belonged to (`resolved_from`)+ note attributes the gating threshold to whoever it actually belonged to (`resolved_from`)and links to the report in PostHog (`report_url`, auth-gated) — the PR is otherwise the onlyplace the author hears about held-back findings, so the comment must not dead-end.`capped_lens_parts` is set when a single-agent turn reviewed a PR past the lens part cap. The@@ -256,46 +334,32 @@ def render_final_body(lists the findings a Full turn did not post because another reviewer's PR comment raises them, eachlinked to that comment under `pr_url`; `raised_elsewhere_count` counts all of them."""- found_total = sum(counts.values())- found_line = "Found " + ", ".join(- f"**{counts[priority]} {PRIORITY_LABELS[priority]}**" for priority in PRIORITIES_BY_URGENCY- )- lines = [f"### \U0001f994 {_product_name(review_mode)} reviewed this pull request", ""]- if found_total == 0 and raised_elsewhere:- lines.append("Nothing new to raise.")- # A flash turn is the quick pass, so a clean one gets a plain line instead of the celebration.- elif 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(- [- "Nothing worth raising this time. Enjoy the moment:",- "",- f"",- ]- )+ counts, _ = finding_counts(pairs)+ published = published_priorities_for(threshold)+ published_count = sum(count for priority, count in counts.items() if priority in published)+ held_back_count = sum(counts.values()) - published_count++ publish_parts = []+ if published_count:+ publish_parts.append(f"{published_count} posted" + (f" ([view review]({review_url}))" if review_url else ""))+ if held_back_count:+ # An unrecognized resolved_from reads as "author".+ attribution = _THRESHOLD_ATTRIBUTIONS.get(resolved_from, _THRESHOLD_ATTRIBUTIONS["author"])+ held = f'{held_back_count} held back by {attribution} "{_THRESHOLD_LABELS[threshold]}" threshold'+ publish_parts.append(held + (f" ([view in PostHog]({report_url}))" if report_url else ""))+ single_agent = review_design == REVIEW_DESIGN_SINGLE_AGENT+ steps = _SINGLE_AGENT_STEPS if single_agent else _PIPELINE_STEPS+ results = _step_results(review_design, snapshot or SnapshotStats(), turn or TurnStats(), pairs)+ results.append(" · ".join(publish_parts) or "Nothing to post")+ rows = [(step, "done", result) for step, result in zip(steps, results)]++ if published_count:+ summary = f"Posted {pluralize(published_count, 'finding')}: {_priority_counts(counts, published)}."+ elif held_back_count:+ summary = f"Found {pluralize(held_back_count, 'finding')}, all below the urgency threshold."else:- lines.append(found_line + ".")- lines.append("")- if published_count > 0:- published_line = f"Published {_plural(published_count, 'finding')}"- if review_url:- published_line += f" ([view the review]({review_url}))"- lines.append(published_line + ".")- if held_back_count > 0:- # An unrecognized resolved_from reads as "author" throughout (attribution AND suffix).- source = resolved_from if resolved_from in _THRESHOLD_ATTRIBUTIONS else "author"- sentence = (- f"{_plural(held_back_count, 'finding')} stayed below {_THRESHOLD_ATTRIBUTIONS[source]} "- f'"{_THRESHOLD_LABELS[threshold]}" urgency threshold'- )- if source in _PERSONAL_THRESHOLD_SOURCES:- sentence += " in their PostHog Review settings"- sentence += ", so they were not published."- if report_url:- sentence += f" [View them in PostHog]({report_url})."- lines.append(sentence)+ summary = "Nothing to post."+ lines = [_header(review_mode, "reviewed", head_sha), "", summary, "", *_table(rows)]if capped_lens_parts is not None:lines.extend([@@ -312,103 +376,75 @@ def render_final_body(hidden = max(raised_elsewhere_count, len(raised_elsewhere)) - len(shown)if hidden > 0:lines.append(f"- and {hidden} more")+ # A Standard turn is the quick pass, so a clean one gets no celebration.+ elif sum(counts.values()) == 0 and review_mode != REVIEW_MODE_FLASH and celebrate_clean_reviews:+ media_url, media_alt = random.choice(_NO_ISSUES_MEDIA)+ lines.extend(["", f""])lines.extend(["", status_marker(report_id)])if marker is not None:lines.append(marker.hidden_comment())return "\n".join(lines)-def render_resolution_progress_section(*, done: int, total: int, fixed: int, left_for_you: int) -> str:- """The resolving-state section: the run's counter plus the outcomes that matter mid-run."""- line = f"Resolving comments: {done}/{total}"- outcome_bits = [- bit for bit, count in ((f"{fixed} fixed", fixed), (f"{left_for_you} left for you", left_for_you)) if count- ]- if outcome_bits:- line += " · " + ", ".join(outcome_bits)- return "\n".join(- [- f"**{line}**",- "",- "<sub>Safe fixes are committed to the branch; every settled thread gets a reply. "- "This line updates as threads settle.</sub>",- ]- )+def _fixed_with_commits(fixed: int) -> str:+ return f"{fixed} fixed with {'a commit' if fixed == 1 else 'commits'} on your branch"+++def render_resolution_progress_row(*, done: int, total: int, fixed: int, left_for_you: int) -> str:+ """The resolving-state row: the run's counter plus the outcomes that matter mid-run."""+ bits = [_fixed_with_commits(fixed)] if fixed else []+ if left_for_you:+ bits.append(f"{left_for_you} left for you")+ return _table_row(_RESOLVE_STEP, f"{done}/{total}", ", ".join(bits))-def render_resolution_final_section(*, outcomes: dict[str, int], failed_turns: int) -> str:+def render_resolution_final_row(*, outcomes: dict[str, int], failed_turns: int) -> str:"""The run's closing tally, including the threads the run could not handle."""counts: dict[str, int] = {}for outcome, count in outcomes.items():label = _RESOLUTION_OUTCOME_LABELS.get(outcome, outcome)counts[label] = counts.get(label, 0) + count- bits = [f"{counts[label]} {label}" for label in _RESOLUTION_OUTCOME_ORDER if counts.get(label)]- line = "Resolved comments: " + (", ".join(bits) if bits else "no threads needed action")+ bits = [+ _fixed_with_commits(counts[label]) if label == "fixed" else f"{counts[label]} {label}"+ for label in _RESOLUTION_OUTCOME_ORDER+ if counts.get(label)+ ]if failed_turns:- line += f" · couldn't handle {failed_turns}"- return f"**{line}**"---def render_resolution_failed_section(*, done: int, total: int) -> str:- """The crashed-run section, so a dead resolution never reads as forever in progress on the PR."""- return "\n".join(- [- f"**Couldn't finish resolving comments: stopped at {done}/{total}**",- "",- "<sub>The remaining threads were not touched. The next review or resolution run picks them up.</sub>",- ]- )+ bits.append(f"couldn't handle {failed_turns}")+ return _table_row(_RESOLVE_STEP, "done", ", ".join(bits) or "No threads needed action")++def render_resolution_failed_row(*, done: int, total: int) -> str:+ """The crashed-run row, so a dead resolution never reads as forever in progress on the PR."""+ return _table_row(_RESOLVE_STEP, "failed", f"Stopped at {done}/{total}")-def render_resolution_held_section(hold: CommitHold, *, done: int = 0, total: int = 0) -> str:++def render_resolution_held_row(hold: CommitHold, *, done: int = 0, total: int = 0) -> str:"""Why the stage did not commit fixes, so the author knows the open threads are theirs.`total` is set only when the run stopped part way."""- if hold == CommitHold.STACKED:- line = (- f"Stopped resolving comments at {done}/{total}: another pull request is now stacked on this branch"- if total- else "Not resolving comments: other pull requests are stacked on this branch"- )- why = "A fix commit here would leave the stacked pull requests out of date"- elif hold == CommitHold.BRANCH_PROTECTED:- line = (- f"Stopped resolving comments at {done}/{total}: this branch is now protected"- if total- else "Not resolving comments: this branch is protected"- )- why = "A person decides what lands on a protected branch"- else:- line = (- f"Stopped resolving comments at {done}/{total}: this pull request was submitted to the merge queue"- if total- else "Not resolving comments: this pull request is submitted to the merge queue"- )- why = "A fix commit would change what was submitted, or remove it from the queue"- return "\n".join([f"**{line}**", "", f"<sub>{why}, so the open threads stay with you.</sub>"])---def _splice_resolution_section(body: str, section: str) -> str:- """Replace (or append) the marker-delimited resolution section within a comment body."""- block = f"{RESOLUTION_SECTION_START}\n{section}\n{RESOLUTION_SECTION_END}"- if RESOLUTION_SECTION_START in body and RESOLUTION_SECTION_END in body:- head, _, rest = body.partition(RESOLUTION_SECTION_START)- _, _, tail = rest.partition(RESOLUTION_SECTION_END)- return f"{head.rstrip()}\n\n{block}{tail}"- return f"{body.rstrip()}\n\n{block}" if body.strip() else block---def render_failed_body(report_id: str, *, review_mode: str = REVIEW_MODE_FULL) -> str:- return "\n".join(- [- 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.",- "",- status_marker(report_id),- ]- )+ reason = _HOLD_REASONS[hold]+ if total:+ return _table_row(_RESOLVE_STEP, "stopped", f"Stopped at {done}/{total} because {reason}")+ return _table_row(_RESOLVE_STEP, "skipped", f"Not run because {reason}")+++def _splice_resolution_row(body: str, row: str) -> str:+ """Replace the body's Resolve comments row, or add it after the last table row."""+ # Comments posted before the step table carry the resolution text between these markers.+ head, _, rest = body.partition(_OLD_RESOLUTION_START)+ body = head.rstrip() + rest.partition(_OLD_RESOLUTION_END)[2] if rest else body+ lines = body.split("\n")+ table_rows = [index for index, line in enumerate(lines) if line.startswith("| ")]+ for index in table_rows:+ if lines[index].startswith(f"| {_RESOLVE_STEP} |"):+ lines[index] = row+ return "\n".join(lines)+ if table_rows:+ lines.insert(table_rows[-1] + 1, row)+ return "\n".join(lines)+ return "\n".join([*lines, "", *_table([]), row])def _auth(team_id: int, repository: str) -> tuple[str, str | None] | None:@@ -523,7 +559,9 @@ def ensure_status_comment(token, installation_id = authowner, repo = _split_repository(report.repository)marker = status_marker(report_id)- body = render_in_progress_body(report_id, None, review_mode=review_mode, review_design=review_design)+ body = render_in_progress_body(+ report_id, None, review_mode=review_mode, review_design=review_design, head_sha=report.head_sha+ )comment_id = report.status_comment_idif comment_id is None:@@ -548,6 +586,41 @@ def ensure_status_comment(logger.exception("Could not post the ReviewHog status comment; the review continues without it")+@frozen+class _TurnState:+ """The turn's snapshot facts, pipeline shape, and (finding, verdict) pairs at the report's head."""++ snapshot: SnapshotStats+ turn: TurnStats+ pairs: list[tuple[ReviewIssueFinding, ValidationVerdict | None]]+++def _turn_state(team_id: int, report: ReviewReport, run_index: int) -> _TurnState:+ report_id = str(report.id)+ heads = {report_id: report.head_sha}+ return _TurnState(+ snapshot=snapshot_stats(team_id, heads).get(report_id, SnapshotStats()),+ turn=turn_stats(team_id, heads).get(report_id, TurnStats()),+ pairs=load_findings_bundle(team_id=team_id, report_ids=[report_id]).turn(report_id, run_index),+ )+++def _render_live_body(team_id: int, report: ReviewReport, review_mode: str, review_design: str, *, failed: bool) -> str:+ # The in-flight turn's findings live one run_index ahead of the completed watermark.+ state = _turn_state(team_id, report, report.run_count + 1)+ return render_in_progress_body(+ str(report.id),+ progress_payload(team_id, report, state.snapshot, state.turn, state.pairs),+ review_mode=review_mode,+ review_design=_review_design(state.snapshot, review_design),+ head_sha=report.head_sha,+ snapshot=state.snapshot,+ turn=state.turn,+ pairs=state.pairs,+ failed=failed,+ )++def maybe_refresh_status_comment(team_id: int,report_id: str,@@ -577,27 +650,13 @@ def maybe_refresh_status_comment(report = ReviewReport.objects.for_team(team_id).get(id=report_id)if report.status_comment_id is None or report.pr_number is None:return- heads = {report_id: report.head_sha}- snapshot = snapshot_stats(team_id, heads).get(report_id, SnapshotStats())- turn = turn_stats(team_id, heads).get(report_id, TurnStats())- # The in-flight turn's findings live one run_index ahead of the completed watermark.- current_pairs = load_findings_bundle(team_id=team_id, report_ids=[report_id]).turn(- report_id, report.run_count + 1- )- progress = progress_payload(team_id, report, snapshot, turn, current_pairs)auth = _auth(team_id, report.repository)if auth is None:returntoken, installation_id = authowner, repo = _split_repository(report.repository)- _patch_comment(- owner,- repo,- report.status_comment_id,- render_in_progress_body(report_id, progress, review_mode=review_mode, review_design=review_design),- token=token,- installation_id=installation_id,- )+ body = _render_live_body(team_id, report, review_mode, review_design, failed=False)+ _patch_comment(owner, repo, report.status_comment_id, body, token=token, installation_id=installation_id)except Exception:logger.exception("Could not refresh the ReviewHog status comment; the review continues without it")@@ -627,25 +686,19 @@ def finalize_status_comment(input: FinalizeStatusCommentInput) -> None:report = ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).first()if report is None or report.status_comment_id is None or report.pr_number is None:return- counts = dict.fromkeys(IssuePriority, 0)- for finding, verdict in load_valid_findings(- team_id=input.team_id, report_id=input.report_id, run_index=input.run_index- ):- counts[effective_priority(finding.priority, verdict.adjusted_priority)] += 1- threshold = IssuePriority(input.urgency_threshold)- published = published_priorities_for(threshold)- published_count = sum(count for priority, count in counts.items() if priority in published)- held_back_count = sum(count for priority, count in counts.items() if priority not in published)+ state = _turn_state(input.team_id, report, input.run_index)rendered = render_final_body(input.report_id,- counts=counts,- published_count=published_count,- held_back_count=held_back_count,- threshold=threshold,+ threshold=IssuePriority(input.urgency_threshold),review_url=input.review_url,+ snapshot=state.snapshot,+ turn=state.turn,+ pairs=state.pairs,+ head_sha=report.head_sha,resolved_from=input.resolved_from,report_url=report_deep_link(input.team_id, input.report_id),review_mode=input.review_mode,+ review_design=_review_design(state.snapshot, REVIEW_DESIGN_PIPELINE),celebrate_clean_reviews=input.celebrate_clean_reviews,marker=input.marker,capped_lens_parts=input.capped_lens_parts,@@ -668,19 +721,21 @@ def fail_status_comment(team_id: int, report_id: str, *, review_mode: str = REVIreport = ReviewReport.objects.for_team(team_id).filter(id=report_id).first()if report is None or report.status_comment_id is None or report.pr_number is None:return- _edit_and_stamp(team_id, report, render_failed_body(report_id, review_mode=review_mode))+ _edit_and_stamp(+ team_id, report, _render_live_body(team_id, report, review_mode, REVIEW_DESIGN_PIPELINE, failed=True)+ )except Exception:logger.exception("Could not mark the ReviewHog status comment as failed")def update_resolution_status_comment(- team_id: int, report_id: str, section: str, *, integration_row_id: int | None = None+ team_id: int, report_id: str, row: str, *, integration_row_id: int | None = None) -> None:- """Splice the resolution stage's section into the report's status comment.+ """Splice the resolution stage's table row into the report's status comment.Chained runs extend the review's existing comment (edits don't notify PR subscribers, and oneReviewHog voice per PR beats a second comment); standalone runs, where the PR never got a- review comment, create it on demand carrying just the resolution section. Best-effort like+ review comment, create it on demand carrying just the resolution row. Best-effort likeevery entry point here: a status edit must never fail or block a resolution run.A resolution run passes its pinned `integration_row_id` so the token is re-minted from that row@@ -718,7 +773,9 @@ def update_resolution_status_comment(# An empty existing body falls back to the marker just like a missing one: splicing into an# empty base drops the marker, and _find_marker_comment recovery relies on it surviving so a# lost status_comment_id can re-adopt the comment instead of posting a duplicate.- new_body = _splice_resolution_section(body if body else marker, section)+ new_body = _splice_resolution_row(body if body else marker, row)+ if new_body == body:+ returnif comment_id is not None:_patch_comment(owner, repo, comment_id, new_body, token=token, installation_id=installation_id)else:@@ -729,7 +786,7 @@ def update_resolution_status_comment(report.status_comment_edited_at = timezone.now()report.save(update_fields=["status_comment_id", "status_comment_edited_at", "updated_at"])except Exception:- logger.exception("Could not update the ReviewHog resolution status section; the run continues without it")+ logger.exception("Could not update the ReviewHog resolution status row; the run continues without it")def _edit_and_stamp(team_id: int, report: ReviewReport, body: str) -> None:diff --git a/products/review_hog/backend/temporal/resolution.py b/products/review_hog/backend/temporal/resolution.pyindex c4329ecb4f4f..77bd89df948a 100644--- a/products/review_hog/backend/temporal/resolution.py+++ b/products/review_hog/backend/temporal/resolution.py@@ -73,10 +73,10 @@ from products.review_hog.backend.reviewer.sandbox.executor import ()from products.review_hog.backend.reviewer.skill_loader import load_resolution_skill_for_runfrom products.review_hog.backend.reviewer.status_comment import (- render_resolution_failed_section,- render_resolution_final_section,- render_resolution_held_section,- render_resolution_progress_section,+ render_resolution_failed_row,+ render_resolution_final_row,+ render_resolution_held_row,+ render_resolution_progress_row,update_resolution_status_comment,)from products.review_hog.backend.reviewer.tools.github_client import github_api_request@@ -389,7 +389,7 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResuupdate_resolution_status_comment(input.team_id,report_id,- render_resolution_held_section(hold),+ render_resolution_held_row(hold),integration_row_id=github.integration.id,)triage, overflow = [], 0@@ -767,7 +767,7 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunRawait database_sync_to_async(update_resolution_status_comment, thread_sensitive=False)(input.team_id,prepared.report_id,- render_resolution_progress_section(+ render_resolution_progress_row(done=sum(result.delivered_outcomes.values()),total=total_queued,fixed=result.delivered_outcomes.get(ThreadOutcome.FIXED.value, 0),@@ -908,7 +908,7 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunRawait database_sync_to_async(update_resolution_status_comment, thread_sensitive=False)(input.team_id,prepared.report_id,- render_resolution_failed_section(done=sum(result.delivered_outcomes.values()), total=total_queued),+ render_resolution_failed_row(done=sum(result.delivered_outcomes.values()), total=total_queued),integration_row_id=prepared.integration_row_id,)raise@@ -925,13 +925,13 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunRawait database_sync_to_async(update_resolution_status_comment, thread_sensitive=False)(input.team_id,prepared.report_id,- render_resolution_held_section(+ render_resolution_held_row(result.stopped_reason, done=sum(result.delivered_outcomes.values()), total=total_queued)if result.stopped_reason# Undelivered threads (judged, or redelivered, without their GitHub writes landing) join# the couldn't-handle count: the tally must not claim an outcome the thread can't show.- else render_resolution_final_section(+ else render_resolution_final_row(outcomes=result.delivered_outcomes, failed_turns=result.failed_turns + result.undelivered),integration_row_id=prepared.integration_row_id,@@ -985,7 +985,7 @@ def _fail_resolution(input: FailResolutionInput) -> None:update_resolution_status_comment(input.team_id,str(report.id),- render_resolution_failed_section(done=state.done, total=state.total),+ render_resolution_failed_row(done=state.done, total=state.total),)diff --git a/products/review_hog/backend/tests/test_resolution_activity.py b/products/review_hog/backend/tests/test_resolution_activity.pyindex 1ed72ea2a6d9..c52586d20513 100644--- a/products/review_hog/backend/tests/test_resolution_activity.py+++ b/products/review_hog/backend/tests/test_resolution_activity.py@@ -465,7 +465,7 @@ class TestResolutionPersistenceAndDelivery(BaseTest):_fail_resolution(FailResolutionInput(team_id=self.team.id, owner="posthog", repo="posthog", pr_number=123))assert ReviewReport.objects.for_team(self.team.id).get(id=report.id).status == ReviewReport.Status.IDLE- assert "stopped at 1/3" in status_comment.call_args.args[2]+ assert "Stopped at 1/3" in status_comment.call_args.args[2]# Crash before prepare queued anything: no run anchor, so no section to replace.report.pr_number = 124@@ -794,7 +794,7 @@ class TestFailedRunActivity(NonAtomicBaseTest):"pr_in_merge_queue","submitted to the merge queue",),- ("stacked", None, True, "pr_has_stacked_pull_requests", "now stacked on this branch"),+ ("stacked", None, True, "pr_has_stacked_pull_requests", "stacked on this branch"),])def test_hold_appearing_mid_run_stops_the_session_before_the_next_turn(@@ -826,7 +826,7 @@ class TestFailedRunActivity(NonAtomicBaseTest):continue_turn.assert_not_called()assert result.triaged == 1assert result.stopped_reason == reason- assert "Stopped resolving comments at 1/2" in status_comment.call_args.args[2]+ assert "| stopped | Stopped at 1/2 because" in status_comment.call_args.args[2]assert section_text in status_comment.call_args.args[2]assert self._report_status() == ReviewReport.Status.IDLEdiff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.pyindex 2fe354102ebc..b8b482c0165b 100644--- a/products/review_hog/backend/tests/test_status_comment.py+++ b/products/review_hog/backend/tests/test_status_comment.py@@ -1,3 +1,4 @@+from collections.abc import Callablefrom datetime import timedeltafrom typing import Any@@ -9,27 +10,29 @@ from django.utils import timezonefrom parameterized import parameterizedfrom products.review_hog.backend.models import ReviewReport+from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdictfrom products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULLfrom products.review_hog.backend.reviewer.fingerprint import ReviewHogMarkerfrom products.review_hog.backend.reviewer.models.github_meta import PRMetadatafrom products.review_hog.backend.reviewer.models.issue_validation import IssueValidationfrom products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRange+from products.review_hog.backend.reviewer.models.perspective_selection import ChunkPerspectiveSelection+from products.review_hog.backend.reviewer.models.thread_resolution import CommitHoldfrom products.review_hog.backend.reviewer.persistence import persist_findings, persist_verdict, upsert_review_report-from products.review_hog.backend.reviewer.progress import run_outcome_markers-from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT+from products.review_hog.backend.reviewer.progress import SnapshotStats, TurnStats, run_outcome_markers+from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_SINGLE_AGENTfrom products.review_hog.backend.reviewer.status_comment import (- RESOLUTION_SECTION_START,FinalizeStatusCommentInput,- _splice_resolution_section,+ _splice_resolution_row,ensure_status_comment,fail_status_comment,finalize_status_comment,maybe_refresh_status_comment,- render_failed_body,render_final_body,render_in_progress_body,- render_resolution_final_section,- render_resolution_progress_section,+ render_resolution_final_row,+ render_resolution_held_row,+ render_resolution_progress_row,status_marker,update_resolution_status_comment,)@@ -42,171 +45,137 @@ _PAGINATED = f"{_MODULE}.github_api_get_paginated"_INTEGRATION = f"{_MODULE}.GitHubIntegration"-_STAGE_LINE_CASES: list[tuple[dict[str, Any] | None, str]] = [- (None, "Step 1/6 · Preparing the diff"),- ({"review_stage": "chunking", "done": None, "total": None}, "Step 1/6 · Splitting into chunks"),- ({"review_stage": "reviewing", "done": 7, "total": 18}, "Step 3/6 · Running review passes · 7/18"),- ({"review_stage": "validating", "done": 2, "total": None}, "Step 5/6 · Validating findings"),-]+def _pair(n: int, priority: IssuePriority, *, is_valid: bool = True) -> tuple[ReviewIssueFinding, ValidationVerdict]:+ key = f"r1:a.py:{n}"+ finding = ReviewIssueFinding(+ issue_key=key, run_index=1, title="t", file="a.py", body="b", suggestion="s", priority=priority+ )+ return finding, ValidationVerdict(issue_key=key, is_valid=is_valid, argumentation="a")+-_SINGLE_AGENT_STAGE_LINE_CASES: list[tuple[dict[str, Any] | None, str]] = [- (None, "Step 2/3 · Reviewing the pull request"),- ({"review_stage": "single_agent_finalizing", "done": None, "total": None}, "Step 3/3 · Finalizing the review"),+_PAIRS = [+ _pair(1, IssuePriority.MUST_FIX),+ _pair(2, IssuePriority.CONSIDER),+ _pair(3, IssuePriority.SHOULD_FIX, is_valid=False),]+_SELECTION = [ChunkPerspectiveSelection(chunk_id=1, perspectives=["a", "b", "c"], reason="r")]+_DEEP: dict[str, Any] = {+ "snapshot": SnapshotStats(files_reviewed=14),+ "turn": TurnStats(chunk_count=3, perspective_issue_count=14, blind_spot_issue_count=2, selection_chunks=_SELECTION),+ "head_sha": "b81c2e1ffff",+}+_STANDARD: dict[str, Any] = {"review_mode": REVIEW_MODE_FLASH, "review_design": REVIEW_DESIGN_SINGLE_AGENT}-class TestRenderInProgressBody:- @parameterized.expand(- [(progress, line, REVIEW_DESIGN_PIPELINE) for progress, line in _STAGE_LINE_CASES]- + [(progress, line, REVIEW_DESIGN_SINGLE_AGENT) for progress, line in _SINGLE_AGENT_STAGE_LINE_CASES]- )- def test_renders_the_stage_line_and_marker(- self, progress: dict[str, Any] | None, expected_line: str, review_design: str- ) -> None:- body = render_in_progress_body("rid", progress, review_design=review_design)- assert f"**{expected_line}**" in body- assert status_marker("rid") in body # the marker is what makes edit-in-place reuse possible+def _running(stage: str | None, done: int | None = None, total: int | None = None, **kwargs: Any) -> str:+ progress = {"review_stage": stage, "done": done, "total": total} if stage else None+ return render_in_progress_body("rid", progress, **kwargs)-class TestFlashHeader:- @parameterized.expand(- [- ("in_progress", lambda mode: render_in_progress_body("rid", None, review_mode=mode)),- (- "final",- lambda mode: render_final_body(- "rid",- counts=dict.fromkeys(IssuePriority, 0),- published_count=0,- held_back_count=0,- threshold=IssuePriority.CONSIDER,- review_url=None,- review_mode=mode,- ),- ),- ("failed", lambda mode: render_failed_body("rid", review_mode=mode)),- ]- )- 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.- flash, full = render(REVIEW_MODE_FLASH), render(REVIEW_MODE_FULL)- assert flash.startswith("### \U0001f994 PostHog Review (standard) ")- assert full.startswith("### \U0001f994 PostHog Review ")- assert "(standard)" not in full- assert "FLASH MODE" not in flash + full+def _done(threshold: IssuePriority = IssuePriority.SHOULD_FIX, **kwargs: Any) -> str:+ return render_final_body("rid", threshold=threshold, review_url="https://g/review", **kwargs)-class TestRenderFinalBody:- @parameterized.expand(+_BODY_CASES: list[tuple[str, Callable[[], str], list[str]]] = [+ (+ "deep_running",+ lambda: _running("reviewing", 7, 9, **_DEEP),[- # All published: full counts + the review link, no held-back line.- (- {IssuePriority.MUST_FIX: 1, IssuePriority.SHOULD_FIX: 2, IssuePriority.CONSIDER: 5},- 8,- 0,- IssuePriority.CONSIDER,- "https://g/review",- [- "Found **1 must fix**, **2 should fix**, **5 consider**",- "Published 8 findings ([view the review](https://g/review))",- ],- ["stayed below"],- ),- # The key case: some findings held back — the comment must still show everything found.- (- {IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 2, IssuePriority.CONSIDER: 5},- 2,- 5,- IssuePriority.SHOULD_FIX,- "https://g/review",- [- "Found **0 must fix**, **2 should fix**, **5 consider**",- "Published 2 findings",- '5 findings stayed below the author\'s "Should fix" urgency threshold',- ],- [],- ),- # Zero publishable: explicit closure instead of silence, no "Published" line.- (- {IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 0, IssuePriority.CONSIDER: 5},- 0,- 5,- IssuePriority.SHOULD_FIX,- None,- ["Found **0 must fix**, **0 should fix**, **5 consider**", "5 findings stayed below"],- ["Published"],- ),- # Nothing found at all.- (- {IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 0, IssuePriority.CONSIDER: 0},- 0,- 0,- IssuePriority.SHOULD_FIX,- None,- ["Nothing worth raising this time. Enjoy the moment:", "!["],- ["Published", "stayed below"],- ),- # Posted on a prior crashed attempt (marker skip): published, but no link to render.- (- {IssuePriority.MUST_FIX: 1, IssuePriority.SHOULD_FIX: 0, IssuePriority.CONSIDER: 0},- 1,- 0,- IssuePriority.SHOULD_FIX,- None,- ["Published 1 finding."],- ["view the review"],- ),- ]- )- def test_shows_full_counts_and_the_published_vs_held_back_split(- self, counts, published_count, held_back_count, threshold, review_url, expected, absent- ) -> None:- body = render_final_body(- "rid",- counts=counts,- published_count=published_count,- held_back_count=held_back_count,- threshold=threshold,- review_url=review_url,- )+ "### PostHog Review · Deep · reviewing `b81c2e1`",+ "| Prepare the diff | done | 14 files, 3 chunks |\n| Pick perspectives | done | 3 perspectives |",+ "| Run review passes | 7/9 | |",+ "| Publish | waiting | |",+ ],+ ),+ (+ "deep_failed",+ lambda: _running("validating", 1, 3, pairs=_PAIRS, failed=True, **_DEEP),+ [+ "### PostHog Review · Deep · couldn't finish reviewing `b81c2e1`",+ 'The review failed at "Validate findings". Ask for a Deep review again to retry.',+ "| Merge overlapping findings | done | 16 → 3 |\n| Validate findings | failed | |\n| Publish | skipped | |",+ ],+ ),+ # The kickoff body has no progress, and a single-agent turn starts its sessions right after it.+ (+ "standard_kickoff",+ lambda: _running(None, **_STANDARD),+ ["Standard · reviewing this pull request", "| Main review and lenses | running | |"],+ ),+ (+ "standard_failed",+ lambda: _running("single_agent_reviewing", failed=True, **_STANDARD),+ ["It runs again on the next push to this pull request.", "| Main review and lenses | failed | |"],+ ),+ (+ "deep_done",+ lambda: _done(pairs=_PAIRS, report_url="https://ph.test/r", **_DEEP),+ [+ "### PostHog Review · Deep · reviewed `b81c2e1`\n\nPosted 1 finding: 1 Must fix.",+ "| Run review passes | done | 14 issues (+2 blind-spot) |",+ "| Validate findings | done | 2 kept, 1 dismissed |",+ # The full found count stays visible even when the threshold holds some findings back.+ '| Publish | done | 1 posted ([view review](https://g/review)) · 1 held back by the author\'s "Should fix" threshold ([view in PostHog](https://ph.test/r)) |',+ ],+ ),+ # With no perspective selected for any chunk, only the blind-spot sweep reports issues.+ (+ "deep_done_blind_spot_only",+ lambda: _done(pairs=_PAIRS, **{**_DEEP, "turn": TurnStats(blind_spot_issue_count=2)}),+ ["| Run review passes | done | 0 issues (+2 blind-spot) |"],+ ),+ (+ "standard_done",+ lambda: _done(IssuePriority.CONSIDER, turn=TurnStats(perspective_issue_count=9), pairs=_PAIRS, **_STANDARD),+ [+ "Posted 2 findings: 1 Must fix, 1 Consider.",+ "| Main review and lenses | done | 9 issues |\n| Merge and cap | done | 9 → 2 |",+ ],+ ),+ ("standard_clean", lambda: _done(**_STANDARD), ["Nothing to post.", "| Publish | done | Nothing to post |"]),+]+++class TestRenderBodies:+ @parameterized.expand(_BODY_CASES)+ def test_renders_the_step_table(self, _name: str, render: Callable[[], str], expected: list[str]) -> None:+ body = render()for fragment in expected:assert fragment in body, f"missing {fragment!r} in:\n{body}"- for fragment in absent:- assert fragment not in body, f"unexpected {fragment!r} in:\n{body}"- assert status_marker("rid") in body+ assert status_marker("rid") in body # the marker is what makes edit-in-place reuse possible+ assert all(ord(char) < 0x2600 for char in body), "the status comment carries no emoji"++class TestRenderFinalBody:@parameterized.expand([# Whose settings gated the run must be named truthfully: blaming "the author's" settings# for a requester-gated run is the exact misattribution this wording exists to fix, and# the defensive default variant has no settings page to point at.- ("author", 'the author\'s "Should fix" urgency threshold in their PostHog Review settings'),- ("override", 'the requester\'s "Should fix" urgency threshold in their PostHog Review settings'),- ("default", 'the default "Should fix" urgency threshold,'),+ ("author", 'the author\'s "Should fix" threshold'),+ ("override", 'the requester\'s "Should fix" threshold'),+ ("default", 'the default "Should fix" threshold'),# An unknown future value must degrade to the author wording, not crash the comment.- ("mystery", 'the author\'s "Should fix" urgency threshold in their PostHog Review settings'),+ ("mystery", 'the author\'s "Should fix" threshold'),])def test_held_back_sentence_attributes_the_gating_threshold(self, resolved_from: str, expected: str) -> None:body = render_final_body("rid",- counts={IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 0, IssuePriority.CONSIDER: 2},- published_count=0,- held_back_count=2,+ pairs=[_pair(1, IssuePriority.CONSIDER), _pair(2, IssuePriority.CONSIDER)],threshold=IssuePriority.SHOULD_FIX,review_url=None,resolved_from=resolved_from,report_url="https://ph.test/project/1/code-review?review=rid",marker=ReviewHogMarker(version="reviewhog-flash-9-9", fingerprint="abc1234"),)- assert f"2 findings stayed below {expected}" in body, body+ assert f"2 held back by {expected}" in body, body# The version rides in a hidden HTML comment, so it adds no visible text to the PR.hidden = "<!-- reviewhog-version: reviewhog-flash-9-9 abc1234 -->"assert hidden in bodyassert "reviewhog-flash" not in body.replace(hidden, "")# 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+ assert "([view in PostHog](https://ph.test/project/1/code-review?review=rid))" in body@parameterized.expand([@@ -222,9 +191,6 @@ class TestRenderFinalBody:) -> None:body = render_final_body("rid",- counts={IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 0, IssuePriority.CONSIDER: 0},- published_count=0,- held_back_count=0,threshold=IssuePriority.SHOULD_FIX,review_url=None,review_mode=review_mode,@@ -236,10 +202,7 @@ class TestRenderFinalBody:mock_choice.assert_called_once()else:assert "dog.png" not in body- assert "Enjoy the moment" not in bodymock_choice.assert_not_called()- if review_mode == REVIEW_MODE_FLASH:- assert "Nothing worth raising." in body@parameterized.expand([@@ -254,9 +217,7 @@ class TestRenderFinalBody:) -> None:body = render_final_body("rid",- counts={IssuePriority.MUST_FIX: must_fix, IssuePriority.SHOULD_FIX: 0, IssuePriority.CONSIDER: 0},- published_count=must_fix,- held_back_count=0,+ pairs=[_pair(n, IssuePriority.MUST_FIX) for n in range(must_fix)],threshold=IssuePriority.SHOULD_FIX,review_url=None,review_mode=REVIEW_MODE_FLASH,@@ -266,7 +227,7 @@ class TestRenderFinalBody:note = "This pull request is large, so the review ran in 4 parts with less depth than usual."assert (note in body) is expect_note- @parameterized.expand([("clean_turn", 0, "Nothing new to raise."), ("turn_with_findings", 1, "Found ")])+ @parameterized.expand([("clean_turn", 0, "Nothing to post."), ("turn_with_findings", 1, "Posted 1 finding")])def test_full_lists_what_other_comments_already_raise(self, _name: str, must_fix: int, opening: str) -> None:raised = [AlreadyRaised(title=f"Problem {n}", level="P2", comment_id=100 + n, commenter="greptile-apps[bot]")@@ -275,9 +236,7 @@ class TestRenderFinalBody:body = render_final_body("rid",- counts={IssuePriority.MUST_FIX: must_fix, IssuePriority.SHOULD_FIX: 0, IssuePriority.CONSIDER: 0},- published_count=must_fix,- held_back_count=0,+ pairs=[_pair(n, IssuePriority.MUST_FIX) for n in range(must_fix)],threshold=IssuePriority.SHOULD_FIX,review_url=None,raised_elsewhere=raised[:10],@@ -287,7 +246,7 @@ class TestRenderFinalBody:# A Full turn that only repeated other reviewers must say so instead of celebrating a clean PR.assert opening in body- assert "Enjoy the moment" not in body+ assert "![" not in bodyassert ("- **P2 · Problem 0**, raised by `greptile-apps[bot]` ([comment](https://github.com/o/r/pull/7#discussion_r100))"in body@@ -349,7 +308,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("### \U0001f994 PostHog Review (standard) ")+ assert mock_request.call_args.kwargs["json"]["body"].startswith("### PostHog Review · Standard · reviewing ")report.refresh_from_db()assert report.status_comment_id == 777assert report.status_comment_edited_at is not None@@ -493,12 +452,13 @@ class TestFinalizeStatusComment(BaseTest):assert _patches(mock_request) == ["/repos/o/r/issues/comments/555"]body = mock_request.call_args.kwargs["json"]["body"]- assert "Found **1 must fix**, **0 should fix**, **2 consider**" in body+ assert "Posted 1 finding: 1 Must fix." in body# Titles in the already-raised list are model text, so a token quoted from sandbox output must not post.assert leaked not in bodyassert "**P1 · Token [redacted] leaks**" in body- assert "Published 1 finding ([view the review](https://g/review))" in body- assert '2 findings stayed below the author\'s "Should fix" urgency threshold' in body+ assert (+ '1 posted ([view review](https://g/review)) · 2 held back by the author\'s "Should fix" threshold' in body+ )# The held-back link into the app. `?review=<report id>` is a permanent public contract# (baked into GitHub comments) — the frontend's URL sync accepts exactly this param.assert f"/project/{self.team.id}/code-review?review={report_id})" in body@@ -517,42 +477,73 @@ class TestFinalizeStatusComment(BaseTest):assert _patches(mock_request) == ["/repos/o/r/issues/comments/555"]body = mock_request.call_args.kwargs["json"]["body"]- 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("### \U0001f994 PostHog Review (standard) ")+ # leave a dead Standard run reading as a Deep one.+ assert body.startswith("### PostHog Review · Standard · couldn't finish reviewing ")-class TestResolutionSection:- def test_splice_appends_then_replaces_in_place(self) -> None:- # The section is edited into the shared status comment on every settled thread; a broken- # splice would either stack one section per update or eat the review's own body above it.- review_body = "### review outcome\n\nFound things.\n\n" + status_marker("rid")- first = _splice_resolution_section(- review_body, render_resolution_progress_section(done=0, total=3, fixed=0, left_for_you=0)- )- assert "### review outcome" in first- assert "Resolving comments: 0/3" in first+_DONE_BODY = f"### reviewed\n\n| Step | Status | Result |\n|---|---|---|\n| Publish | done | 1 posted |\n\n{status_marker('rid')}"+_OLD_BODY = (+ f"### reviewed\n\n{status_marker('rid')}\n\n"+ "<!-- reviewhog:resolution:start -->\n**Resolving comments: 0/3**\n<!-- reviewhog:resolution:end -->"+)- second = _splice_resolution_section(- first, render_resolution_progress_section(done=2, total=3, fixed=1, left_for_you=1)- )- assert "### review outcome" in second- assert status_marker("rid") in second- assert second.count(RESOLUTION_SECTION_START) == 1- assert "Resolving comments: 2/3 · 1 fixed, 1 left for you" in second- assert "0/3" not in second+class TestResolutionRow:+ @parameterized.expand(+ [+ (+ "running",+ _DONE_BODY,+ [render_resolution_progress_row(done=2, total=5, fixed=1, left_for_you=0)],+ "| Publish | done | 1 posted |\n| Resolve comments | 2/5 | 1 fixed with a commit on your branch |",+ ),+ (+ # Every settled thread rewrites the row, so a broken splice would stack one row per update.+ "done_replaces_running",+ _DONE_BODY,+ [+ render_resolution_progress_row(done=2, total=3, fixed=1, left_for_you=0),+ render_resolution_final_row(outcomes={"fixed": 2, "escalate": 1}, failed_turns=0),+ ],+ "| Resolve comments | done | 2 fixed with commits on your branch, 1 left for you |",+ ),+ (+ "held",+ _DONE_BODY,+ [render_resolution_held_row(CommitHold.BRANCH_PROTECTED)],+ "| Resolve comments | skipped | Not run because this branch is protected |",+ ),+ (+ # A comment posted before the step table must not keep its stale resolution text.+ "old_marker_block",+ _OLD_BODY,+ [render_resolution_progress_row(done=1, total=3, fixed=0, left_for_you=0)],+ "| Step | Status | Result |\n|---|---|---|\n| Resolve comments | 1/3 | |",+ ),+ ]+ )+ def test_splices_one_resolve_row_into_the_table(+ self, _name: str, body: str, rows: list[str], expected: str+ ) -> None:+ for row in rows:+ body = _splice_resolution_row(body, row)++ assert expected in body, body+ assert body.count("| Resolve comments |") == 1+ assert "### reviewed" in body+ assert status_marker("rid") in body+ assert "Resolving comments:" not in body- def test_final_section_buckets_outcomes_and_names_failures(self) -> None:+ def test_final_row_buckets_outcomes_and_names_failures(self) -> None:# The closing tally is the PR author's durable record: already_fixed and obsolete collapse# into one bucket, and threads the run could not handle must be named, never silent.- section = render_resolution_final_section(+ row = render_resolution_final_row(outcomes={"fixed": 2, "wont_fix": 1, "already_fixed": 1, "obsolete": 1, "escalate": 1},failed_turns=2,)- assert "Resolved comments: 2 fixed, 1 declined, 2 already settled, 1 left for you" in section- assert "couldn't handle 2" in section+ assert "2 fixed with commits on your branch, 1 declined, 2 already settled, 1 left for you" in row+ assert "couldn't handle 2" in row@patch(_INTEGRATION)@@ -574,12 +565,12 @@ class TestUpdateResolutionStatusComment(BaseTest):report = self._report()update_resolution_status_comment(- self.team.id, str(report.id), render_resolution_progress_section(done=0, total=3, fixed=0, left_for_you=0)+ self.team.id, str(report.id), render_resolution_progress_row(done=0, total=3, fixed=0, left_for_you=0))assert _posts(mock_request) == ["/repos/o/r/issues/123/comments"]posted = next(c for c in mock_request.call_args_list if c.args[0] == "POST")- assert "Resolving comments: 0/3" in posted.kwargs["json"]["body"]+ assert "| Resolve comments | 0/3 | |" in posted.kwargs["json"]["body"]assert status_marker(str(report.id)) in posted.kwargs["json"]["body"]report.refresh_from_db()assert report.status_comment_id == 888@@ -598,14 +589,14 @@ class TestUpdateResolutionStatusComment(BaseTest):mock_request.side_effect = [get_response, MagicMock()]update_resolution_status_comment(- self.team.id, str(report.id), render_resolution_progress_section(done=1, total=3, fixed=1, left_for_you=0)+ self.team.id, str(report.id), render_resolution_progress_row(done=1, total=3, fixed=1, left_for_you=0))assert _posts(mock_request) == []assert _patches(mock_request) == ["/repos/o/r/issues/comments/777"]patched = mock_request.call_args_list[1].kwargs["json"]["body"]assert "### reviewed" in patched- assert "Resolving comments: 1/3 · 1 fixed" in patched+ assert "| Resolve comments | 1/3 | 1 fixed with a commit on your branch |" in patcheddef test_empty_existing_body_keeps_the_marker_for_recovery(self, mock_request: MagicMock, mock_paginated: MagicMock, mock_integration: MagicMock@@ -622,7 +613,7 @@ class TestUpdateResolutionStatusComment(BaseTest):mock_request.side_effect = [get_response, MagicMock()]update_resolution_status_comment(- self.team.id, str(report.id), render_resolution_progress_section(done=1, total=3, fixed=1, left_for_you=0)+ self.team.id, str(report.id), render_resolution_progress_row(done=1, total=3, fixed=1, left_for_you=0))assert _patches(mock_request) == ["/repos/o/r/issues/comments/777"]@@ -652,7 +643,7 @@ class TestUpdateResolutionStatusComment(BaseTest):update_resolution_status_comment(self.team.id,str(report.id),- render_resolution_progress_section(done=1, total=3, fixed=1, left_for_you=0),+ render_resolution_progress_row(done=1, total=3, fixed=1, left_for_you=0),integration_row_id=42,)