: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): make the resolution stage visible and guard the review cycle (#82626)
Alex Lebedevd93c32769b5a
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex b603e3ab338f..7923c0e4d54e 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -88,6 +88,18 @@ the PR author's resolution criteria (canonical for unmapped authors). Design + dStage 7; vocabulary: CONTEXT.md; the live-e2e qualification plan (the resolver fixes its own PR):`eval/experiments/2026-07-resolution-e2e/PLAN.md`.+**Resolution visibility & the busy-guard** (grilled 2026-08-13, DECISIONS.md "Resolution-stage visibility & cycle guard"; ADR `adr/0001`):+a run opens with a `resolution_run` work-list artefact (queued thread ids + counts) written by `_prepare_run`,+and `reviewer/progress.py::resolution_states` derives the run's state from artefacts alone —+resolving (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),+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 **busy-guard** (`temporal/client.py::workflow_running`, fail-open describe on the deterministic ids) refuses a review start while the PR's `resolve-pr` runs and a standalone resolution while `review-pr` runs —+Temporal's same-id joining can't see across the two workflows; the chained post-publish dispatch is exempt by construction.+**TODO (SOON) — react to thread replies: answer and act when a human responds to an escalated (or any settled) thread.**The per-thread mechanics already exist and are e2e-proven: a new human comment beats the verdict watermark andre-opens triage for exactly that thread, standing verdicts ("SAFE TO FIX" / "E2E REQUIRED") steer the re-judged@@ -644,6 +656,19 @@ refreshes the perspective stats and an open drawer's detail (`reviewHogSettingsLpublished head, where `progress_payload` falls through to a review-stage label ("deduplicating"; thepre-publish window reads "finalizing"). A dedicated `resolving` stage needs the serializer enum, thefrontend stage labels, and regenerated types — deliberately left out of the staleness fix.+- **Accepted gap — a stopped standalone resolution on a never-reviewed PR never shows in the scene list.** Such+ a report has no `last_run_at` (only review turns stamp it), and the list admits it only while its activity is+ fresh — mutually exclusive with the stale-based "stopped" state, so the row drops out exactly when it would+ say "didn't finish" (the detail endpoint excludes it too). Accepted because the PR status comment now carries+ the failure notice reliably (the workflow-level `fail_resolution_activity` backstop) and the flow is rare+ (`/resolve` / inbox handoffs on PRs ReviewHog never reviewed). Fixing it means a new list slice for reports+ with a recent `resolution_run` plus an aging-out bound for stopped rows.+- **Accepted gap — a resolution turn longer than the 30-minute staleness window shows a false "didn't finish".**+ Resolution writes once per settled thread, so a single long turn (worst: the first, which carries sandbox boot+ - clone) can outlast `IN_PROGRESS_STALE_AFTER` with the run healthy — the row reads "stopped" while a+ retrigger correctly 409s. Accepted: typical turns run a few minutes, the label self-corrects on the next+ verdict, and the busy-guard still prevents double runs. If turns ever grow, add a periodic DB liveness beat+ inside `resolve_threads_activity` (Temporal's Heartbeater pings Temporal only, never the DB the UI reads).- **Alpha maturity** — the published comment still says "ReviewHog Alpha" and asks users to reply"valid"/"invalid" (`reviewer/tools/publish_review.py`, the `post_promo` block). Publish is now liveper-run (the trigger endpoint posts with `publish=true`), so settle the prod wording before real usersdiff --git a/products/review_hog/CONTEXT.md b/products/review_hog/CONTEXT.mdindex 6ada5466e7a5..461daa69cc2b 100644--- a/products/review_hog/CONTEXT.md+++ b/products/review_hog/CONTEXT.md@@ -26,6 +26,8 @@ Vocabulary settled while working on the product. Pure vocabulary — no spec, no- **Safe to fix now vs needs e2e** — the operational safety bar (inherited from the triage skill): a fix is safe when it is contained and provable in-session by unit tests/lint; asks touching LLM prompts, live external calls, or publish/workflow semantics need e2e verification → ESCALATE. Proportionality is part of the bar: a fix requiring new infrastructure (schema change, new abstraction, config knob) is a decision, not a mechanical fix → never auto-implemented.- **Pre-verdicted thread** — a thread carrying a standing human verdict as a reply (e.g. **SAFE TO FIX** / **E2E REQUIRED**). The resolution stage honors these: SAFE TO FIX substitutes for the worth judgment when verification confirms it; E2E REQUIRED forces ESCALATE. This is the human override channel into an otherwise autonomous run.- **Inventory** — the run's opening step: all unresolved threads fetched once and skimmed together before any turn, marking shared root causes. Turns stay strictly one-thread-each; a thread whose root cause an earlier turn already fixed closes as ALREADY FIXED pointing at that commit.+- **Review cycle** — one review turn plus its chained resolution, taken as a unit: the span from review start until the resolution stage finishes settling that review's comments. Two Temporal workflows implement it (see ADR 0001), but users reason about the cycle — "the PR is being worked on" — not the stages.+- **Busy-guard** — the explicit cross-stage check that refuses to start a new review while the PR's `resolve-pr` workflow is running, and refuses to start a standalone resolution while its `review-pr` workflow is running (the chained hand-off is exempt: it fires only after publish). Needed because Temporal's same-id joining cannot see across the two workflows.- **Resolution etiquette** — triage and fixing logic is identical for every thread regardless of author; only the _resolve_ action is author-gated. Human-authored threads: reply as the bot with the outcome (fix + commit link, or the decline/escalate reasoning), **never resolve** — the human keeps the final word on their own thread. Bot-authored threads: reply and resolve on terminal outcomes. ESCALATE never resolves, for any author. (Autonomous adaptation of the triage skill's "bot threads: reply + resolve; human threads: hand back" invariant — the bot now speaks as itself, but resolution of human threads still belongs to humans.)- **Entry points** — the durable interface is a trigger-style endpoint (mirroring `ReviewHogTriggerViewSet`: shared-secret bearer, server-side team/user resolution, unscoped mount), callable by API clients (other products, e.g. self-driving) and by a thin label-driven GitHub Action. Chained mode — `ReviewPRWorkflow` dispatching the stage after publish — is an internal dispatch, not an HTTP hop, and it is the **default**: reviewing includes resolving, gated by the acting user's `resolve_comments` setting (on unless they opt out; snapshotted at acting-user resolution like the other gates), with the workflow input as a per-run override only the Code review scene uses (its split Review button offers "review without resolving" and "resolve only"). A `run_resolution` management command mirrors `run_review` for dev/test. Deterministic skip gates run before any sandbox: closed/merged PR, fork (hard refuse — this stage writes), empty work-list after the pre-filter. One run per PR at a time via a deterministic workflow ID.- **Writing mechanics** — one signed commit per FIXED thread (a signed commit is inherently remote — the harness creates commits via the GitHub API, so commit cadence _is_ push cadence), with that thread's reply/resolve posted right after its commit is visible. On a mid-run race (author pushed; signed commit refuses because the remote advanced): sync onto the new head once, re-verify, retry; if the branch moves again, yield gracefully — done threads keep their outcomes, the rest wait for the next run.diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.mdindex f8952687f56f..165d82114d23 100644--- a/products/review_hog/DECISIONS.md+++ b/products/review_hog/DECISIONS.md@@ -3791,3 +3791,53 @@ the model/effort is brand-new, add it to the registry in **both** repos (`utils.gateway model list in `@posthog/agent`) or startup validation rejects it on one side.---++## Resolution-stage visibility & cycle guard (grilled 2026-08-13)++Motivated by the first prod day: a resolution on a user's PR (#80527) showed no progress anywhere, and #78061's+resolution died silently at sandbox checkout. Decisions, in one PR:++- **Busy-guard, both directions.** Starting a review (UI, label, trigger API) is refused while the PR's+ `resolve-pr` workflow runs ("Still resolving comments from the last review"); starting a standalone resolution+ is refused while `review-pr` runs. Chained hand-off exempt (fires post-publish by construction). Explicit check+ on the two deterministic workflow ids — Temporal same-id joining can't see across workflows (ADR 0001; blocked,+ not queued — queueing machinery isn't worth it yet).+- **Resolving progress derives from the artefact stream, not new columns.** At prepare, the run appends a+ work-list artefact (total, skipped); the reviews API counts the run's thread-verdict artefacts against it.+ Row shows "Resolving comments · 6/10 · 5 fixed, 1 needs you"; crashed runs go quiet and age out via the+ existing staleness window, mirroring review progress. Rejected: mutable stats block on the report (second+ writer, stale stats on crash).+- **Settled means delivered** (PR-review follow-up, 2026-08-18). The counters originally bumped at judge time,+ so a thread whose GitHub reply/resolve failed still read as done/fixed until the next run redelivered. Both+ surfaces now count only delivered threads — the activity renders from `delivered_outcomes` (bumped after+ `_deliver_side_effects` succeeds) and the UI derivation counts only `reply_posted` verdict rows — with+ undelivered threads folded into the closing tally's "couldn't handle" count. `triaged`/`outcomes` keep their+ judge-time meaning for the run note. Rejected: leaving it (the tally claimed replies that weren't on the PR)+ and a separate "pending redelivery" bucket (a third state to explain for a transient window).+- **Same GitHub status comment, extended.** Chained runs edit the review's existing status comment with a+ resolving section + final tally; standalone runs create the comment on demand via the same machinery+ (edits don't notify — one ReviewHog voice per PR).+- **Failure is visible.** UI: work-list artefact present + activity stale + no closing run-note ⇒ "Resolution+ didn't finish · stopped at N/M". GitHub: partial failures flow into the final tally ("couldn't handle 2");+ hard crashes get a best-effort failure edit (reusing the review's `fail_status_comment` pattern). Closes the+ silent-death mode observed on #78061.+- **Workflow-level failure cleanup** (PR-review follow-up, 2026-08-18). The activity's final-attempt failure+ edit misses three death modes: `_prepare_run` failures (before its `try` opens), timeout/cancellation+ (`CancelledError` is a `BaseException`), and worker death (no handler runs) — all of which left the GitHub+ comment saying "Resolving comments" forever (the UI half self-heals via staleness). `ResolvePRWorkflow` now+ wraps the resolution activity and fires a best-effort `fail_resolution_activity` before re-raising, gated+ behind `workflow.patched("fail-resolution-cleanup-2026-08")` for in-flight runs. The cleanup locates the+ report by `(team, repo, pr_number)` (the workflow never learns the report id on failure), idles it, and+ derives stopped-at counts via `resolution_states` — the exact numbers the UI row shows; no live run anchor+ means no comment edit, so a pre-queue crash can't spawn a spurious "stopped at 0/0" comment. The+ activity-level edit stays as the fast path. Mirrors the review workflow's `fail_status_comment_activity`.+- **👀 reaction marks queued threads.** Added right after work-list classification, triage-queued threads only+ (so 👀 = "in this run's queue"), best-effort, and left in place afterwards (removal doubles API calls for no+ real gain). Reactions send no notifications. Rejected: placeholder "working on it" comments — double+ notifications, and a crashed run leaves broken promises.+- **Not doing:** re-review-after-fixes dispatch (the loop's job, separately costed); prohibiting re-review after+ a _finished_ cycle (already safe: same-id review starts join the running workflow).++Vocabulary added to CONTEXT.md: **Review cycle**, **Busy-guard**. ADR: `adr/0001-resolution-is-a-separate-workflow.md`+(kept resolution a separate workflow after challenging it — standalone mode, failure isolation, independent+versioning outweigh the manual seam).diff --git a/products/review_hog/adr/0001-resolution-is-a-separate-workflow.md b/products/review_hog/adr/0001-resolution-is-a-separate-workflow.mdnew file mode 100644index 000000000000..03e43901df84--- /dev/null+++ b/products/review_hog/adr/0001-resolution-is-a-separate-workflow.md@@ -0,0 +1,7 @@+# Resolution runs as its own Temporal workflow, not a stage of the review workflow++Reviewing (`review-pr`) and resolving comments (`resolve-pr`) are separate Temporal workflows, with the review dispatching resolution as an abandoned child after publish. Considered folding resolution into the review workflow as a post-validation stage; rejected because (1) standalone resolution is first-class — `/resolve` and inbox handoffs settle other bots' and humans' comments on PRs ReviewHog never reviewed, so a merged workflow would still need a second entry point; (2) a resolution crash must not fail an already-published review, which the abandoned-child seam gives for free; (3) two short histories version independently — editing one stage's command sequence doesn't risk non-determinism for in-flight runs of the other.++## Consequences++Cross-stage coordination is manual: Temporal's same-id joining dedups review-vs-review and resolve-vs-resolve but cannot see across the two, so "is this PR's cycle busy?" checks and stage-aware UI/status surfaces must be built explicitly (decided 2026-08-13, reaffirmed while designing resolution-stage visibility).diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.pyindex 5b2048d6d676..14be7403f501 100644--- a/products/review_hog/backend/api/reviews.py+++ b/products/review_hog/backend/api/reviews.py@@ -1,6 +1,5 @@import uuidimport logging-from datetime import timedeltafrom typing import Any, cast, get_argsfrom django.conf import settings@@ -33,17 +32,26 @@ from products.review_hog.backend.reviewer.models.issues_review import IssuePriorfrom products.review_hog.backend.reviewer.models.split_pr_into_chunks import ChunksListfrom products.review_hog.backend.reviewer.persistence import load_chunk_set, load_findings_bundle, load_turn_findingsfrom products.review_hog.backend.reviewer.progress import (+ IN_PROGRESS_STALE_AFTER,+ RESOLUTION_RESOLVING,+ RESOLUTION_STOPPED,REVIEW_STAGES,+ ResolutionRunState,SnapshotStats,TurnStats,progress_payload,+ resolution_states,snapshot_stats,turn_stats,)from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_requestfrom products.review_hog.backend.reviewer.tools.github_meta import PRFetcher, PRMetadata, PRParser-from products.review_hog.backend.temporal.client import start_resolution_workflow, start_review_pr_workflow-from products.review_hog.backend.temporal.types import TRIGGER_UI+from products.review_hog.backend.temporal.client import (+ start_resolution_workflow,+ start_review_pr_workflow,+ workflow_running,+)+from products.review_hog.backend.temporal.types import TRIGGER_UI, resolve_pr_workflow_id, review_pr_workflow_idlogger = logging.getLogger(__name__)@@ -54,10 +62,6 @@ MAX_REVIEWS_LIMIT = 100# Effectiveness stats aggregate deeper than the list — enough history for survival rates to mean something.PERSPECTIVE_STATS_REPORT_LIMIT = 50-# An ACTIVE report only counts as "in progress" while its run is visibly moving (artefacts stream in-# throughout a run); past this an abandoned/crashed run stops rendering as a live row.-IN_PROGRESS_STALE_AFTER = timedelta(minutes=30)-_PRIORITY_CHOICES = [priority.value for priority in IssuePriority]# Display order for the detail view: most urgent first._PRIORITY_DISPLAY_RANK = {IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 1, IssuePriority.CONSIDER: 2}@@ -108,6 +112,20 @@ class ReviewProgressSerializer(serializers.Serializer):)+class ReviewResolutionStatusSerializer(serializers.Serializer):+ resolution_status = serializers.ChoiceField(+ choices=[RESOLUTION_RESOLVING, RESOLUTION_STOPPED],+ help_text="Where the run stands: `resolving` while threads are being settled, `stopped` when the "+ "run died partway (went quiet with no closing summary).",+ )+ done = serializers.IntegerField(help_text="Queued threads settled so far this run.")+ total = serializers.IntegerField(help_text="Threads queued for this run.")+ fixed = serializers.IntegerField(help_text="Settled threads that were fixed with a commit to the branch.")+ needs_attention = serializers.IntegerField(+ help_text="Settled threads left for the author: judged worth doing but not safe to fix unattended."+ )++class ReviewSelectionChunkSerializer(serializers.Serializer):chunk_id = serializers.IntegerField(help_text="The chunk this row describes, as numbered by the chunker.")chunk_type = serializers.CharField(@@ -163,10 +181,19 @@ class ReviewRecentReviewSerializer(serializers.Serializer):)published = serializers.BooleanField(help_text="Whether a review has been published back to GitHub.")in_progress = serializers.BooleanField(- help_text="Whether a review turn is running on this report right now (activity within the last 30 minutes)."+ help_text="Whether a run is on this report right now: a review turn or a resolution run "+ "(activity within the last 30 minutes).")progress = ReviewProgressSerializer(- allow_null=True, help_text="The in-flight turn's stage and counters; null unless `in_progress`."+ allow_null=True,+ help_text="The in-flight review turn's stage and counters; null unless a review turn is running "+ "(a resolving report carries `resolution` instead).",+ )+ resolution = ReviewResolutionStatusSerializer(+ allow_null=True,+ help_text="The report's latest resolution run (settling the PR's review threads): live progress "+ "while it runs, or where it stopped when it died partway. Null when there is none, it completed, "+ "or a newer review turn superseded it.",)must_fix_count = serializers.IntegerField(help_text="The latest turn's valid findings at must_fix effective priority."@@ -437,6 +464,7 @@ def _review_payload(turn: TurnStats,pairs: list[tuple[ReviewIssueFinding, ValidationVerdict | None]],progress: dict[str, Any] | None = None,+ resolution: ResolutionRunState | None = None,) -> dict[str, Any]:"""The list-row payload for one report; the detail endpoint layers findings on top."""counts = dict.fromkeys(IssuePriority, 0)@@ -463,8 +491,17 @@ def _review_payload("run_count": report.run_count,"last_run_at": report.last_run_at,"published": report.published_head_sha is not None,- "in_progress": progress is not None,+ "in_progress": progress is not None or (resolution is not None and resolution.status == RESOLUTION_RESOLVING),"progress": progress,+ "resolution": {+ "resolution_status": resolution.status,+ "done": resolution.done,+ "total": resolution.total,+ "fixed": resolution.fixed,+ "needs_attention": resolution.needs_attention,+ }+ if resolution is not None+ else None,"must_fix_count": counts[IssuePriority.MUST_FIX],"should_fix_count": counts[IssuePriority.SHOULD_FIX],"consider_count": counts[IssuePriority.CONSIDER],@@ -581,14 +618,18 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetlive_snapshots = snapshot_stats(team_id, live_heads) if in_flight else {}live_turns = turn_stats(team_id, live_heads) if in_flight else {}bundle = load_findings_bundle(team_id=team_id, report_ids=[str(report.id) for report in reports])+ resolution_map = resolution_states(team_id, reports)items = []for report in reports:report_id = str(report.id)snapshot = snapshots.get(report_id, SnapshotStats())turn = turns.get(report_id, TurnStats())pairs = bundle.turn(report_id, report.run_count)+ resolution = resolution_map.get(report_id)progress = None- if report_id in in_progress_ids:+ # A resolving report's live run is the resolution, not a review turn — inferring a+ # review stage from the completed turn's artefacts would relabel it "deduplicating".+ if report_id in in_progress_ids and (resolution is None or resolution.status != RESOLUTION_RESOLVING):# The in-flight turn's findings live one run_index ahead of the completed watermark.current_pairs = bundle.turn(report_id, report.run_count + 1)progress = progress_payload(@@ -598,7 +639,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetlive_turns.get(report_id, TurnStats()),current_pairs,)- items.append(_review_payload(report, snapshot, turn, pairs, progress))+ items.append(_review_payload(report, snapshot, turn, pairs, progress, resolution))return Response(ReviewRecentReviewsPageSerializer({"results": items, "has_more": has_more}).data)@extend_schema(@@ -654,6 +695,11 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetresponse=ReviewTriggerErrorSerializer,description="The ReviewHog UI trigger is not enabled for this project.",),+ 409: OpenApiResponse(+ response=ReviewTriggerErrorSerializer,+ description="The pull request's cycle is busy (busy-guard): reviews are blocked while its "+ "comments are being resolved, and resolve-only runs are blocked while a review is running.",+ ),429: OpenApiResponse(description="GitHub rate-limited the App's token; retry after the Retry-After delay."),},summary="Start a review of a pull request",@@ -731,6 +777,27 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetstatus=status.HTTP_400_BAD_REQUEST,)run_mode: str = serializer.validated_data["run_mode"]+ # The busy-guard (CONTEXT.md): Temporal joins same-id starts on its own, but a review and+ # this PR's resolution run under different workflow ids, so the cross-stage check is+ # explicit — and the answer is a refusal, not a queue.+ pr_owner, pr_repo = str(pr_info["owner"]), str(pr_info["repo"])+ if run_mode == RUN_MODE_RESOLVE_ONLY:+ if workflow_running(+ review_pr_workflow_id(team_id=team_id, owner=pr_owner, repo=pr_repo, pr_number=pr_number)+ ):+ return Response(+ {+ "error": "A review is already running on this pull request. It resolves comments when it finishes."+ },+ status=status.HTTP_409_CONFLICT,+ )+ elif workflow_running(+ resolve_pr_workflow_id(team_id=team_id, owner=pr_owner, repo=pr_repo, pr_number=pr_number)+ ):+ return Response(+ {"error": "Still resolving comments from the last review. Try again when it finishes."},+ status=status.HTTP_409_CONFLICT,+ )# Rebuilt canonical URL: the parser accepts trailing paths (e.g. …/pull/123/files).pr_url = f"https://github.com/{pr_info['owner']}/{pr_info['repo']}/pull/{pr_info['pr_number']}"# The requester is both the run user (sandbox identity) and the acting user (whose@@ -823,7 +890,11 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetdismissed = [_finding_payload(f, v) for f, v in pairs if v is not None and not v.is_valid]payload = {**_review_payload(- report, snapshots.get(report_id, SnapshotStats()), turns.get(report_id, TurnStats()), pairs+ report,+ snapshots.get(report_id, SnapshotStats()),+ turns.get(report_id, TurnStats()),+ pairs,+ resolution=resolution_states(team_id, [report]).get(report_id),),"head_sha": completed_head,"report_markdown": report.report_markdown,diff --git a/products/review_hog/backend/api/trigger.py b/products/review_hog/backend/api/trigger.pyindex dd6f0bb7348d..e7d3b54f5fde 100644--- a/products/review_hog/backend/api/trigger.py+++ b/products/review_hog/backend/api/trigger.py@@ -13,8 +13,12 @@ from posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Team-from products.review_hog.backend.temporal.client import start_resolution_workflow, start_review_pr_workflow-from products.review_hog.backend.temporal.types import TRIGGER_LABEL+from products.review_hog.backend.temporal.client import (+ start_resolution_workflow,+ start_review_pr_workflow,+ workflow_running,+)+from products.review_hog.backend.temporal.types import TRIGGER_LABEL, resolve_pr_workflow_id, review_pr_workflow_idlogger = logging.getLogger(__name__)@@ -167,6 +171,10 @@ class ReviewHogTriggerViewSet(viewsets.ViewSet):403: OpenApiResponse(response=ReviewHogTriggerErrorSerializer, description="Missing/invalid token or disallowed repo"),+ 409: OpenApiResponse(+ response=ReviewHogTriggerErrorSerializer,+ description="The PR's resolution run is still going (busy-guard); retry once it finishes",+ ),503: OpenApiResponse(response=ReviewHogTriggerErrorSerializer, description="Trigger team not configured"),},summary="Trigger a ReviewHog PR review",@@ -195,6 +203,15 @@ class ReviewHogTriggerViewSet(viewsets.ViewSet):return gatesteam_id, user_id = gates+ # The busy-guard (CONTEXT.md): a review is refused while this PR's resolution run is still+ # going — Temporal joins same-id review starts on its own, but resolve-pr is a different id.+ owner, _, repo_name = repo.partition("/")+ if workflow_running(resolve_pr_workflow_id(team_id=team_id, owner=owner, repo=repo_name, pr_number=pr_number)):+ return Response(+ {"error": "Still resolving comments from the last review. Try again when it finishes."},+ status=status.HTTP_409_CONFLICT,+ )+# Forks are rejected server-side in the workflow's fetch activity (and by the Action gate); the# endpoint stays free of GitHub I/O and returns immediately. Reviewing includes resolving:# whether the run chains the resolution stage is the PR author's `resolve_comments` setting@@ -223,6 +240,10 @@ class ReviewHogTriggerViewSet(viewsets.ViewSet):403: OpenApiResponse(response=ReviewHogTriggerErrorSerializer, description="Missing/invalid token or disallowed repo"),+ 409: OpenApiResponse(+ response=ReviewHogTriggerErrorSerializer,+ description="The PR's review workflow is still going (busy-guard); it chains resolution itself",+ ),503: OpenApiResponse(response=ReviewHogTriggerErrorSerializer, description="Trigger team not configured"),},summary="Trigger the ReviewHog resolution stage on a PR",@@ -249,6 +270,15 @@ class ReviewHogTriggerViewSet(viewsets.ViewSet):return gatesteam_id, user_id = gates+ # The busy-guard's other direction: a standalone resolution is refused while the PR's+ # review workflow is still going (a finishing review chains its own resolution anyway).+ owner, _, repo_name = repo.partition("/")+ if workflow_running(review_pr_workflow_id(team_id=team_id, owner=owner, repo=repo_name, pr_number=pr_number)):+ return Response(+ {"error": "A review is already running on this pull request. It resolves comments when it finishes."},+ status=status.HTTP_409_CONFLICT,+ )+# Fork/closed gates run server-side in the workflow's prepare step (they need GitHub I/O).pr_url = f"https://github.com/{repo}/pull/{pr_number}"workflow_id = start_resolution_workflow(diff --git a/products/review_hog/backend/migrations/0029_alter_reviewreportartefact_type.py b/products/review_hog/backend/migrations/0029_alter_reviewreportartefact_type.pynew file mode 100644index 000000000000..dd47bd54a85b--- /dev/null+++ b/products/review_hog/backend/migrations/0029_alter_reviewreportartefact_type.py@@ -0,0 +1,34 @@+# Generated by Django 5.2.17 on 2026-08-13 13:31++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("review_hog", "0028_reviewusersettings_resolve_comments"),+ ]++ operations = [+ migrations.AlterField(+ model_name="reviewreportartefact",+ name="type",+ field=models.CharField(+ choices=[+ ("issue_finding", "Issue Finding"),+ ("validation_verdict", "Validation Verdict"),+ ("finding_outcome", "Finding Outcome"),+ ("thread_verdict", "Thread Verdict"),+ ("resolution_run", "Resolution Run"),+ ("task_run", "Task Run"),+ ("commit", "Commit"),+ ("code_reference", "Code Reference"),+ ("note", "Note"),+ ("chunk_set", "Chunk Set"),+ ("perspective_selection", "Perspective Selection"),+ ("perspective_result", "Perspective Result"),+ ("pr_snapshot", "Pr Snapshot"),+ ],+ max_length=100,+ ),+ ),+ ]diff --git a/products/review_hog/backend/migrations/max_migration.txt b/products/review_hog/backend/migrations/max_migration.txtindex ed6e13411013..391b0cd2d8d1 100644--- a/products/review_hog/backend/migrations/max_migration.txt+++ b/products/review_hog/backend/migrations/max_migration.txt@@ -1 +1 @@-0028_reviewusersettings_resolve_comments+0029_alter_reviewreportartefact_typediff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.pyindex 77f866cdcbb4..d329528197d3 100644--- a/products/review_hog/backend/models.py+++ b/products/review_hog/backend/models.py@@ -6,6 +6,7 @@ from posthog.models.utils import UUIDModelfrom products.review_hog.backend.reviewer.artefact_content import (ArtefactContentValidationError,FindingOutcomeArtefact,+ ResolutionRunArtefact,ReviewArtefactContent,ReviewIssueFinding,ReviewLogArtefactContent,@@ -166,6 +167,8 @@ class ReviewReportArtefact(UUIDModel, TeamScopedRootMixin):FINDING_OUTCOME = "finding_outcome"# The resolution stage's per-thread ruling (latest row per thread_id wins).THREAD_VERDICT = "thread_verdict"+ # One resolution run's opening work-list; the newest row is the report's latest run.+ RESOLUTION_RUN = "resolution_run"TASK_RUN = "task_run"COMMIT = "commit"CODE_REFERENCE = "code_reference"@@ -282,6 +285,13 @@ class ReviewReportArtefact(UUIDModel, TeamScopedRootMixin):"""Append a `thread_verdict` (latest row per `thread_id` wins at read time)."""return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)+ @classmethod+ def append_resolution_run(+ cls, *, team_id: int, report_id: str, content: ResolutionRunArtefact, attribution: ArtefactAttribution+ ) -> "ReviewReportArtefact":+ """Append a `resolution_run` (one per run, at prepare; the newest row is the latest run)."""+ return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)+@classmethoddef add_log(cls, *, team_id: int, report_id: str, content: ReviewLogArtefactContent, attribution: ArtefactAttributiondiff --git a/products/review_hog/backend/receivers.py b/products/review_hog/backend/receivers.pyindex 6a509bd05ebb..9b22f0114ca6 100644--- a/products/review_hog/backend/receivers.py+++ b/products/review_hog/backend/receivers.py@@ -274,16 +274,39 @@ def _start_review("""Fire-and-forget the review workflow; Temporal being down must never surface into the saver.The PR leg wins when both targets are present — the client accepts exactly one, and a PR is the- strictly better target (publishable, and its head IS the pushed branch).+ strictly better target (publishable, and its head IS the pushed branch). The PR leg also honors+ the busy-guard, the same refusal the trigger/resolve endpoints apply, so an inbox review never+ starts while this PR's resolution run is still committing to the branch."""# Function-local: importing the temporal client executes the review_hog temporal package, whose# activity registration reaches temporalio, modal, openai, and anthropic — all four forbidden at# django.setup() by the startup-import-budget test. See the module-top comment.- from products.review_hog.backend.temporal.client import start_review_pr_workflow # noqa: PLC0415- from products.review_hog.backend.temporal.types import TRIGGER_INBOX # noqa: PLC0415+ from products.review_hog.backend.reviewer.tools.github_meta import PRParser # noqa: PLC0415+ from products.review_hog.backend.temporal.client import start_review_pr_workflow, workflow_running # noqa: PLC0415+ from products.review_hog.backend.temporal.types import TRIGGER_INBOX, resolve_pr_workflow_id # noqa: PLC0415try:if pr_url is not None:+ # Busy-guard (CONTEXT.md): a published inbox review chains its own resolution, which+ # commits to the branch for minutes — starting a fresh review meanwhile races those+ # pushes and re-reviews threads mid-settlement. Only the PR leg needs it (resolution+ # needs a pr_url, so the branch leg can't collide); the chained hand-off starts+ # resolution as a child workflow, never through this path, so it stays exempt.+ pr_info = PRParser().parse_github_pr_url(pr_url)+ if workflow_running(+ resolve_pr_workflow_id(+ team_id=team_id,+ owner=str(pr_info["owner"]),+ repo=str(pr_info["repo"]),+ pr_number=int(pr_info["pr_number"]),+ )+ ):+ logger.info(+ "review_hog_inbox_review_skipped_busy: resolution still running for %s (signal report %s)",+ pr_url,+ signal_report_id,+ )+ returnworkflow_id = start_review_pr_workflow(team_id=team_id,user_id=user_id,diff --git a/products/review_hog/backend/reviewer/artefact_content.py b/products/review_hog/backend/reviewer/artefact_content.pyindex 96b576f6270f..1b57051e296e 100644--- a/products/review_hog/backend/reviewer/artefact_content.py+++ b/products/review_hog/backend/reviewer/artefact_content.py@@ -193,6 +193,27 @@ class ThreadVerdictArtefact(BaseModel):return v+class ResolutionRunArtefact(BaseModel):+ """Content for a `resolution_run` artefact: one resolution run's opening work-list.++ Appended by the run's prepare step the moment the work-list is classified, so progress surfaces+ (the reviews API's resolving row, the PR status comment) can count the run's `thread_verdict`+ artefacts against it. The newest row marks the report's latest resolution run; the run's closing+ `note` artefact (author `review_hog_resolution`) marks it finished — a run artefact with no+ later closing note is either still running (recent artefact activity) or died partway (stale).+ """++ total: int = Field(description="Threads queued for a resolution turn this run (post pre-filter and run cap).")+ thread_ids: list[str] = Field(+ default_factory=list,+ description="The queued threads' node ids, so progress counts only this run's verdicts "+ "(redelivered prior-run verdicts also append rows during the run).",+ )+ redeliver: int = Field(default=0, description="Threads only needing their GitHub writes redelivered (no LLM turn).")+ skipped: int = Field(default=0, description="Threads skipped as already judged and delivered.")+ overflow: int = Field(default=0, description="Threads beyond the run cap, left for the next run.")++class ChunkSetArtefact(BaseModel):"""Content for a `chunk_set` artefact: the PR's chunking computed for ONE review turn.@@ -259,6 +280,7 @@ ReviewArtefactContent = (| ValidationVerdict| FindingOutcomeArtefact| ThreadVerdictArtefact+ | ResolutionRunArtefact| ReviewLogArtefactContent| ReviewWorkingStateContent)@@ -269,6 +291,7 @@ ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {"validation_verdict": ValidationVerdict,"finding_outcome": FindingOutcomeArtefact,"thread_verdict": ThreadVerdictArtefact,+ "resolution_run": ResolutionRunArtefact,"task_run": TaskRunArtefact,"commit": Commit,"code_reference": CodeReference,diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.pyindex b951f6f546cb..3d5ca7ea37f0 100644--- a/products/review_hog/backend/reviewer/progress.py+++ b/products/review_hog/backend/reviewer/progress.py@@ -10,18 +10,23 @@ comment, so the two surfaces can never disagree.import loggingimport operatorfrom dataclasses import dataclass+from datetime import datetime, timedeltafrom functools import reducefrom typing import Any-from django.db.models import Func, IntegerField, JSONField, Q, QuerySet+from django.db.models import Func, IntegerField, JSONField, Max, Q, QuerySetfrom django.db.models.fields.json import KeyTextTransform, KeyTransformfrom django.db.models.functions import Cast+from django.utils import timezonefrom pydantic import ValidationError+from posthog.dataclasses import frozen+from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact, ReviewSkillConfigfrom products.review_hog.backend.reviewer.artefact_content import (PerspectiveSelectionArtefact,+ ResolutionRunArtefact,ReviewIssueFinding,ValidationVerdict,)@@ -37,6 +42,18 @@ logger = logging.getLogger(__name__)REVIEW_STAGES = ["fetching", "chunking", "selecting", "reviewing", "deduplicating", "validating", "finalizing"]+# An ACTIVE report only counts as running while its run is visibly moving (artefacts stream in+# throughout a run); past this quiet window a review run stops rendering as live, and a resolution+# run with no closing note starts rendering as died partway.+IN_PROGRESS_STALE_AFTER = timedelta(minutes=30)++RESOLUTION_RESOLVING = "resolving"+RESOLUTION_STOPPED = "stopped"+# The `author` the resolution stage stamps on its closing run `note` — the completion marker the+# state derivation looks for. Kept here so the writer (temporal/resolution.py) and this reader+# can't drift apart.+RESOLUTION_RUN_NOTE_AUTHOR = "review_hog_resolution"+@dataclassclass SnapshotStats:@@ -205,6 +222,123 @@ def turn_stats(team_id: int, heads: dict[str, str | None]) -> dict[str, TurnStatreturn stats+@frozen+class ResolutionRunState:+ """The report's latest resolution run, as the list row and the drawer render it."""++ status: str # RESOLUTION_RESOLVING | RESOLUTION_STOPPED+ done: int = 0+ total: int = 0+ fixed: int = 0+ needs_attention: int = 0+++def resolution_states(team_id: int, reports: list[ReviewReport]) -> dict[str, ResolutionRunState]:+ """Each report's latest resolution run — resolving or died-partway — derived from artefacts.++ The run's `resolution_run` artefact (written at prepare) anchors it: the run's progress is its+ queued threads' `thread_verdict` rows written since, its completion is a closing run `note`+ (author `review_hog_resolution`) written since, and its liveness is the report's overall+ artefact activity against the staleness window — the same signal `_in_progress_report_ids`+ uses for review turns, so the two can't disagree about "visibly moving".++ A report is absent from the result when it has no resolution run, its latest run completed+ (closing note present), or a newer review turn superseded it (a `pr_snapshot` written after the+ run anchor — that turn's own progress takes over the row).+ """+ runs: dict[str, tuple[ResolutionRunArtefact, datetime]] = {}+ run_rows = (+ ReviewReportArtefact.objects.for_team(team_id)+ .filter(+ report_id__in=[report.id for report in reports],+ type=ReviewReportArtefact.ArtefactType.RESOLUTION_RUN,+ )+ .order_by("report_id", "-created_at", "-id")+ .distinct("report_id")+ .values("report_id", "content", "created_at")+ )+ for row in run_rows:+ report_id = str(row["report_id"])+ try:+ run = ResolutionRunArtefact.model_validate_json(row["content"])+ except ValidationError as e:+ logger.warning("Skipping unparseable resolution_run for report %s: %s", report_id, e)+ continue+ if run.total > 0:+ runs[report_id] = (run, row["created_at"])+ if not runs:+ return {}++ def _latest_after(queryset: QuerySet) -> dict[str, datetime]:+ rows = queryset.values_list("report_id").annotate(latest=Max("created_at")).values_list("report_id", "latest")+ return {str(report_id): latest for report_id, latest in rows}++ scoped = ReviewReportArtefact.objects.for_team(team_id).filter(report_id__in=list(runs))+ snapshot_latest = _latest_after(scoped.filter(type=ReviewReportArtefact.ArtefactType.PR_SNAPSHOT))+ note_latest = _latest_after(+ scoped.filter(type=ReviewReportArtefact.ArtefactType.NOTE)+ .annotate(note_author=KeyTextTransform("author", _content_json()))+ .filter(note_author=RESOLUTION_RUN_NOTE_AUTHOR)+ )+ activity_latest = _latest_after(scoped.exclude(type=ReviewReportArtefact.ArtefactType.FINDING_OUTCOME))++ live: dict[str, tuple[ResolutionRunArtefact, datetime]] = {}+ for report_id, (run, started_at) in runs.items():+ superseded = snapshot_latest.get(report_id) is not None and snapshot_latest[report_id] > started_at+ completed = note_latest.get(report_id) is not None and note_latest[report_id] >= started_at+ if not superseded and not completed:+ live[report_id] = (run, started_at)+ if not live:+ return {}++ # Latest verdict per thread within each live run (rows come oldest-first, so later rows win) —+ # scoped to the run's own queued threads, because redelivering a prior run's verdict also+ # appends rows during this run. Only delivered verdicts (`reply_posted`) count: a judged thread+ # whose GitHub writes failed has no reply yet, so it must not read as settled.+ verdicts: dict[str, dict[str, tuple[str, bool]]] = {report_id: {} for report_id in live}+ verdict_rows = (+ ReviewReportArtefact.objects.for_team(team_id)+ .filter(+ report_id__in=list(live),+ type=ReviewReportArtefact.ArtefactType.THREAD_VERDICT,+ created_at__gte=min(started_at for _, started_at in live.values()),+ )+ .annotate(+ thread_id=KeyTextTransform("thread_id", _content_json()),+ outcome=KeyTextTransform("outcome", _content_json()),+ reply_posted=KeyTextTransform("reply_posted", _content_json()),+ )+ .order_by("created_at", "id")+ .values("report_id", "thread_id", "outcome", "reply_posted", "created_at")+ )+ for verdict_row in verdict_rows:+ report_id = str(verdict_row["report_id"])+ run, started_at = live[report_id]+ if verdict_row["created_at"] < started_at or verdict_row["thread_id"] not in run.thread_ids:+ continue+ verdicts[report_id][verdict_row["thread_id"]] = (+ verdict_row["outcome"],+ verdict_row["reply_posted"] == "true",+ )++ cutoff = timezone.now() - IN_PROGRESS_STALE_AFTER+ reports_by_id = {str(report.id): report for report in reports}+ states: dict[str, ResolutionRunState] = {}+ for report_id, (run, _started_at) in live.items():+ report = reports_by_id[report_id]+ last_activity = max(filter(None, [report.updated_at, activity_latest.get(report_id)]), default=None)+ fresh = last_activity is not None and last_activity >= cutoff+ delivered = [outcome for outcome, reply_posted in verdicts[report_id].values() if reply_posted]+ states[report_id] = ResolutionRunState(+ status=RESOLUTION_RESOLVING if fresh else RESOLUTION_STOPPED,+ done=len(delivered),+ total=run.total,+ fixed=sum(1 for outcome in delivered if outcome == "fixed"),+ needs_attention=sum(1 for outcome in delivered if outcome == "escalate"),+ )+ return states++def _expected_reads(team_id: int, report: ReviewReport, turn: TurnStats) -> int | None:"""How many (pass, chunk) reviews this turn should produce.diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.pyindex 899063c07104..d6abe3da6211 100644--- a/products/review_hog/backend/reviewer/status_comment.py+++ b/products/review_hog/backend/reviewer/status_comment.py@@ -7,6 +7,10 @@ edited, never re-posted: comment edits don't notify PR subscribers, while everyeveryone. Progress renders from the same derivation the reviews API uses (`reviewer.progress`), sothe 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+also 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, orretry a review, so all exceptions are swallowed after logging."""@@ -21,7 +25,7 @@ from django.db.models import Qfrom django.utils import timezonefrom posthog.dataclasses import frozen-from posthog.models.integration import GitHubIntegration+from posthog.models.integration import GitHubIntegration, Integrationfrom products.review_hog.backend.models import ReviewReportfrom products.review_hog.backend.reviewer.constants import (@@ -111,6 +115,24 @@ 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 -->"++# 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+# the PR author skimming a tally.+_RESOLUTION_OUTCOME_LABELS = {+ "fixed": "fixed",+ "wont_fix": "declined",+ "already_fixed": "already settled",+ "obsolete": "already settled",+ "escalate": "left for you",+}+_RESOLUTION_OUTCOME_ORDER = ("fixed", "declined", "already settled", "left for you")++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.@@ -205,6 +227,58 @@ def render_final_body(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 render_resolution_final_section(*, 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")+ 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>",+ ]+ )+++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) -> str:return "\n".join([@@ -229,6 +303,18 @@ def _auth(team_id: int, repository: str) -> tuple[str, str | None] | None:return github.get_access_token(), github.github_installation_id+def _auth_from_row(team_id: int, integration_row_id: int) -> tuple[str, str | None]:+ """A fresh installation token from an already-pinned integration row, skipping `_auth`'s probe.++ A resolution run selects its installation once and refreshes the status comment after every+ thread; re-running the selection probe each time repeats a `GET /repos/{repository}` for an+ answer the run already has. GitHub still enforces access on the edit itself, so a mid-run+ revocation surfaces there and is swallowed like any other status-comment failure.+ """+ github = GitHubIntegration(Integration.objects.get(id=integration_row_id, team_id=team_id))+ return github.get_access_token(), github.github_installation_id++def _find_marker_comment(owner: str, repo: str, pr_number: int, marker: str, *, token: str, installation_id: str | None) -> int | None:@@ -250,6 +336,18 @@ def _find_marker_comment(return None+def _get_comment(owner: str, repo: str, comment_id: int, *, token: str, installation_id: str | None) -> str:+ """The comment's current body — the resolution splice edits around the review's own text."""+ response = github_api_request(+ "GET",+ f"/repos/{owner}/{repo}/issues/comments/{comment_id}",+ token=token,+ installation_id=installation_id,+ endpoint="/repos/{owner}/{repo}/issues/comments/{comment_id}",+ )+ return response.json().get("body") or ""++def _post_comment(owner: str, repo: str, pr_number: int, body: str, *, token: str, installation_id: str | None) -> int | None:@@ -426,6 +524,65 @@ def fail_status_comment(team_id: int, report_id: str) -> None: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+) -> None:+ """Splice the resolution stage's section into the report's status comment.++ Chained runs extend the review's existing comment (edits don't notify PR subscribers, and one+ ReviewHog 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+ every 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+ (`_auth_from_row`) rather than re-running the installation-selection probe on every refresh;+ without one it falls back to the probe (`_auth`).+ """+ try:+ report = ReviewReport.objects.for_team(team_id).filter(id=report_id).first()+ if report is None or report.pr_number is None:+ return+ auth = (+ _auth_from_row(team_id, integration_row_id)+ if integration_row_id is not None+ else _auth(team_id, report.repository)+ )+ if auth is None:+ return+ token, installation_id = auth+ owner, repo = _split_repository(report.repository)+ marker = status_marker(report_id)++ comment_id = report.status_comment_id+ if comment_id is None:+ comment_id = _find_marker_comment(+ owner, repo, report.pr_number, marker, token=token, installation_id=installation_id+ )+ body: str | None = None+ if comment_id is not None:+ try:+ body = _get_comment(owner, repo, comment_id, token=token, installation_id=installation_id)+ except GitHubAPIError as e:+ if e.status != 404:+ raise+ comment_id = None # the stored comment was deleted on GitHub; post fresh+ # 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)+ if comment_id is not None:+ _patch_comment(owner, repo, comment_id, new_body, token=token, installation_id=installation_id)+ else:+ comment_id = _post_comment(+ owner, repo, report.pr_number, new_body, token=token, installation_id=installation_id+ )+ report.status_comment_id = comment_id+ 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")++def _edit_and_stamp(team_id: int, report: ReviewReport, body: str) -> None:auth = _auth(team_id, report.repository)if auth is None:diff --git a/products/review_hog/backend/reviewer/tools/github_threads.py b/products/review_hog/backend/reviewer/tools/github_threads.pyindex 571741cc708f..11331b575f42 100644--- a/products/review_hog/backend/reviewer/tools/github_threads.py+++ b/products/review_hog/backend/reviewer/tools/github_threads.py@@ -59,6 +59,8 @@ class ThreadComment(BaseModel):"""One comment inside a review thread, as the resolution stage consumes it."""id: int | None = Field(default=None, description="GitHub databaseId; None for minimized/ghost comments.")+ # GraphQL node id (PRRC_…) — the addReaction mutation's subject; empty for ghost comments.+ node_id: str = ""author_login: str = ""# From GraphQL `author { __typename }` — authoritative, unlike login-suffix heuristics.author_is_bot: bool = False@@ -166,6 +168,7 @@ query($owner: String!, $name: String!, $number: Int!, $cursor: String, $pageSizecomments(first: $commentsPerThread) {pageInfo { hasNextPage endCursor }nodes {+ iddatabaseIdurlbody@@ -213,6 +216,7 @@ def _parse_comments(nodes: list[Any]) -> list[ThreadComment]:comments.append(ThreadComment(id=comment.get("databaseId"),+ node_id=comment.get("id") or "",author_login=author.get("login") or "",author_is_bot=author.get("__typename") == "Bot",author_association=comment.get("authorAssociation") or "NONE",@@ -343,6 +347,28 @@ def reply_to_thread(return comment.get("databaseId"), comment.get("url")+def add_eyes_reaction(*, token: str, subject_id: str, installation_id: str | None = None) -> None:+ """Add a 👀 reaction to a comment (by GraphQL node id) — the "queued for this run" marker.++ Reactions send no notifications, and GitHub treats a repeat addReaction as a no-op, so a+ retried prepare step never stacks duplicates. The reaction is deliberately never removed:+ removal would double the API calls for no real gain (see DECISIONS.md — resolution-stage+ visibility).+ """+ github_graphql_request(+ """+ mutation($subjectId: ID!) {+ addReaction(input: {subjectId: $subjectId, content: EYES}) {+ reaction { content }+ }+ }+ """,+ {"subjectId": subject_id},+ token=token,+ installation_id=installation_id,+ )++def resolve_thread(*, token: str, thread_id: str, installation_id: str | None = None) -> bool:"""Resolve a review thread; returns GitHub's resulting `isResolved`."""data = github_graphql_request(diff --git a/products/review_hog/backend/temporal/__init__.py b/products/review_hog/backend/temporal/__init__.pyindex 3335224cffbd..84792ed2f76f 100644--- a/products/review_hog/backend/temporal/__init__.py+++ b/products/review_hog/backend/temporal/__init__.py@@ -27,7 +27,11 @@ from products.review_hog.backend.temporal.outcomes_activities import (discover_outcome_teams_activity,)from products.review_hog.backend.temporal.outcomes_workflow import ClassifyFindingOutcomesWorkflow-from products.review_hog.backend.temporal.resolution import ResolvePRWorkflow, resolve_threads_activity+from products.review_hog.backend.temporal.resolution import (+ ResolvePRWorkflow,+ fail_resolution_activity,+ resolve_threads_activity,+)from products.review_hog.backend.temporal.workflow import (ReviewPerspectivesWorkflow,ReviewPRWorkflow,@@ -68,4 +72,5 @@ ACTIVITIES = [discover_outcome_teams_activity,classify_team_outcomes_activity,resolve_threads_activity,+ fail_resolution_activity,]diff --git a/products/review_hog/backend/temporal/client.py b/products/review_hog/backend/temporal/client.pyindex d81fed0ac5dc..2a5a0abd6882 100644--- a/products/review_hog/backend/temporal/client.py+++ b/products/review_hog/backend/temporal/client.py@@ -32,7 +32,9 @@ from typing import Any, castfrom django.conf import settingsfrom asgiref.sync import async_to_sync+from temporalio.client import WorkflowExecutionStatusfrom temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicy+from temporalio.service import RPCError, RPCStatusCodefrom posthog.models.team.team import Teamfrom posthog.temporal.common.client import sync_connect@@ -54,6 +56,29 @@ logger = logging.getLogger(__name__)_PARENT_RETRY = RetryPolicy(maximum_attempts=2)+def workflow_running(workflow_id: str) -> bool:+ """Whether `workflow_id` has a live execution — the busy-guard's probe (CONTEXT.md — "Busy-guard").++ Temporal's same-id joining dedups review-vs-review and resolve-vs-resolve on its own, but the+ review and resolution workflows carry different ids, so the cross-stage "is this PR's cycle+ busy?" check is this explicit describe. Fail-open on probe errors other than not-found: a+ trigger must not 500 over a flaky describe, and a real Temporal outage still surfaces on the+ start call itself.+ """+ try:+ client = sync_connect()+ description = async_to_sync(client.get_workflow_handle(workflow_id).describe)()+ except RPCError as e:+ if e.status == RPCStatusCode.NOT_FOUND:+ return False+ logger.warning("Busy-guard describe failed for %s: %s", workflow_id, e)+ return False+ except Exception:+ logger.exception("Busy-guard describe failed for %s", workflow_id)+ return False+ return description.status == WorkflowExecutionStatus.RUNNING++def _build_inputs(*,team_id: int,diff --git a/products/review_hog/backend/temporal/resolution.py b/products/review_hog/backend/temporal/resolution.pyindex 1f460898ded5..6bd79cc6a8dd 100644--- a/products/review_hog/backend/temporal/resolution.py+++ b/products/review_hog/backend/temporal/resolution.py@@ -35,7 +35,7 @@ from posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connectionsfrom products.review_hog.backend.models import ReviewReport, ReviewReportArtefact-from products.review_hog.backend.reviewer.artefact_content import ThreadVerdictArtefact+from products.review_hog.backend.reviewer.artefact_content import ResolutionRunArtefact, ThreadVerdictArtefactfrom products.review_hog.backend.reviewer.constants import (MAX_THREADS_PER_RUN,RESOLUTION_INITIAL_PERMISSION_MODE,@@ -51,6 +51,7 @@ from products.review_hog.backend.reviewer.persistence import (persist_thread_verdict,upsert_review_report,)+from products.review_hog.backend.reviewer.progress import RESOLUTION_RUN_NOTE_AUTHOR, resolution_statesfrom products.review_hog.backend.reviewer.sandbox.executor import (MultiTurnSession,continue_sandbox_session,@@ -58,11 +59,18 @@ from products.review_hog.backend.reviewer.sandbox.executor import (start_sandbox_session,)from products.review_hog.backend.reviewer.skill_loader import load_resolution_skill_for_run+from products.review_hog.backend.reviewer.status_comment import (+ render_resolution_failed_section,+ render_resolution_final_section,+ render_resolution_progress_section,+ update_resolution_status_comment,+)from products.review_hog.backend.reviewer.tools.github_client import github_api_requestfrom products.review_hog.backend.reviewer.tools.github_meta import PRFetcherfrom products.review_hog.backend.reviewer.tools.github_threads import (ReviewThread,ThreadAction,+ add_eyes_reaction,classify_thread,commit_on_branch,fetch_unresolved_threads,@@ -131,6 +139,9 @@ class ResolutionRunResult:# Threads that got an LLM turn this run, and their outcome counts (keyed by ThreadOutcome value).triaged: int = 0outcomes: dict[str, int] = field(default_factory=dict)+ # Outcome counts for threads whose GitHub writes also landed. The PR-facing counters render from+ # these, not `outcomes` — a judged thread with no reply must not read as settled.+ delivered_outcomes: dict[str, int] = field(default_factory=dict)# Threads whose persisted verdict only needed its GitHub writes redelivered (no LLM turn).redelivered: int = 0# Threads skipped as already judged and delivered.@@ -226,6 +237,12 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResu_idle_report(input.team_id, report_id)return result+ if triage:+ _append_resolution_run(+ input, report_id, triage=triage, redeliver_count=len(redeliver), skipped=skipped, overflow=overflow+ )+ _mark_queued_threads(input, triage, token=token, installation_id=installation_id)+acting_user_id = input.acting_user_idif acting_user_id is None:acting_user_id = _login_to_user_id(input.team_id, pr_metadata.author)@@ -251,14 +268,66 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResu)-def _delivery_auth(integration_row_id: int) -> tuple[str, str | None]:+def _append_resolution_run(+ input: ResolveThreadsInput,+ report_id: str,+ *,+ triage: list[ReviewThread],+ redeliver_count: int,+ skipped: int,+ overflow: int,+) -> None:+ """Open the run's progress anchor: the work-list artefact the UI and status comment count+ verdicts against. Best-effort — progress is a visibility feature, never worth failing the run.++ A retried prepare appends a fresh row for the remaining work-list (judged threads have skipped+ out by then), and the newest row wins at read time, so progress tracks the current attempt.+ """+ try:+ ReviewReportArtefact.append_resolution_run(+ team_id=input.team_id,+ report_id=report_id,+ content=ResolutionRunArtefact(+ total=len(triage),+ thread_ids=[thread.thread_id for thread in triage],+ redeliver=redeliver_count,+ skipped=skipped,+ overflow=overflow,+ ),+ attribution=ArtefactAttribution.system(),+ )+ except Exception:+ logger.exception("Could not append the resolution_run artefact; the run continues without progress")+++def _mark_queued_threads(+ input: ResolveThreadsInput, triage: list[ReviewThread], *, token: str, installation_id: str | None+) -> None:+ """👀 on each queued thread's opening comment: "in this run's queue", visible at a glance.++ Triage-queued threads only — settled, redeliver-only, and overflow threads get nothing, so the+ reaction doubles as the queue boundary. Best-effort per thread (a reaction must never fail or+ delay the run), and left in place afterwards: removal would double the API calls for no real+ gain, and GitHub no-ops a repeat addReaction so retries never stack duplicates.+ """+ for thread in triage:+ first = thread.first_comment+ if first is None or not first.node_id:+ continue+ try:+ add_eyes_reaction(token=token, subject_id=first.node_id, installation_id=installation_id)+ except Exception:+ logger.exception("Could not add the queued 👀 reaction on thread %s", thread.thread_id)+++def _delivery_auth(team_id: int, integration_row_id: int) -> tuple[str, str | None]:"""A fresh token from the run-pinned installation, without re-running the selection probe.The probe answers *which* installation, not *may we write* — GitHub enforces access on everycall — so a mid-run revocation surfaces as a 401/404 on the write itself, the same per-threadundelivered accounting the probe failure used to produce."""- github = GitHubIntegration(Integration.objects.get(id=integration_row_id))+ github = GitHubIntegration(Integration.objects.get(id=integration_row_id, team_id=team_id))return github.get_access_token(), github.github_installation_id@@ -295,7 +364,7 @@ def _deliver_side_effects(thread as undelivered — the reply is already persisted, so the next run's pre-filter redeliversjust the resolve."""- token, installation_id = _delivery_auth(integration_row_id)+ token, installation_id = _delivery_auth(input.team_id, integration_row_id)updated = verdictif updated.outcome == ThreadOutcome.FIXED.value and updated.commit_sha and updated.commit_verified is None:verified = commit_on_branch(@@ -412,7 +481,7 @@ def _append_run_note(input: ResolveThreadsInput, report_id: str, result: ResolutReviewReportArtefact.add_log(team_id=input.team_id,report_id=report_id,- content=NoteArtefact(note=note, author="review_hog_resolution"),+ content=NoteArtefact(note=note, author=RESOLUTION_RUN_NOTE_AUTHOR),attribution=ArtefactAttribution.system(),)except Exception:@@ -469,11 +538,32 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunRreturn preparedresult = ResolutionRunResult(report_id=prepared.report_id, skipped=prepared.skipped, overflow=prepared.overflow)+ total_queued = len(prepared.triage)++ async def refresh_status_section() -> None:+ # update_resolution_status_comment is best-effort by construction (it swallows and logs),+ # so this can be awaited bare at every call site.+ if not total_queued:+ return+ await database_sync_to_async(update_resolution_status_comment, thread_sensitive=False)(+ input.team_id,+ prepared.report_id,+ render_resolution_progress_section(+ done=sum(result.delivered_outcomes.values()),+ total=total_queued,+ fixed=result.delivered_outcomes.get(ThreadOutcome.FIXED.value, 0),+ left_for_you=result.delivered_outcomes.get(ThreadOutcome.ESCALATE.value, 0),+ ),+ integration_row_id=prepared.integration_row_id,+ )+final_attempt = activity.info().attempt >= RESOLUTION_MAX_ATTEMPTSsession: MultiTurnSession | None = Nonerun_ok = Falsetry:async with Heartbeater():+ # The section appears at 0/N before any turn runs, so a watcher sees the run exists.+ await refresh_status_section()# Redeliveries first: pure GitHub writes, no LLM — a crash mid-session must not leave# last run's judged threads undelivered behind this run's new turns.for _thread, verdict in prepared.redeliver:@@ -571,10 +661,14 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunRbranch=prepared.pr_metadata.head_branch,integration_row_id=prepared.integration_row_id,)+ result.delivered_outcomes[resolution.outcome.value] = (+ result.delivered_outcomes.get(resolution.outcome.value, 0) + 1+ )except Exception:# The verdict row still says reply_posted=False, so the next run redelivers.result.undelivered += 1logger.exception("Side effects failed for thread %s; the next run will retry", thread.thread_id)+ await refresh_status_section()run_ok = Trueexcept Exception:if final_attempt:@@ -583,6 +677,15 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunRawait database_sync_to_async(_idle_report, thread_sensitive=False)(input.team_id, prepared.report_id)except Exception:logger.exception("Could not idle report %s after the failed final attempt", prepared.report_id)+ # The PR-side half of the same promise: the status comment must not read as resolving+ # forever either (mirrors the review's fail_status_comment).+ if total_queued:+ await 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),+ integration_row_id=prepared.integration_row_id,+ )raisefinally:if session is not None:@@ -593,6 +696,17 @@ async def resolve_threads_activity(input: ResolveThreadsInput) -> ResolutionRunR)await database_sync_to_async(_append_run_note, thread_sensitive=False)(input, prepared.report_id, result)+ if total_queued:+ await database_sync_to_async(update_resolution_status_comment, thread_sensitive=False)(+ input.team_id,+ prepared.report_id,+ # 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.+ render_resolution_final_section(+ outcomes=result.delivered_outcomes, failed_turns=result.failed_turns + result.undelivered+ ),+ integration_row_id=prepared.integration_row_id,+ )await database_sync_to_async(_idle_report, thread_sensitive=False)(input.team_id, prepared.report_id)return result@@ -617,6 +731,46 @@ def _persist_turn_verdict_row(return verdict+@frozen+class FailResolutionInput:+ team_id: int+ owner: str+ repo: str+ pr_number: int+++def _fail_resolution(input: FailResolutionInput) -> None:+ report = (+ ReviewReport.objects.for_team(input.team_id)+ .filter(repository=f"{input.owner}/{input.repo}", pr_number=input.pr_number)+ .first()+ )+ if report is None:+ return+ _idle_report(input.team_id, str(report.id))+ state = resolution_states(input.team_id, [report]).get(str(report.id))+ if state is None:+ # No live run to report on: nothing was queued, the run already wrote its closing note, or+ # a newer review turn owns the row — so there is no stale "Resolving comments" section either.+ return+ update_resolution_status_comment(+ input.team_id,+ str(report.id),+ render_resolution_failed_section(done=state.done, total=state.total),+ )+++@scoped_temporal()+@close_db_connections+async def fail_resolution_activity(input: FailResolutionInput) -> None:+ """Terminal-failure cleanup the workflow fires when the resolution activity dies without+ reaching its own handler (a prepare failure, a timeout, cancellation, or worker death): return+ the report to rest and replace a stale "Resolving comments" section with the failed one, counted+ from the persisted work-list — the same derivation the UI row shows."""+ await database_sync_to_async(_fail_resolution, thread_sensitive=False)(input)++@temporalio.workflow.defn(name="resolve-pr")class ResolvePRWorkflow:"""Setup activities → the single long resolution-session activity. Deterministic id per PR."""@@ -644,22 +798,44 @@ class ResolvePRWorkflow:start_to_close_timeout=_QUICK_TIMEOUT,retry_policy=_RETRY,)- result: ResolutionRunResult = await workflow.execute_activity(- resolve_threads_activity,- ResolveThreadsInput(- team_id=inputs.team_id,- user_id=inputs.user_id,- acting_user_id=inputs.acting_user_id,- owner=inputs.owner,- repo=inputs.repo,- pr_number=inputs.pr_number,- pr_url=inputs.pr_url,- trigger_source=inputs.trigger_source,- ),- start_to_close_timeout=_RESOLUTION_TIMEOUT,- heartbeat_timeout=_RESOLUTION_HEARTBEAT,- retry_policy=_RESOLUTION_RETRY,- )+ try:+ result: ResolutionRunResult = await workflow.execute_activity(+ resolve_threads_activity,+ ResolveThreadsInput(+ team_id=inputs.team_id,+ user_id=inputs.user_id,+ acting_user_id=inputs.acting_user_id,+ owner=inputs.owner,+ repo=inputs.repo,+ pr_number=inputs.pr_number,+ pr_url=inputs.pr_url,+ trigger_source=inputs.trigger_source,+ ),+ start_to_close_timeout=_RESOLUTION_TIMEOUT,+ heartbeat_timeout=_RESOLUTION_HEARTBEAT,+ retry_policy=_RESOLUTION_RETRY,+ )+ except Exception:+ # The activity's own handler misses prepare failures, timeouts, cancellation, and worker+ # death — only this workflow-level cleanup survives those, so a dead run never reads as+ # resolving forever (mirrors the review workflow's fail_status_comment_activity).+ # Best-effort so the cleanup can never mask the original error.+ if workflow.patched("fail-resolution-cleanup-2026-08"):+ try:+ await workflow.execute_activity(+ fail_resolution_activity,+ FailResolutionInput(+ team_id=inputs.team_id,+ owner=inputs.owner,+ repo=inputs.repo,+ pr_number=inputs.pr_number,+ ),+ start_to_close_timeout=_FETCH_TIMEOUT,+ retry_policy=_RETRY,+ )+ except Exception:+ workflow.logger.warning("Could not run the resolution failure cleanup")+ raiseif result.skipped_reason:workflow.logger.info(f"Resolution stage skipped: {result.skipped_reason}")else:diff --git a/products/review_hog/backend/tests/test_inbox_trigger.py b/products/review_hog/backend/tests/test_inbox_trigger.pyindex cd0022f90ccc..56e3f61da007 100644--- a/products/review_hog/backend/tests/test_inbox_trigger.py+++ b/products/review_hog/backend/tests/test_inbox_trigger.py@@ -21,6 +21,7 @@ from products.tasks.backend.models import Task, TaskRun# receivers.py imports both at call time (startup-import-budget), so the defining modules are the# patch targets._START = "products.review_hog.backend.temporal.client.start_review_pr_workflow"+_WORKFLOW_RUNNING = "products.review_hog.backend.temporal.client.workflow_running"_STAMPHOG_QUEUE = "products.stamphog.backend.facade.tasks.queue_inbox_pr_review"# GitHub's own casing, as a real `output.pr_url` carries it. The task row lowercases its slug, so# this is what lets an assertion tell the task's repository apart from the PR URL's own claim.@@ -31,6 +32,11 @@ _HEAD_BRANCH = "posthog-code/fix-the-thing"class TestInboxTrigger(BaseTest):def setUp(self) -> None:super().setUp()+ # The PR leg now probes the busy-guard before starting; default it idle so the existing+ # cases exercise the review path without a live Temporal, and the busy case overrides it.+ busy_patcher = patch(_WORKFLOW_RUNNING, return_value=False)+ self.addCleanup(busy_patcher.stop)+ busy_patcher.start()self.signal_report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.IN_PROGRESS, signal_count=1, total_weight=1.0)@@ -175,6 +181,32 @@ class TestInboxTrigger(BaseTest):head_branch=_HEAD_BRANCH,)+ @patch(_START, return_value="wf-1")+ def test_pr_review_is_skipped_while_the_prs_resolution_is_running(self, mock_start) -> None:+ # Busy-guard: a published inbox review chains its own resolution, and a later TaskRun save+ # re-fires this receiver. Without the guard that second review races the resolution's pushes+ # and re-reviews threads it is mid-way through settling — the exact collision the endpoints+ # already refuse. The branch leg can't collide, so only the PR leg is guarded.+ self._mock_start = mock_start+ self._suggest_reviewers(["alice"])+ self._opt_in(self.alice)+ with patch(_WORKFLOW_RUNNING, return_value=True):+ self._record_output(self._run(self._task()), {"pr_url": _PR_URL})++ mock_start.assert_not_called()++ @patch(_START, return_value="wf-1")+ def test_branch_review_ignores_the_resolution_busy_guard(self, mock_start) -> None:+ # A branch-only target has no PR for a resolution to run against, so a "busy" probe must not+ # block it — the branch leg reviews regardless.+ self._mock_start = mock_start+ self._suggest_reviewers(["alice"])+ self._opt_in(self.alice)+ with patch(_WORKFLOW_RUNNING, return_value=True):+ self._record_output(self._run(self._task()), {"head_branch": _HEAD_BRANCH})++ mock_start.assert_called_once()+@patch(_START, return_value="wf-1")def test_run_creation_with_a_target_does_not_trigger(self, mock_start) -> None:# Creation saves are ignored: runs exist before the agent does anything, and a target on adiff --git a/products/review_hog/backend/tests/test_resolution_activity.py b/products/review_hog/backend/tests/test_resolution_activity.pyindex c05896078d52..fd5581b25eb4 100644--- a/products/review_hog/backend/tests/test_resolution_activity.py+++ b/products/review_hog/backend/tests/test_resolution_activity.py@@ -14,7 +14,7 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom products.review_hog.backend.models import ReviewReport, ReviewReportArtefact, ReviewSkillConfig-from products.review_hog.backend.reviewer.artefact_content import ThreadVerdictArtefact+from products.review_hog.backend.reviewer.artefact_content import ResolutionRunArtefact, ThreadVerdictArtefactfrom products.review_hog.backend.reviewer.constants import RESOLUTION_MAX_ATTEMPTSfrom products.review_hog.backend.reviewer.lazy_seed import sync_canonical_resolutionfrom products.review_hog.backend.reviewer.models.github_meta import PRMetadata@@ -23,15 +23,18 @@ from products.review_hog.backend.reviewer.persistence import load_thread_verdictfrom products.review_hog.backend.reviewer.skill_loader import REVIEW_HOG_RESOLUTION_SKILL_NAMEfrom products.review_hog.backend.reviewer.tools.github_threads import FixCommitInspection, ReviewThread, ThreadCommentfrom products.review_hog.backend.temporal.resolution import (+ FailResolutionInput,ResolutionRunResult,ResolveThreadsInput,_append_run_note,_append_task_run,_deliver_side_effects,+ _fail_resolution,_prepare_run,_PreparedRun,resolve_threads_activity,)+from products.signals.backend.artefact_attribution import ArtefactAttributionfrom products.skills.backend.models.skills import LLMSkillfrom products.tasks.backend.models import Task@@ -248,6 +251,7 @@ class TestResolutionPersistenceAndDelivery(BaseTest):patch(f"{_RESOLUTION}._installation_for", return_value=_mock_installation()),patch(f"{_RESOLUTION}._fetch_pr_metadata", return_value=_pr_metadata()),patch(f"{_RESOLUTION}.fetch_unresolved_threads", return_value=[thread]),+ patch(f"{_RESOLUTION}.add_eyes_reaction"),):return _prepare_run(ResolveThreadsInput(@@ -331,6 +335,44 @@ class TestResolutionPersistenceAndDelivery(BaseTest):# Restricted commits are real pushed commits: the restriction gates delivery, not the audit log.assert ReviewReportArtefact.objects.for_team(self.team.id).filter(report_id=report.id, type="commit").exists()+ def test_fail_resolution_idles_the_report_and_marks_where_it_stopped(self) -> None:+ # The workflow-level crash cleanup: it must count only delivered threads against the queued+ # work-list, and a crash before anything was queued must not edit (or create) a comment —+ # the create-on-demand path would post a spurious "stopped at 0/0" otherwise.+ report = self._report()+ ReviewReportArtefact.append_resolution_run(+ team_id=self.team.id,+ report_id=str(report.id),+ content=ResolutionRunArtefact(total=3, thread_ids=["PRRT_1", "PRRT_2", "PRRT_3"]),+ attribution=ArtefactAttribution.system(),+ )+ persist_thread_verdict(+ team_id=self.team.id,+ report_id=str(report.id),+ verdict=_verdict(outcome="fixed", reply_posted=True),+ )+ persist_thread_verdict(+ team_id=self.team.id,+ report_id=str(report.id),+ verdict=_verdict(thread_id="PRRT_2", outcome="fixed", reply_posted=False),+ )++ with patch(f"{_RESOLUTION}.update_resolution_status_comment") as status_comment:+ _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]++ # Crash before prepare queued anything: no run anchor, so no section to replace.+ report.pr_number = 124+ report.status = ReviewReport.Status.ACTIVE+ report.save(update_fields=["pr_number", "status"])+ ReviewReportArtefact.objects.for_team(self.team.id).filter(report_id=report.id).delete()+ with patch(f"{_RESOLUTION}.update_resolution_status_comment") as status_comment:+ _fail_resolution(FailResolutionInput(team_id=self.team.id, owner="posthog", repo="posthog", pr_number=124))+ assert ReviewReport.objects.for_team(self.team.id).get(id=report.id).status == ReviewReport.Status.IDLE+ assert status_comment.call_count == 0+def test_run_note_names_delivery_failures(self) -> None:# A token-expiry tail must be visible in the durable run note, not just worker logs.report = self._report()@@ -395,6 +437,80 @@ class TestResolutionPersistenceAndDelivery(BaseTest):assert report.status == ReviewReport.Status.IDLEnote = ReviewReportArtefact.objects.for_team(self.team.id).get(report_id=report.id, type="note")assert "0 thread(s) triaged" in note.content+ # No queued threads means no progress anchor — a total=0 run artefact would render this+ # clean no-op as a crashed run once it aged past the staleness window.+ assert (+ not ReviewReportArtefact.objects.for_team(self.team.id)+ .filter(report_id=report.id, type="resolution_run")+ .exists()+ )++ def _prepare_with(self, threads: list[ReviewThread], eyes: Mock | None = None) -> object:+ eyes = eyes if eyes is not None else Mock()+ with (+ patch(f"{_RESOLUTION}._installation_for", return_value=_mock_installation()),+ patch(f"{_RESOLUTION}._fetch_pr_metadata", return_value=_pr_metadata()),+ patch(f"{_RESOLUTION}.fetch_unresolved_threads", return_value=threads),+ patch(f"{_RESOLUTION}.add_eyes_reaction", eyes),+ patch(+ f"{_RESOLUTION}.load_resolution_skill_for_run",+ return_value=Mock(skill_name="review-hog-resolution-criteria", version=1),+ ),+ ):+ return _prepare_run(self._input())++ def test_prepare_anchors_the_run_and_marks_only_queued_threads(self) -> None:+ # The run's progress anchor must list exactly the queued threads (progress counts verdicts+ # against it, so a settled thread in the list would read as forever-unfinished work), and+ # the 👀 queue marker must skip settled threads for the same reason.+ report = self._report()+ queued = ReviewThread(+ thread_id="PRRT_1",+ path="f.py",+ comments=[ThreadComment(id=1, node_id="PRRC_1", author_login="greptile", author_is_bot=True, body="b")],+ )+ settled = ReviewThread(+ thread_id="PRRT_2",+ path="f.py",+ comments=[ThreadComment(id=100, node_id="PRRC_2", author_login="greptile", author_is_bot=True, body="b")],+ )+ persist_thread_verdict(+ team_id=self.team.id,+ report_id=str(report.id),+ verdict=_verdict("PRRT_2", outcome="wont_fix", reply_posted=True, resolved=True, commit_sha=None),+ )+ eyes = Mock()++ prepared = self._prepare_with([queued, settled], eyes)++ assert isinstance(prepared, _PreparedRun)+ run_artefact = ReviewReportArtefact.objects.for_team(self.team.id).get(+ report_id=report.id, type="resolution_run"+ )+ content = json.loads(run_artefact.content)+ assert content["total"] == 1+ assert content["thread_ids"] == ["PRRT_1"]+ assert content["skipped"] == 1+ assert eyes.call_args_list == [((), {"token": "token", "subject_id": "PRRC_1", "installation_id": "inst-1"})]++ def test_reaction_failure_never_fails_prepare(self) -> None:+ # A GitHub flake on the cosmetic queue marker must not cost the run (or the progress anchor,+ # which is written first).+ report = self._report()+ thread = ReviewThread(+ thread_id="PRRT_1",+ path="f.py",+ comments=[ThreadComment(id=1, node_id="PRRC_1", author_login="greptile", author_is_bot=True, body="b")],+ )++ prepared = self._prepare_with([thread], Mock(side_effect=RuntimeError("github flake")))++ assert isinstance(prepared, _PreparedRun)+ assert (+ ReviewReportArtefact.objects.for_team(self.team.id)+ .filter(report_id=report.id, type="resolution_run")+ .exists()+ )class TestFailedRunActivity(NonAtomicBaseTest):@@ -430,6 +546,7 @@ class TestFailedRunActivity(NonAtomicBaseTest):patch(f"{_RESOLUTION}._delivery_auth", return_value=("token", "inst-1")),patch(f"{_RESOLUTION}._fetch_pr_metadata", return_value=_pr_metadata()),patch(f"{_RESOLUTION}.fetch_unresolved_threads", return_value=threads),+ patch(f"{_RESOLUTION}.add_eyes_reaction"),patch(f"{_RESOLUTION}.load_resolution_skill_for_run",return_value=Mock(skill_name="review-hog-resolution-criteria", version=1),@@ -489,3 +606,29 @@ class TestFailedRunActivity(NonAtomicBaseTest):assert result.outcomes == {"wont_fix": 1}assert result.failed_turns == 2assert self._report_status() == ReviewReport.Status.IDLE++ def test_undelivered_thread_never_counts_as_settled_in_the_status_comment(self) -> None:+ # A judged thread whose GitHub writes failed has no reply on the PR — the progress line and+ # the closing tally must not claim it as done/declined; it lands in "couldn't handle" instead.+ mock_activity = Mock()+ mock_activity.info.return_value.attempt = 1+ session = Mock()+ session.task_run.task_id = "11111111-1111-1111-1111-111111111111"+ session.task_run.id = "run-1"+ res = ThreadResolution(thread_id="PRRT_A", outcome="wont_fix", reasoning="checked", reply="declined")+ with ExitStack() as stack:+ for p in self._base_patches(mock_activity, [self._thread("PRRT_A")]):+ stack.enter_context(p)+ stack.enter_context(patch(f"{_RESOLUTION}.start_sandbox_session", AsyncMock(return_value=(session, res))))+ stack.enter_context(patch(f"{_RESOLUTION}.end_sandbox_session", AsyncMock()))+ stack.enter_context(patch(f"{_RESOLUTION}.reply_to_thread", side_effect=RuntimeError("token expired")))+ status_comment = stack.enter_context(patch(f"{_RESOLUTION}.update_resolution_status_comment"))++ result = async_to_sync(resolve_threads_activity)(self._input())++ assert result.outcomes == {"wont_fix": 1}+ assert result.delivered_outcomes == {}+ assert result.undelivered == 1+ final_section = status_comment.call_args.args[2]+ assert "couldn't handle 1" in final_section+ assert "declined" not in final_sectiondiff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.pyindex 1ba37948e3d1..383200cb5cb7 100644--- a/products/review_hog/backend/tests/test_reviews_api.py+++ b/products/review_hog/backend/tests/test_reviews_api.py@@ -14,7 +14,9 @@ from products.review_hog.backend.api.reviews import IN_PROGRESS_STALE_AFTERfrom products.review_hog.backend.models import ReviewReport, ReviewReportArtefactfrom products.review_hog.backend.reviewer.artefact_content import (FindingOutcomeArtefact,+ ResolutionRunArtefact,ReviewIssueFinding,+ ThreadVerdictArtefact,ValidationVerdict,)from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRMetadata@@ -30,7 +32,9 @@ from products.review_hog.backend.reviewer.persistence import (persist_perspective_selection,persist_pr_snapshot,)+from products.review_hog.backend.reviewer.progress import RESOLUTION_RUN_NOTE_AUTHORfrom products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.artefact_schemas import NoteArtefactdef _pr_metadata(head_sha: str, title: str) -> PRMetadata:@@ -493,6 +497,114 @@ class TestRecentReviewsAPI(APIBaseTest):"total": 2,}+ def _resolution_run(self, report: ReviewReport, thread_ids: list[str], *, skipped: int = 0) -> None:+ ReviewReportArtefact.append_resolution_run(+ team_id=self.team.id,+ report_id=str(report.id),+ content=ResolutionRunArtefact(total=len(thread_ids), thread_ids=thread_ids, skipped=skipped),+ attribution=ArtefactAttribution.system(),+ )++ def _thread_verdict(self, report: ReviewReport, thread_id: str, outcome: str, *, delivered: bool = True) -> None:+ ReviewReportArtefact.append_thread_verdict(+ team_id=self.team.id,+ report_id=str(report.id),+ content=ThreadVerdictArtefact(+ thread_id=thread_id, outcome=outcome, reasoning="r", reply="reply", reply_posted=delivered+ ),+ attribution=ArtefactAttribution.system(),+ )++ def _closing_run_note(self, report: ReviewReport) -> None:+ ReviewReportArtefact.add_log(+ team_id=self.team.id,+ report_id=str(report.id),+ content=NoteArtefact(note="Resolution run on PR #5: done", author=RESOLUTION_RUN_NOTE_AUTHOR),+ attribution=ArtefactAttribution.system(),+ )++ def test_resolving_report_shows_resolution_progress_not_a_review_stage(self) -> None:+ # The prod mislabel this feature fixes: a chained resolution kept the report ACTIVE with+ # fresh artefacts, so the row inferred a review stage from the COMPLETED turn's working+ # state and rendered "Re-reviewing · Merging overlapping findings". A resolving report must+ # carry resolution progress instead, counting only this run's queued threads — not a+ # redelivered foreign verdict, not a previous run's verdict for a re-queued thread, and not+ # a judged thread whose GitHub writes haven't landed.+ report = self._report(pr_number=5, acting_user=self.user, status=ReviewReport.Status.ACTIVE)+ with freeze_time(timezone.now() - timedelta(hours=1)):+ # A previous run already judged PRRT_3; a new comment re-queued it, so only a verdict+ # written during THIS run may count toward its progress.+ self._thread_verdict(report, "PRRT_3", "fixed")+ self._resolution_run(report, ["PRRT_1", "PRRT_2", "PRRT_3"])+ self._thread_verdict(report, "PRRT_1", "fixed")+ self._thread_verdict(report, "PRRT_2", "escalate")+ # A prior run's redelivery (thread not queued this run) also appends a row mid-run.+ self._thread_verdict(report, "PRRT_X", "fixed")+ # Judged but its GitHub reply failed — no reply on the thread yet, so it must not count.+ self._thread_verdict(report, "PRRT_3", "fixed", delivered=False)++ row = self.client.get(self.url).json()["results"][0]++ assert row["in_progress"] is True+ assert row["progress"] is None+ assert row["resolution"] == {+ "resolution_status": "resolving",+ "done": 2,+ "total": 3,+ "fixed": 1,+ "needs_attention": 1,+ }++ @parameterized.expand(+ [+ ("completed_run_via_closing_note",),+ ("superseded_by_newer_review_turn",),+ ]+ )+ def test_finished_or_superseded_resolution_carries_no_state(self, scenario: str) -> None:+ # A completed run must not render as crashed once it ages past the staleness window (the+ # closing note is the completion marker), and a crashed run must yield the row to a newer+ # review turn's own progress instead of pinning a stale "didn't finish" on it.+ report = self._report(pr_number=5, acting_user=self.user, status=ReviewReport.Status.ACTIVE, head_sha="sha1")+ with freeze_time(timezone.now() - timedelta(hours=2)):+ self._resolution_run(report, ["PRRT_1"])+ self._thread_verdict(report, "PRRT_1", "fixed")+ if scenario == "completed_run_via_closing_note":+ self._closing_run_note(report)+ if scenario == "superseded_by_newer_review_turn":+ persist_pr_snapshot(+ team_id=self.team.id,+ report_id=str(report.id),+ head_sha="sha1",+ pr_metadata=_pr_metadata("sha1", "next turn"),+ pr_comments=[],+ pr_files=[],+ )++ row = self.client.get(self.url).json()["results"][0]++ assert row["resolution"] is None++ def test_dead_resolution_run_shows_where_it_stopped(self) -> None:+ # The silent-death mode: a resolution that dies partway used to leave no trace anywhere.+ # With the run anchor present, no closing note, and activity past the staleness window, the+ # row must say where it stopped instead of nothing.+ with freeze_time(timezone.now() - timedelta(hours=2)):+ report = self._report(pr_number=5, acting_user=self.user, status=ReviewReport.Status.IDLE)+ self._resolution_run(report, ["PRRT_1", "PRRT_2", "PRRT_3"])+ self._thread_verdict(report, "PRRT_1", "fixed")++ row = self.client.get(self.url).json()["results"][0]++ assert row["in_progress"] is False+ assert row["resolution"] == {+ "resolution_status": "stopped",+ "done": 1,+ "total": 3,+ "fixed": 1,+ "needs_attention": 0,+ }+def test_publish_window_stays_in_progress_and_reads_finalizing(self) -> None:# On publishing runs finalize bumps run_count but defers the idle write to the publish# stage, so the report is briefly ACTIVE with no in-flight findings. The row must keep@@ -513,7 +625,8 @@ class TestRecentReviewsAPI(APIBaseTest):assert row["progress"] == {"review_stage": "finalizing", "done": None, "total": None}# A resolution run holds the same ACTIVE-at-completed-head shape but with the head already- # published — that window keeps its pre-existing label (relabeling it is a separate change).+ # published — that window keeps its pre-existing label until the run's `resolution_run`+ # artefact lands, at which point the row carries `resolution` instead.ReviewReport.objects.for_team(self.team.id).filter(id=report.id).update(published_head_sha="sha1")row = self.client.get(self.url).json()["results"][0]assert row["in_progress"] is Truediff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.pyindex 0c6bccb4c9af..c588b5adfeb6 100644--- a/products/review_hog/backend/tests/test_status_comment.py+++ b/products/review_hog/backend/tests/test_status_comment.py@@ -14,14 +14,19 @@ from products.review_hog.backend.reviewer.models.issue_validation import IssueVafrom products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRangefrom products.review_hog.backend.reviewer.persistence import persist_findings, persist_verdict, upsert_review_reportfrom products.review_hog.backend.reviewer.status_comment import (+ RESOLUTION_SECTION_START,FinalizeStatusCommentInput,+ _splice_resolution_section,ensure_status_comment,fail_status_comment,finalize_status_comment,maybe_refresh_status_comment,render_final_body,render_in_progress_body,+ render_resolution_final_section,+ render_resolution_progress_section,status_marker,+ update_resolution_status_comment,)from products.review_hog.backend.temporal.activities import _fail_run@@ -383,6 +388,144 @@ class TestFinalizeStatusComment(BaseTest):assert "couldn't finish this review" in body+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++ 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++ def test_final_section_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(+ 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+++@patch(_INTEGRATION)+@patch(_PAGINATED)+@patch(_REQUEST)+class TestUpdateResolutionStatusComment(BaseTest):+ def _report(self) -> ReviewReport:+ report_id = upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata())+ return ReviewReport.objects.for_team(self.team.id).get(id=report_id)++ def test_standalone_run_creates_the_comment_on_demand(+ self, mock_request: MagicMock, mock_paginated: MagicMock, mock_integration: MagicMock+ ) -> None:+ # A standalone resolution targets a PR that never got a review comment — without the+ # create-on-demand path the run has no GitHub-visible progress at all.+ _wire_auth(mock_integration)+ mock_paginated.return_value = iter([])+ mock_request.return_value.json.return_value = {"id": 888}+ 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)+ )++ 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 status_marker(str(report.id)) in posted.kwargs["json"]["body"]+ report.refresh_from_db()+ assert report.status_comment_id == 888++ def test_chained_run_extends_the_existing_review_comment(+ self, mock_request: MagicMock, mock_paginated: MagicMock, mock_integration: MagicMock+ ) -> None:+ # One ReviewHog voice per PR: the resolution section lands inside the review's comment via+ # edit (no new comment, no notification), with the review's own body preserved above it.+ _wire_auth(mock_integration)+ report = self._report()+ report.status_comment_id = 777+ report.save(update_fields=["status_comment_id"])+ get_response = MagicMock()+ get_response.json.return_value = {"body": "### reviewed\n\n" + status_marker(str(report.id))}+ 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)+ )++ 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++ def test_empty_existing_body_keeps_the_marker_for_recovery(+ self, mock_request: MagicMock, mock_paginated: MagicMock, mock_integration: MagicMock+ ) -> None:+ # An empty existing comment body must not drop the status marker: if status_comment_id is+ # ever lost, _find_marker_comment re-adopts the comment by that marker, so the spliced body+ # has to carry it even when there is nothing to splice into (else recovery posts a duplicate).+ _wire_auth(mock_integration)+ report = self._report()+ report.status_comment_id = 777+ report.save(update_fields=["status_comment_id"])+ get_response = MagicMock()+ get_response.json.return_value = {"body": ""}+ 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)+ )++ assert _patches(mock_request) == ["/repos/o/r/issues/comments/777"]+ patched = mock_request.call_args_list[1].kwargs["json"]["body"]+ assert status_marker(str(report.id)) in patched++ @patch(f"{_MODULE}.Integration")+ def test_pinned_integration_row_skips_the_selection_probe(+ self,+ mock_integration_model: MagicMock,+ mock_request: MagicMock,+ mock_paginated: MagicMock,+ mock_integration: MagicMock,+ ) -> None:+ # A resolution run pins its installation once and refreshes after every thread; passing the+ # pinned row must re-mint the token from it, never re-run first_for_team_repository (a+ # GET /repos/... per integration tried) on each refresh.+ mock_integration.return_value.get_access_token.return_value = "tok"+ mock_integration.return_value.github_installation_id = "inst-1"+ report = self._report()+ report.status_comment_id = 777+ report.save(update_fields=["status_comment_id"])+ get_response = MagicMock()+ get_response.json.return_value = {"body": "### reviewed\n\n" + status_marker(str(report.id))}+ 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),+ integration_row_id=42,+ )++ mock_integration.first_for_team_repository.assert_not_called()+ mock_integration_model.objects.get.assert_called_once_with(id=42, team_id=self.team.id)+ assert _patches(mock_request) == ["/repos/o/r/issues/comments/777"]++class TestFailRun(BaseTest):def test_returns_the_report_to_rest_even_without_a_status_comment(self) -> None:# Publishing runs defer finalize's idle write to the publish stage, so the failure path mustdiff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.pyindex c05685e6e01e..c162175e1ae7 100644--- a/products/review_hog/backend/tests/test_temporal_workflow.py+++ b/products/review_hog/backend/tests/test_temporal_workflow.py@@ -27,6 +27,7 @@ from products.review_hog.backend.temporal.activities import (AppendCodeReviewArtefactInput,BuildBodyInput,DedupResult,+ GenerateSchemasInput,LoadBlindSpotsInput,LoadedBlindSpotsSkillDTO,LoadedPerspectiveDTO,@@ -40,9 +41,17 @@ from products.review_hog.backend.temporal.activities import (ReviewChunkInput,ReviewMeta,SelectPerspectivesInput,+ SyncReviewSkillsInput,TrackReviewFailedInput,ValidateChunkInput,ValidateChunkResult,+ ValidateIntegrationInput,+)+from products.review_hog.backend.temporal.resolution import (+ FailResolutionInput,+ ResolutionRunResult,+ ResolvePRWorkflow,+ ResolveThreadsInput,)from products.review_hog.backend.temporal.types import (ResolvePRWorkflowInputs,@@ -763,3 +772,52 @@ async def test_validate_issues_workflow_fails_above_failure_floor():with pytest.raises(WorkflowFailureError):await _run_validate_workflow(issue_ids=["1-1-1", "1-2-1"], validate_chunk=validate_chunk)+++async def test_resolve_pr_workflow_runs_the_failure_cleanup_on_a_dead_resolution():+ # The resolution activity's own failure handler misses prepare failures, timeouts, and worker+ # death — the workflow-level cleanup is the only thing standing between those and a PR comment+ # stuck on "Resolving comments" forever. It must fire on terminal failure and never on success.+ cleanup_calls: list[int] = []++ @activity.defn(name="validate_github_integration_activity")+ async def validate_integration(input: ValidateIntegrationInput) -> None:+ return None++ @activity.defn(name="sync_review_skills_activity")+ async def sync_skills(input: SyncReviewSkillsInput) -> None:+ return None++ @activity.defn(name="generate_schemas_activity")+ async def generate_schemas(input: GenerateSchemasInput) -> None:+ return None++ @activity.defn(name="resolve_threads_activity")+ async def resolve_threads(input: ResolveThreadsInput) -> ResolutionRunResult:+ raise ApplicationError("prepare exploded", non_retryable=True)++ @activity.defn(name="fail_resolution_activity")+ async def fail_resolution(input: FailResolutionInput) -> None:+ cleanup_calls.append(input.pr_number)++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[ResolvePRWorkflow],+ activities=[validate_integration, sync_skills, generate_schemas, resolve_threads, fail_resolution],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ with pytest.raises(WorkflowFailureError):+ await env.client.execute_workflow(+ ResolvePRWorkflow.run,+ ResolvePRWorkflowInputs(+ team_id=1, user_id=2, acting_user_id=2, pr_url="u", owner="o", repo="r", pr_number=7+ ),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert cleanup_calls == [7]diff --git a/products/review_hog/backend/tests/test_trigger_api.py b/products/review_hog/backend/tests/test_trigger_api.pyindex bdffeb5dcc64..eb1cf95f5ca2 100644--- a/products/review_hog/backend/tests/test_trigger_api.py+++ b/products/review_hog/backend/tests/test_trigger_api.py@@ -12,7 +12,10 @@ from posthog.models.team import Teamfrom posthog.models.user import UserTRIGGER_URL = "/api/review_hog/trigger/"+RESOLVE_URL = "/api/review_hog/resolve/"_START = "products.review_hog.backend.api.trigger.start_review_pr_workflow"+_START_RESOLUTION = "products.review_hog.backend.api.trigger.start_resolution_workflow"+_BUSY = "products.review_hog.backend.api.trigger.workflow_running"@override_settings(REVIEWHOG_TRIGGER_TOKEN="secret-token")@@ -29,6 +32,10 @@ class TestReviewHogTriggerApi(APIBaseTest):REVIEWHOG_RUN_USER_ID=self.run_user.id,)self._settings_ctx.enable()+ # The busy-guard probes Temporal on every trigger; tests must never open real connections.+ busy_patcher = patch(_BUSY, return_value=False)+ self.mock_busy = busy_patcher.start()+ self.addCleanup(busy_patcher.stop)def tearDown(self):self._settings_ctx.disable()@@ -178,6 +185,40 @@ class TestReviewHogTriggerApi(APIBaseTest):self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)self.assertEqual(mock_start.call_args.kwargs["user_id"], self.user.id)+ @patch(_START, return_value="wf-1")+ def test_trigger_refused_while_resolution_is_running(self, mock_start):+ # The busy-guard: a review started while the PR's resolve-pr workflow runs would race the+ # resolution session's pushes and re-review threads it is mid-way through settling. Temporal+ # can't dedupe across the two workflow ids, so a dropped (or wrong-id) probe here means+ # double runs — the check must hit resolve-pr's exact deterministic id and refuse.+ self.mock_busy.return_value = True+ resp = self.client.post(+ TRIGGER_URL,+ {"repo": "PostHog/posthog", "pr_number": 123},+ format="json",+ HTTP_AUTHORIZATION="Bearer secret-token",+ )+ self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT)+ self.assertIn("Still resolving comments", resp.json()["error"])+ self.mock_busy.assert_called_once_with(f"resolve-pr:{self.trigger_team.id}:posthog/posthog:123")+ mock_start.assert_not_called()++ @patch(_START_RESOLUTION, return_value="wf-r-1")+ def test_resolve_refused_while_review_is_running(self, mock_start_resolution):+ # The other direction: a standalone resolution during a live review would settle threads+ # the finishing review is about to chain its own resolution for.+ self.mock_busy.return_value = True+ resp = self.client.post(+ RESOLVE_URL,+ {"repo": "PostHog/posthog", "pr_number": 123},+ format="json",+ HTTP_AUTHORIZATION="Bearer secret-token",+ )+ self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT)+ self.assertIn("review is already running", resp.json()["error"])+ self.mock_busy.assert_called_once_with(f"review-pr:{self.trigger_team.id}:posthog/posthog:123")+ mock_start_resolution.assert_not_called()+@parameterized.expand([("deactivated", True),diff --git a/products/review_hog/backend/tests/test_ui_trigger_api.py b/products/review_hog/backend/tests/test_ui_trigger_api.pyindex 8fb7a2ad0263..d2d4f355ab6d 100644--- a/products/review_hog/backend/tests/test_ui_trigger_api.py+++ b/products/review_hog/backend/tests/test_ui_trigger_api.py@@ -15,6 +15,7 @@ _START = "products.review_hog.backend.api.reviews.start_review_pr_workflow"_START_RESOLUTION = "products.review_hog.backend.api.reviews.start_resolution_workflow"_ACCESS = "products.review_hog.backend.api.reviews.GitHubIntegration.first_for_team_repository"_META = "products.review_hog.backend.api.reviews._fetch_pr_metadata"+_BUSY = "products.review_hog.backend.api.reviews.workflow_running"def _pr_meta(**overrides: object) -> MagicMock:@@ -29,6 +30,13 @@ class TestReviewHogUiTriggerApi(APIBaseTest):# The settings GET below resolves stamphog_connected off the stamphog product DB.databases = {"default", "stamphog_db_writer", "stamphog_db_reader"}+ def setUp(self) -> None:+ super().setUp()+ # The busy-guard probes Temporal on every trigger; tests must never open real connections.+ busy_patcher = patch(_BUSY, return_value=False)+ self.mock_busy = busy_patcher.start()+ self.addCleanup(busy_patcher.stop)+def _trigger(self, pr_url: str, run_mode: str | None = None):body: dict[str, str] = {"pr_url": pr_url}if run_mode is not None:@@ -108,6 +116,41 @@ class TestReviewHogUiTriggerApi(APIBaseTest):trigger_source="ui",)+ @parameterized.expand(+ [+ # (name, run_mode, probed_workflow_id_prefix, error_fragment)+ ("review_blocked_by_running_resolution", None, "resolve-pr", "Still resolving comments"),+ ("resolve_only_blocked_by_running_review", "resolve_only", "review-pr", "review is already running"),+ ]+ )+ @patch(_META, return_value=_pr_meta())+ @patch(_ACCESS, return_value=object())+ @patch(_START_RESOLUTION)+ @patch(_START)+ def test_busy_guard_refuses_the_cross_stage_start(+ self,+ _name,+ run_mode,+ probed_prefix,+ error_fragment,+ mock_start,+ mock_start_resolution,+ _mock_access,+ _mock_meta,+ ):+ # The busy-guard: Temporal joins same-id starts, but review-pr and resolve-pr are different+ # ids, so a dropped (or wrong-id) probe means a review racing the resolution session's+ # pushes — the incident class this refusal exists for. Blocked, not queued.+ self.mock_busy.return_value = True+ with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode=run_mode)++ self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT, resp.content)+ self.assertIn(error_fragment, resp.json()["error"])+ self.mock_busy.assert_called_once_with(f"{probed_prefix}:{self.team.id}:posthog/posthog.com:123")+ mock_start.assert_not_called()+ mock_start_resolution.assert_not_called()+@patch(_ACCESS, return_value=object())@patch(_START_RESOLUTION)@patch(_START)diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsxindex 702d8e85079a..6944e0c74de7 100644--- a/products/review_hog/frontend/CodeReviewScene.tsx+++ b/products/review_hog/frontend/CodeReviewScene.tsx@@ -53,6 +53,7 @@ import type {ReviewIssuePriorityEnumApi,ReviewPerspectiveStatItemApi,ReviewRecentReviewApi,+ ReviewResolutionStatusApi,UrgencyThresholdEnumApi,} from 'products/review_hog/frontend/generated/api.schemas'import {@@ -398,6 +399,17 @@ function progressLabel(review: ReviewRecentReviewApi): string {}}+/** The live resolution run's row label, e.g. "Resolving comments · 6/10 · 5 fixed, 1 needs you". */+function resolutionLabel(resolution: ReviewResolutionStatusApi): string {+ const outcomes = [+ resolution.fixed > 0 ? `${resolution.fixed} fixed` : null,+ resolution.needs_attention > 0+ ? `${resolution.needs_attention} need${resolution.needs_attention === 1 ? 's' : ''} you`+ : null,+ ].filter(Boolean)+ return `Resolving comments · ${resolution.done}/${resolution.total}${outcomes.length ? ` · ${outcomes.join(', ')}` : ''}`+}+/** A first review still running: no findings to expand into yet, just the live stage. */function RunningReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.Element {const { reviewsScope } = useValues(reviewHogSettingsLogic)@@ -421,7 +433,11 @@ function RunningReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.El</>)}<span className="text-tertiary">·</span>- <span className="whitespace-nowrap font-medium text-warning">{progressLabel(review)}</span>+ <span className="whitespace-nowrap font-medium text-warning">+ {review.resolution?.resolution_status === 'resolving'+ ? resolutionLabel(review.resolution)+ : progressLabel(review)}+ </span></div></div><LemonButton size="small" type="secondary" to={review.github_url} targetBlank sideIcon={<IconExternal />}>@@ -459,11 +475,19 @@ function RecentReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.Ele<div className="min-w-0 flex-1"><div className="flex items-center gap-2"><span className="truncate text-sm font-semibold">{reviewTitle(review)}</span>- {review.in_progress && (+ {review.resolution?.resolution_status === 'resolving' ? (+ <LemonTag type="warning" size="small" className="inline-flex items-center gap-1">+ <Spinner className="text-xs" /> {resolutionLabel(review.resolution)}+ </LemonTag>+ ) : review.in_progress ? (<LemonTag type="warning" size="small" className="inline-flex items-center gap-1"><Spinner className="text-xs" /> Re-reviewing · {progressLabel(review)}</LemonTag>- )}+ ) : review.resolution?.resolution_status === 'stopped' ? (+ <LemonTag type="muted" size="small">+ Resolution didn't finish · stopped at {review.resolution.done}/{review.resolution.total}+ </LemonTag>+ ) : null}{!review.published && (<LemonTag type="muted" size="small">Not published@@ -657,13 +681,16 @@ function RecentReviewsSection(): JSX.Element | null {* in alpha).*/function TriggerReviewSection(): JSX.Element | null {- const { settings, triggerPrUrl, triggeringReview } = useValues(reviewHogSettingsLogic)+ const { settings, triggerPrUrl, triggeringReview, triggerUrlResolving } = useValues(reviewHogSettingsLogic)const { setTriggerPrUrl, submitTriggerReview } = useActions(reviewHogSettingsLogic)if (!settings?.can_trigger_reviews) {return null}const noUrlReason = !triggerPrUrl.trim() ? 'Paste a pull request URL first' : undefined+ // Mirrors the server-side busy-guard for PRs visible in the list; pasted URLs outside it still+ // get the same refusal from the trigger endpoint.+ const resolvingReason = triggerUrlResolving ? 'Still resolving comments from the last review' : undefinedconst inFlightReason = triggeringReview ? 'A run is already starting…' : undefinedreturn (<section className="flex flex-col gap-4">@@ -688,10 +715,10 @@ function TriggerReviewSection(): JSX.Element | null {type="primary"htmlType="submit"loading={triggeringReview}- disabledReason={noUrlReason}+ disabledReason={noUrlReason ?? resolvingReason}sideAction={{icon: <IconChevronDown />,- disabledReason: noUrlReason ?? inFlightReason,+ disabledReason: noUrlReason ?? resolvingReason ?? inFlightReason,dropdown: {placement: 'bottom-end',overlay: (diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.tsindex d0bc65192be7..0c088b5e79e0 100644--- a/products/review_hog/frontend/generated/api.schemas.ts+++ b/products/review_hog/frontend/generated/api.schemas.ts@@ -99,6 +99,33 @@ export interface ReviewProgressApi {total: number | null}+/**+ * * `resolving` - resolving+ * * `stopped` - stopped+ */+export type ResolutionStatusEnumApi = (typeof ResolutionStatusEnumApi)[keyof typeof ResolutionStatusEnumApi]++export const ResolutionStatusEnumApi = {+ Resolving: 'resolving',+ Stopped: 'stopped',+} as const++export interface ReviewResolutionStatusApi {+ /** Where the run stands: `resolving` while threads are being settled, `stopped` when the run died partway (went quiet with no closing summary).+ *+ * * `resolving` - resolving+ * * `stopped` - stopped */+ resolution_status: ResolutionStatusEnumApi+ /** Queued threads settled so far this run. */+ done: number+ /** Threads queued for this run. */+ total: number+ /** Settled threads that were fixed with a commit to the branch. */+ fixed: number+ /** Settled threads left for the author: judged worth doing but not safe to fix unattended. */+ needs_attention: number+}+export interface ReviewRecentReviewApi {/** The review report's id, for fetching the review's detail. */id: string@@ -147,10 +174,12 @@ export interface ReviewRecentReviewApi {last_run_at: string | null/** Whether a review has been published back to GitHub. */published: boolean- /** Whether a review turn is running on this report right now (activity within the last 30 minutes). */+ /** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */in_progress: boolean- /** The in-flight turn's stage and counters; null unless `in_progress`. */+ /** The in-flight review turn's stage and counters; null unless a review turn is running (a resolving report carries `resolution` instead). */progress: ReviewProgressApi | null+ /** The report's latest resolution run (settling the PR's review threads): live progress while it runs, or where it stopped when it died partway. Null when there is none, it completed, or a newer review turn superseded it. */+ resolution: ReviewResolutionStatusApi | null/** The latest turn's valid findings at must_fix effective priority. */must_fix_count: number/** The latest turn's valid findings at should_fix effective priority. */@@ -360,10 +389,12 @@ export interface ReviewDetailApi {last_run_at: string | null/** Whether a review has been published back to GitHub. */published: boolean- /** Whether a review turn is running on this report right now (activity within the last 30 minutes). */+ /** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */in_progress: boolean- /** The in-flight turn's stage and counters; null unless `in_progress`. */+ /** The in-flight review turn's stage and counters; null unless a review turn is running (a resolving report carries `resolution` instead). */progress: ReviewProgressApi | null+ /** The report's latest resolution run (settling the PR's review threads): live progress while it runs, or where it stopped when it died partway. Null when there is none, it completed, or a newer review turn superseded it. */+ resolution: ReviewResolutionStatusApi | null/** The latest turn's valid findings at must_fix effective priority. */must_fix_count: number/** The latest turn's valid findings at should_fix effective priority. */diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.tsindex e410f4b7bdc4..bca1d460d9ca 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts@@ -151,6 +151,15 @@ function currentProjectId(): string {return String(teamLogic.values.currentTeamId)}+/** "https://github.com/Org/Repo/pull/123/files" → "org/repo/123"; null when not a PR URL. */+function parsePrPath(url: string): string | null {+ const match = url+ .trim()+ .toLowerCase()+ .match(/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/)+ return match ? `${match[1]}/${match[2]}/${match[3]}` : null+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface reviewHogSettingsLogicValues {awaitingTriggeredReview: boolean@@ -187,6 +196,7 @@ export interface reviewHogSettingsLogicValues {settingsLoading: booleanskillDrawerOpen: booleantriggerPrUrl: string+ triggerUrlResolving: booleantriggeringReview: booleanvalidators: ReviewValidatorConfigApi[] | nullvalidatorsLoading: boolean@@ -443,6 +453,7 @@ export interface reviewHogSettingsLogicMeta {reviewDetail: ReviewDetailApi | null,settings: ReviewUserSettingsApi | null) => ReviewFindingsSplit | null+ triggerUrlResolving: (triggerPrUrl: string, recentReviews: ReviewRecentReviewApi[] | null) => booleanperspectiveScoreboard: (reviewDetail: ReviewDetailApi | null) => PerspectiveScore[] | null}}@@ -845,6 +856,22 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([}},],+ // Mirrors the server-side busy-guard for PRs the list already shows, so the trigger button+ // explains the refusal up front instead of surfacing it as a submit error.+ triggerUrlResolving: [+ (s) => [s.triggerPrUrl, s.recentReviews],+ (triggerPrUrl: string, recentReviews: ReviewRecentReviewApi[] | null): boolean => {+ const target = parsePrPath(triggerPrUrl)+ return (+ !!target &&+ (recentReviews ?? []).some(+ (review) =>+ review.resolution?.resolution_status === 'resolving' &&+ parsePrPath(review.github_url) === target+ )+ )+ },+ ],perspectiveScoreboard: [(s) => [s.reviewDetail],(reviewDetail: ReviewDetailApi | null): PerspectiveScore[] | null => {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 27cb86a3e56b..1b5a1c0c714d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -69741,6 +69741,18 @@ export namespace Schemas {password: string;}+ /**+ * * `resolving` - resolving+ * * `stopped` - stopped+ */+ export type ResolutionStatusEnum = typeof ResolutionStatusEnum[keyof typeof ResolutionStatusEnum];+++ export const ResolutionStatusEnum = {+ Resolving: 'resolving',+ Stopped: 'stopped',+ } as const;+export type RetrieveBasicOutputStatus = typeof RetrieveBasicOutputStatus[keyof typeof RetrieveBasicOutputStatus];@@ -69899,6 +69911,22 @@ export namespace Schemas {total: number | null;}+ export interface ReviewResolutionStatus {+ /** Where the run stands: `resolving` while threads are being settled, `stopped` when the run died partway (went quiet with no closing summary).+ *+ * * `resolving` - resolving+ * * `stopped` - stopped */+ resolution_status: ResolutionStatusEnum;+ /** Queued threads settled so far this run. */+ done: number;+ /** Threads queued for this run. */+ total: number;+ /** Settled threads that were fixed with a commit to the branch. */+ fixed: number;+ /** Settled threads left for the author: judged worth doing but not safe to fix unattended. */+ needs_attention: number;+ }+export interface ReviewSelectionChunk {/** The chunk this row describes, as numbered by the chunker. */chunk_id: number;@@ -70066,10 +70094,12 @@ export namespace Schemas {last_run_at: string | null;/** Whether a review has been published back to GitHub. */published: boolean;- /** Whether a review turn is running on this report right now (activity within the last 30 minutes). */+ /** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */in_progress: boolean;- /** The in-flight turn's stage and counters; null unless `in_progress`. */+ /** The in-flight review turn's stage and counters; null unless a review turn is running (a resolving report carries `resolution` instead). */progress: ReviewProgress | null;+ /** The report's latest resolution run (settling the PR's review threads): live progress while it runs, or where it stopped when it died partway. Null when there is none, it completed, or a newer review turn superseded it. */+ resolution: ReviewResolutionStatus | null;/** The latest turn's valid findings at must_fix effective priority. */must_fix_count: number;/** The latest turn's valid findings at should_fix effective priority. */@@ -70221,10 +70251,12 @@ export namespace Schemas {last_run_at: string | null;/** Whether a review has been published back to GitHub. */published: boolean;- /** Whether a review turn is running on this report right now (activity within the last 30 minutes). */+ /** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */in_progress: boolean;- /** The in-flight turn's stage and counters; null unless `in_progress`. */+ /** The in-flight review turn's stage and counters; null unless a review turn is running (a resolving report carries `resolution` instead). */progress: ReviewProgress | null;+ /** The report's latest resolution run (settling the PR's review threads): live progress while it runs, or where it stopped when it died partway. Null when there is none, it completed, or a newer review turn superseded it. */+ resolution: ReviewResolutionStatus | null;/** The latest turn's valid findings at must_fix effective priority. */must_fix_count: number;/** The latest turn's valid findings at should_fix effective priority. */