: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(stamphog): wait for and count PostHog Review through a backend evidence hook (#115425)
Julian Bezfd9d6946ba05
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex de0d7bc2bbaa..49f6a8b636b5 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -461,7 +461,9 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /suppress the publish or clobber a stranger's comment.**Reactions:** once a publishing turn passes every gate, the workflow puts a 👀 on the PR (`add_review_reaction_activity`) and removes it by the returned reaction id when the turn ends, on success, failure, or cancellation (the `finally` around the review stages).Both calls are fail-open and gated by the `reviewhog-pr-reactions-2026-10` patch.- Stamphog lists `posthog[bot]` in its trusted reviewer bots, so it waits while that 👀 is fresh.+ The 👀 is a cue for people only. The per-head review state is review_hog's public read API, `facade/review_status.py::review_status_for_head` (contract `HeadReviewStatus` in `facade/contracts.py`, implemented by `head_review_status.py`). Stamphog cannot import it (ReviewHog depends on stamphog, never the reverse), so `receivers.connect()` registers `review_evidence_for_stamphog`, a thin adapter onto stamphog's `facade/review_evidence.py` registry, with the reviewer named "PostHog Review".+ It answers per head: pending while a request for the head waits in the queue (the queue workflow's `requested_heads` query) or a turn on the head runs, through its publish; completed with the kind, the valid findings count, the published flag, the merge base the diff was taken against and the skipped files (filtered files, files GitHub sent without a patch, and the files of every pipeline chunk that no review unit finished, because a turn completes when only some of its units fail); failed when the turn for the head failed; None for any other head or a repository no project owns.+ When a publishing turn ends, after publish or after the failure is recorded, `nudge_stamphog_activity` calls stamphog's `request_rereview_after_external_review` (behind the `reviewhog-nudge-stamphog-2026-10` patch, fail-open). Stamphog decides whether a WAIT at that head runs again.**Standard turns post no status comment** (the same patch): the 👀 shows the turn runs, and the outcome is the review, a 👍 on the PR when nothing is publishable, or one failure comment per head (`post_failure_comment`, hidden `reviewhog:failed` marker) posted by `fail_status_comment_activity`.A later publish with findings, in either mode, first removes the app's own 👍 (`remove_own_pr_reactions`, matched with `is_app_bot_author`).Status comments that earlier turns left on the PR stay as they are, and a Standard turn never refreshes them.diff --git a/products/review_hog/backend/facade/review_status.py b/products/review_hog/backend/facade/review_status.pynew file mode 100644index 000000000000..d96263840c9f--- /dev/null+++ b/products/review_hog/backend/facade/review_status.py@@ -0,0 +1,25 @@+"""Facade for reading where PostHog Review's review of one pull request head stands.++Any product may read it, except one that review_hog depends on: stamphog gets the same answer+through the provider that `receivers.connect()` registers, because importing review_hog there would+be a dependency cycle. Lives apart from `reviews.py` and `github.py` because the lookup imports the+Temporal client.+"""++from products.review_hog.backend.facade.review_status_types import HeadReviewState, HeadReviewStatus+from products.review_hog.backend.head_review_status import HeadReviewStatusLookup+from products.review_hog.backend.ownership import RepositoryOwnership++__all__ = ["HeadReviewState", "HeadReviewStatus", "review_status_for_head"]+++def review_status_for_head(repository: str, pr_number: int, head_sha: str) -> HeadReviewStatus | None:+ """The status of the review of exactly `head_sha`, or None when none is known.++ None also when no project reviews the repository. Raises when Temporal does not answer the+ queue query, so a caller cannot read an outage as "nothing pending".+ """+ owner = RepositoryOwnership.find_by_name(repository)+ if owner is None:+ return None+ return HeadReviewStatusLookup(owner.team_id, repository, pr_number, head_sha).status()diff --git a/products/review_hog/backend/facade/review_status_types.py b/products/review_hog/backend/facade/review_status_types.pynew file mode 100644index 000000000000..1a370ced72b0--- /dev/null+++ b/products/review_hog/backend/facade/review_status_types.py@@ -0,0 +1,31 @@+"""Types of the head review status that review_hog exposes to other products. No Django imports."""++from dataclasses import dataclass+from enum import StrEnum+++class HeadReviewState(StrEnum):+ # Accepted but not started, or running. A turn stays pending until its findings are on the PR.+ PENDING = "pending"+ COMPLETED = "completed"+ FAILED = "failed"+++@dataclass(frozen=True, kw_only=True)+class HeadReviewStatus:+ """Where PostHog Review's review of one pull request head stands."""++ state: HeadReviewState+ # "Standard" or "Deep" for a completed turn. Empty while pending or failed.+ review_kind: str+ # Valid findings of a completed turn. Zero while pending or failed.+ findings_count: int+ # True when the turn posted a review on the PR. A clean turn posts nothing, so it stays False.+ published: bool+ head_sha: str+ # The base branch the completed turn reviewed the head against. Empty when it is not known.+ base_branch: str = ""+ # The merge base the completed turn took the diff against. Empty when it is not known.+ base_sha: str = ""+ # The changed files the completed turn left out of the review, for example lock files or a chunk no unit read.+ skipped_paths: tuple[str, ...] = ()diff --git a/products/review_hog/backend/head_review_status.py b/products/review_hog/backend/head_review_status.pynew file mode 100644index 000000000000..c72fa0a6ccb7--- /dev/null+++ b/products/review_hog/backend/head_review_status.py@@ -0,0 +1,201 @@+"""Where PostHog Review's review of one PR head stands. Read through `facade/review_status.py`.++The answer is per head, unlike `pr_status.PRStatusLookup`, which reports "queued" for the whole PR.+The database answers for turns that started: a running turn keeps the report ACTIVE on its head+until its findings are on the PR, and a finished turn leaves a turn marker, the completed head, and+the published heads. A request that waits in the PR's review queue exists only in the queue+workflow, so the workflow's `requested_heads` query answers for it.+"""++from datetime import datetime, timedelta++from posthog.dataclasses import frozen++from products.review_hog.backend.facade.review_status_types import HeadReviewState, HeadReviewStatus+from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact+from products.review_hog.backend.reviewer.artefact_content import TurnMarkerArtefact+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL+from products.review_hog.backend.reviewer.persistence import (+ load_chunk_set,+ load_turn_findings,+ reviewed_pipeline_chunk_ids,+)+from products.review_hog.backend.reviewer.progress import (+ RUN_OUTCOME_FAILED,+ RUN_STAGE_REVIEW,+ finding_counts,+ in_progress_report_ids,+ run_outcome_markers,+)+from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_SINGLE_AGENT+from products.review_hog.backend.reviewer.review_state import turn_review_mode+from products.review_hog.backend.temporal.client import queued_review_heads+from products.review_hog.backend.temporal.types import review_pr_workflow_id++_KIND_NAMES = {REVIEW_MODE_FLASH: "Standard", REVIEW_MODE_FULL: "Deep"}+# Callers poll, for example stamphog every 30 seconds, so a slow queue answer must not hold them.+_QUERY_RPC_TIMEOUT = timedelta(seconds=2)+++@frozen+class _Turn:+ marker: TurnMarkerArtefact+ # When the newest marker row of the turn was written, which is when its last attempt started.+ started_at: datetime+++class HeadReviewStatusLookup:+ def __init__(self, team_id: int, repository: str, pr_number: int, head_sha: str) -> None:+ self.team_id = team_id+ self.repository = repository+ self.pr_number = pr_number+ self.head_sha = head_sha+ # Repository casing can differ per trigger, so match it the way the trigger does.+ self.report = (+ ReviewReport.objects.for_team(team_id).filter(repository__iexact=repository, pr_number=pr_number).first()+ )+ self.report_id = str(self.report.id) if self.report is not None else ""++ def _status(+ self,+ state: HeadReviewState,+ *,+ review_kind: str = "",+ findings_count: int = 0,+ published: bool = False,+ base_branch: str = "",+ base_sha: str = "",+ skipped_paths: tuple[str, ...] = (),+ ) -> HeadReviewStatus:+ return HeadReviewStatus(+ state=state,+ review_kind=review_kind,+ findings_count=findings_count,+ published=published,+ head_sha=self.head_sha,+ base_branch=base_branch,+ base_sha=base_sha,+ skipped_paths=skipped_paths,+ )++ def _running_head(self) -> str | None:+ """The head of the turn that runs now, or None. A turn stays ACTIVE through its publish."""+ report = self.report+ if report is None or report.status != ReviewReport.Status.ACTIVE:+ return None+ if self.report_id not in in_progress_report_ids(self.team_id, [report]):+ return None+ return report.head_sha++ def _queued(self, running_head: str | None) -> bool:+ owner, _, repo = self.repository.partition("/")+ workflow_id = review_pr_workflow_id(team_id=self.team_id, owner=owner, repo=repo, pr_number=self.pr_number)+ heads = queued_review_heads(workflow_id, rpc_timeout=_QUERY_RPC_TIMEOUT)+ if self.head_sha in heads.active or self.head_sha in heads.pending:+ return True+ # A request without a head reviews the live head when its turn starts. A waiting one has not+ # started yet. The active one is the running turn when a turn runs on another head.+ return None in heads.pending or (None in heads.active and running_head is None)++ def _turns_on_head(self) -> dict[int, _Turn]:+ """Each turn on this head by run index, from its marker. The newest row of a retried turn wins."""+ rows = (+ ReviewReportArtefact.objects.for_team(self.team_id)+ .filter(+ report_id=self.report_id,+ type=ReviewReportArtefact.ArtefactType.TURN_MARKER,+ head_sha=self.head_sha,+ )+ .order_by("created_at", "id")+ .values("content", "created_at")+ )+ turns: dict[int, _Turn] = {}+ for row in rows:+ marker = TurnMarkerArtefact.model_validate_json(row["content"])+ turns[marker.run_index] = _Turn(marker=marker, started_at=row["created_at"])+ return turns++ def _skipped_paths(self, turn: _Turn | None) -> tuple[str, ...]:+ """The files the turn left out, plus the files of every pipeline chunk that no review unit finished.++ The fan-out fails a turn only when most of its units fail, so a turn can complete with a chunk unread.+ """+ if turn is None:+ return ()+ skipped = list(turn.marker.skipped_paths or ())+ # A single-agent turn fails when its main session fails, and that session reviews the whole diff.+ if turn.marker.fingerprint_inputs.get("review_design") == REVIEW_DESIGN_SINGLE_AGENT:+ return tuple(skipped)+ chunks = load_chunk_set(team_id=self.team_id, report_id=self.report_id, head_sha=self.head_sha)+ # Without the chunking the gaps are unknown, so the turn keeps only the files it left out.+ if chunks is None:+ return tuple(skipped)+ reviewed = reviewed_pipeline_chunk_ids(team_id=self.team_id, report_id=self.report_id, head_sha=self.head_sha)+ for chunk in chunks.chunks:+ if chunk.chunk_id in reviewed:+ continue+ for file in chunk.files:+ if file.filename not in skipped:+ skipped.append(file.filename)+ return tuple(skipped)++ def _finished(self) -> HeadReviewStatus | None:+ report = self.report+ if report is None:+ return None+ published_heads = report.published_head_shas or {}++ def posted(run_index: int) -> bool:+ return published_heads.get(str(run_index)) == self.head_sha++ turns = {run_index: turn for run_index, turn in self._turns_on_head().items() if run_index <= report.run_count}+ # Only a turn that posts to the PR is a review of the PR. An eval or CLI turn is not, even+ # with valid findings. A clean publishing turn posts nothing and still counts. A marker+ # from before `publishes` existed counts only when its turn posted.+ completed_runs = [+ run_index+ for run_index, turn in turns.items()+ if turn.marker.publishes or (turn.marker.publishes is None and posted(run_index))+ ]+ # Turns that started before turn markers existed have none, so the latest turn's head counts too.+ if (+ report.run_count+ and report.completed_head_sha == self.head_sha+ and report.run_count not in turns+ and posted(report.run_count)+ ):+ completed_runs.append(report.run_count)+ failed_at: dict[int | None, datetime] = {+ marker.run_index: marker.created_at+ for marker in run_outcome_markers(self.team_id, [self.report_id])[self.report_id]+ if marker.stage == RUN_STAGE_REVIEW+ and marker.outcome == RUN_OUTCOME_FAILED+ and marker.head_sha == self.head_sha+ }+ if not completed_runs:+ return self._status(HeadReviewState.FAILED) if failed_at else None+ run_index = max(completed_runs)+ turn = turns.get(run_index)+ # Finalize counts a turn before it publishes, so a failed publish marks a counted turn failed.+ # A failure from before the turn's last attempt started belongs to an attempt that a+ # successful retry replaced.+ if run_index in failed_at and (turn is None or failed_at[run_index] > turn.started_at):+ return self._status(HeadReviewState.FAILED)+ pairs = load_turn_findings(team_id=self.team_id, report_id=self.report_id, run_index=run_index)+ counts, _ = finding_counts(pairs)+ review_mode = turn.marker.review_mode if turn is not None else turn_review_mode(pairs)+ return self._status(+ HeadReviewState.COMPLETED,+ review_kind=_KIND_NAMES.get(review_mode, ""),+ findings_count=sum(counts.values()),+ published=posted(run_index),+ base_branch=(turn.marker.base_branch or "") if turn is not None else "",+ base_sha=(turn.marker.base_sha or "") if turn is not None else "",+ skipped_paths=self._skipped_paths(turn),+ )++ def status(self) -> HeadReviewStatus | None:+ running_head = self._running_head()+ if running_head == self.head_sha or self._queued(running_head):+ return self._status(HeadReviewState.PENDING)+ return self._finished()diff --git a/products/review_hog/backend/receivers.py b/products/review_hog/backend/receivers.pyindex bf49fb693dd9..3b640d4ec611 100644--- a/products/review_hog/backend/receivers.py+++ b/products/review_hog/backend/receivers.py@@ -49,6 +49,11 @@ from products.signals.backend.enums import ReportPriorityfrom products.signals.backend.models import SignalReportArtefactfrom products.signals.backend.report_generation.priority import persisted_report_priorityfrom products.stamphog.backend.facade.inbox_hooks import register_inbox_acting_reviewer_resolver+from products.stamphog.backend.facade.review_evidence import (+ ReviewEvidence,+ ReviewEvidenceState,+ register_review_evidence_provider,+)# This module loads during django.setup() (AppConfig.ready() wires the receiver), and# posthog/test/repo_invariants/test_startup_import_budget.py forbids temporalio/modal/openai/anthropic at setup —@@ -57,9 +62,12 @@ from products.stamphog.backend.facade.inbox_hooks import register_inbox_acting_rlogger = logging.getLogger(__name__)+# The name stamphog shows for these reviews, the same name the reviews carry on GitHub.+REVIEWER_NAME = "PostHog Review"+def connect() -> None:- """Wire the TaskRun-save receiver and the stamphog toggle hook; called once from `AppConfig.ready()`."""+ """Wire the TaskRun-save receiver and the stamphog hooks; called once from `AppConfig.ready()`."""post_save.connect(handle_task_run_saved,sender=django_apps.get_model("tasks", "TaskRun"),@@ -68,6 +76,30 @@ def connect() -> None:# Stamphog re-checks this toggle before re-reviewing a self-driving PR. It gets the resolver# through a hook because importing review_hog from stamphog would be a dependency cycle.register_inbox_acting_reviewer_resolver(resolve_stamphog_acting_reviewer)+ # Stamphog waits for a pending review of the head it judges and counts a completed one as+ # assurance. The same dependency cycle rules out a direct import.+ register_review_evidence_provider(review_evidence_for_stamphog)+++def review_evidence_for_stamphog(repository: str, pr_number: int, head_sha: str) -> ReviewEvidence | None:+ """Map review_hog's own head status onto stamphog's evidence contract."""+ # The lookup reads the review pipeline's modules, which reach openai, anthropic and temporalio.+ from products.review_hog.backend.facade.review_status import review_status_for_head # noqa: PLC0415++ status = review_status_for_head(repository, pr_number, head_sha)+ if status is None:+ return None+ return ReviewEvidence(+ state=ReviewEvidenceState(status.state.value),+ reviewer=REVIEWER_NAME,+ review_kind=status.review_kind,+ findings_count=status.findings_count,+ published=status.published,+ head_sha=status.head_sha,+ base_ref=status.base_branch,+ base_sha=status.base_sha,+ skipped_paths=status.skipped_paths,+ )def handle_task_run_saved(sender: type, instance: Any, created: bool, **kwargs: Any) -> None:diff --git a/products/review_hog/backend/reviewer/artefact_content.py b/products/review_hog/backend/reviewer/artefact_content.pyindex f79a2114aa8f..a889ce7b1847 100644--- a/products/review_hog/backend/reviewer/artefact_content.py+++ b/products/review_hog/backend/reviewer/artefact_content.py@@ -327,7 +327,10 @@ class PRSnapshotArtefact(BaseModel):)merge_base_sha: str | None = Field(default=None,- description="The commit GitHub computes the PR diff against. Fetched for single-agent turns only.",+ description="The commit GitHub computes the PR diff against. None when GitHub did not return it.",+ )+ skipped_paths: list[str] = Field(+ default_factory=list, description="The changed files the review left out (lock, generated, test files).")@@ -347,6 +350,13 @@ class TurnMarkerArtefact(BaseModel):fingerprint_inputs: dict[str, Any] = Field(default_factory=dict, description="The payload the fingerprint hashes (prompt and skill texts as hashes).")+ # The fields below are None on markers written before they existed.+ publishes: bool | None = Field(default=None, description="Whether the turn posts its result to the PR.")+ base_branch: str | None = Field(default=None, description="The base branch the reviewed diff was taken against.")+ base_sha: str | None = Field(default=None, description="The merge base the reviewed diff was taken against.")+ skipped_paths: list[str] | None = Field(+ default=None, description="The changed files the turn left out of the review."+ )RUN_OUTCOME_NOTE_AUTHOR = "review_hog_run_outcome"diff --git a/products/review_hog/backend/reviewer/fingerprint.py b/products/review_hog/backend/reviewer/fingerprint.pyindex bca21c04dcf0..b4af966c28e0 100644--- a/products/review_hog/backend/reviewer/fingerprint.py+++ b/products/review_hog/backend/reviewer/fingerprint.py@@ -48,6 +48,7 @@ from products.review_hog.backend.reviewer.constants import (validation_arm_for_mode,)from products.review_hog.backend.reviewer.models import PROMPTS_DIR+from products.review_hog.backend.reviewer.persistence import load_pr_snapshotfrom products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENTfrom products.review_hog.backend.reviewer.sandbox.executor import JSON_RETRY_PROMPTfrom products.review_hog.backend.reviewer.skill_loader import (@@ -299,9 +300,15 @@ def record_turn_marker(flash_reasoning_effort: str,review_design: str = REVIEW_DESIGN_PIPELINE,coordinator: bool = False,+ publishes: bool | None = None,) -> ReviewHogMarker:- """Compute the turn's marker and persist it as the turn's `turn_marker` artefact."""+ """Compute the turn's marker and persist it as the turn's `turn_marker` artefact.++ The marker also records what the turn reviewed (base branch, merge base and skipped files, from the turn's+ PR snapshot), so a reader of a finished turn knows how far the review reached.+ """report = ReviewReport.objects.for_team(team_id).get(id=report_id)+ snapshot = load_pr_snapshot(team_id=team_id, report_id=report_id, head_sha=head_sha, review_design=review_design)fingerprint = TurnFingerprint.for_turn(team_id=team_id,report=report,@@ -324,6 +331,10 @@ def record_turn_marker(reviewhog_version=marker.version,reviewhog_fingerprint=marker.fingerprint,fingerprint_inputs=fingerprint.inputs,+ publishes=publishes,+ base_branch=snapshot.pr_metadata.base_branch if snapshot is not None else None,+ base_sha=snapshot.merge_base_sha if snapshot is not None else None,+ skipped_paths=snapshot.skipped_paths if snapshot is not None else None,),attribution=ArtefactAttribution.system(),)diff --git a/products/review_hog/backend/reviewer/persistence.py b/products/review_hog/backend/reviewer/persistence.pyindex e6de7c550227..7c82aed82b5a 100644--- a/products/review_hog/backend/reviewer/persistence.py+++ b/products/review_hog/backend/reviewer/persistence.py@@ -439,6 +439,21 @@ def load_perspective_results(return out+def reviewed_pipeline_chunk_ids(*, team_id: int, report_id: str, head_sha: str) -> set[int]:+ """The pipeline chunks at this head that at least one review unit finished, a perspective or the blind spot.++ Any arm counts, because the question is whether a reviewer read the chunk at all.+ """+ chunk_ids: set[int] = set()+ for content in _load_working_state(+ team_id, report_id, ReviewReportArtefact.ArtefactType.PERSPECTIVE_RESULT, head_sha+ ):+ assert isinstance(content, PerspectiveResultArtefact)+ if not is_single_agent_pass(content.pass_number):+ chunk_ids.add(content.chunk_id)+ return chunk_ids++def persist_pr_snapshot(*,team_id: int,@@ -449,6 +464,7 @@ def persist_pr_snapshot(pr_files: list[PRFile],review_design: str = REVIEW_DESIGN_PIPELINE,merge_base_sha: str | None = None,+ skipped_paths: Sequence[str] = (),) -> None:"""Append this turn's fetched PR inputs as a `pr_snapshot` artefact (stored by reference).@@ -466,6 +482,7 @@ def persist_pr_snapshot(pr_files=pr_files,review_design=review_design,merge_base_sha=merge_base_sha,+ skipped_paths=list(skipped_paths),),attribution=ArtefactAttribution.system(),)diff --git a/products/review_hog/backend/reviewer/tests/test_github_meta.py b/products/review_hog/backend/reviewer/tests/test_github_meta.pyindex 4a955a020f60..a487dc8b1aca 100644--- a/products/review_hog/backend/reviewer/tests/test_github_meta.py+++ b/products/review_hog/backend/reviewer/tests/test_github_meta.py@@ -6,7 +6,7 @@ from unittest.mock import Mock, patchfrom parameterized import parameterizedfrom products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError-from products.review_hog.backend.reviewer.tools.github_meta import PRFetcher, PRFilter, PRParser+from products.review_hog.backend.reviewer.tools.github_meta import PRFetcher, PRFilter, PRParser, _patch_omitted_META = "products.review_hog.backend.reviewer.tools.github_meta"@@ -449,16 +449,33 @@ class TestFetchPrData:@parameterized.expand([- ("pipeline", False, ["src/module.py"]),- ("single_agent", True, ["tests/test_module.py", "requirements.txt", "src/module.py"]),+ (+ "pipeline",+ False,+ ["src/module.py", "src/large.py"],+ ["tests/test_module.py", "requirements.txt", "yarn.lock", "src/large.py"],+ ),+ (+ "single_agent",+ True,+ ["tests/test_module.py", "requirements.txt", "src/module.py", "src/large.py"],+ ["yarn.lock", "src/large.py"],+ ),])def test_filtered_and_test_files_are_excluded(- self, mock_request: Mock, mock_paginated: Mock, _name: str, review_tests_and_text: bool, expected: list[str]+ self,+ mock_request: Mock,+ mock_paginated: Mock,+ _name: str,+ review_tests_and_text: bool,+ expected: list[str],+ expected_skipped: list[str],) -> None:# A lock file never reaches the review. Test and `.txt` files reach only the single-agent# design, which was measured with them in its diff; the pipeline was tuned without them. A- # comment follows its file, so dedup sees exactly the comments on reviewed files.+ # comment follows its file, so dedup sees exactly the comments on reviewed files. GitHub sends+ # no patch for a large file, so the review never sees its changes and must report it skipped._wire(mock_request,mock_paginated,@@ -469,6 +486,7 @@ class TestFetchPrData:_file_json(filename="requirements.txt", status="modified", patch="@@ -1,1 +1,1 @@\n+w"),_file_json(filename="yarn.lock", status="modified", patch="@@ -1,1 +1,1 @@\n+y"),_file_json(filename="src/module.py", status="modified", patch="@@ -1,1 +1,1 @@\n+z"),+ _file_json(filename="src/large.py", status="modified"),],)@@ -477,6 +495,7 @@ class TestFetchPrData:comments, files, diff = fetched.pr_comments, fetched.pr_files, fetched.diffassert [f.filename for f in files] == expected+ assert list(fetched.skipped_paths) == expected_skippedassert [comment.path for comment in comments] == (["tests/test_module.py"] if review_tests_and_text else [])assert ("=== tests/test_module.py [added] ===" in diff) is review_tests_and_textassert "yarn.lock" not in diff@@ -577,3 +596,20 @@ class TestFetchPrData:fetcher = PRFetcher("owner", "repo", 123, token="test-token")with pytest.raises(GitHubAPIError):fetcher.fetch_pr_data()+++ "file, omitted",+ [+ ({"filename": "big.py", "status": "modified", "additions": 900, "deletions": 0}, True),+ ({"filename": "logo.png", "status": "added", "additions": 0, "deletions": 0}, True),+ ({"filename": "lib.so", "status": "modified", "additions": 0, "deletions": 0}, True),+ ({"filename": "new_name.py", "status": "renamed", "additions": 0, "deletions": 0}, False),+ (+ {"filename": "small.py", "status": "modified", "additions": 1, "deletions": 0, "patch": "@@ -1 +1 @@\n+x"},+ False,+ ),+ ],+)+def test_patch_omitted_marks_every_unseen_change(file: dict[str, Any], omitted: bool) -> None:+ assert _patch_omitted(file) is omitteddiff --git a/products/review_hog/backend/reviewer/tools/github_meta.py b/products/review_hog/backend/reviewer/tools/github_meta.pyindex 4647ff4914b3..e4ad0c07ea98 100644--- a/products/review_hog/backend/reviewer/tools/github_meta.py+++ b/products/review_hog/backend/reviewer/tools/github_meta.py@@ -247,6 +247,15 @@ class PRParser:return changes+@frozen+class FetchedFiles:+ """The PR's reviewable files, their point-in-time diff, and the files the filter left out."""++ pr_files: list[PRFile]+ diff: str+ skipped_paths: tuple[str, ...]++@frozenclass FetchedPR:"""Everything the review pipeline needs from one fetched review target."""@@ -258,6 +267,18 @@ class FetchedPR:diff: str# The commit GitHub computes the diff against. None when it was not asked for or GitHub did not return it.merge_base_sha: str | None = None+ skipped_paths: tuple[str, ...] = ()+++def _patch_omitted(file: dict[str, Any]) -> bool:+ """True when GitHub sent no patch for a changed file, for example a large or binary file.++ The review then sees the file name but none of its changes, so the file counts as skipped. Only a+ pure rename has no changes to see.+ """+ if file.get("patch"):+ return False+ return not (file.get("status") == "renamed" and not (file["additions"] or file["deletions"]))def _merge_base_sha(comparison: dict[str, Any]) -> str | None:@@ -338,13 +359,17 @@ def fetch_branch_compare(pr_filter = PRFilter(review_tests_and_text=review_tests_and_text)pr_parser = PRParser()pr_files: list[PRFile] = []+ skipped_paths: list[str] = []diff_sections: list[str] = []additions = deletions = 0for file in files:additions += file["additions"]deletions += file["deletions"]if pr_filter.skips(file["filename"]):+ skipped_paths.append(file["filename"])continue+ if _patch_omitted(file):+ skipped_paths.append(file["filename"])patch = file.get("patch")pr_files.append(PRFile(@@ -381,6 +406,7 @@ def fetch_branch_compare(pr_files=pr_files,diff="\n\n".join(diff_sections),merge_base_sha=_merge_base_sha(comparison),+ skipped_paths=tuple(skipped_paths),)@@ -470,16 +496,17 @@ class PRFetcher:logger.warning(f"Could not fetch review comments: {e}")return pr_comments- def fetch_pr_files(self, pr_filter: PRFilter, pr_parser: PRParser) -> tuple[list[PRFile], str]:+ def fetch_pr_files(self, pr_filter: PRFilter, pr_parser: PRParser) -> FetchedFiles:"""Fetch the PR's reviewable files and the point-in-time unified diff snapshot.- Returns ``(pr_files, diff)``. The raw per-file patch is captured here — the only place with+ ``skipped_paths`` are the files the filter left out and the files without a patch. The raw per-file patch is captured here — the only place withthe file's ``patch`` — into the ``diff`` snapshot, kept out of ``PRFile`` so it doesn't bloatthe prompts that dump ``pr_files``. The snapshot is the source for the durable per-turn`commit` artefact (it anchors a finding to the exact reviewed code even after laterforce-pushes)."""pr_files: list[PRFile] = []+ skipped_paths: list[str] = []diff_sections: list[str] = []try:for file in github_api_get_paginated(@@ -489,7 +516,10 @@ class PRFetcher:endpoint="/repos/{owner}/{repo}/pulls/{pull_number}/files",):if pr_filter.skips(file["filename"]):+ skipped_paths.append(file["filename"])continue+ if _patch_omitted(file):+ skipped_paths.append(file["filename"])patch = file.get("patch")pr_files.append(PRFile(@@ -503,7 +533,7 @@ class PRFetcher:diff_sections.append(_format_diff_section(file["filename"], file["status"], patch or ""))except (GitHubAPIError, GitHubRateLimitError) as e:raise ValueError(f"Failed to fetch PR files: {e}") from e- return pr_files, "\n\n".join(diff_sections)+ return FetchedFiles(pr_files=pr_files, diff="\n\n".join(diff_sections), skipped_paths=tuple(skipped_paths))def fetch_merge_base_sha(self, *, base_branch: str, head_sha: str) -> str | None:"""The commit GitHub computes the PR's diff against, or None when the compare call fails.@@ -543,7 +573,7 @@ class PRFetcher:pr_parser = PRParser()pr_metadata = self.fetch_pr_metadata(pr)pr_comments = self.fetch_pr_comments(pr_filter)- pr_files, diff = self.fetch_pr_files(pr_filter, pr_parser)+ files = self.fetch_pr_files(pr_filter, pr_parser)merge_base_sha = (self.fetch_merge_base_sha(base_branch=pr_metadata.base_branch, head_sha=pr_metadata.head_sha)if with_merge_base and pr_metadata.head_sha@@ -553,7 +583,8 @@ class PRFetcher:return FetchedPR(pr_metadata=pr_metadata,pr_comments=pr_comments,- pr_files=pr_files,- diff=diff,+ pr_files=files.pr_files,+ diff=files.diff,merge_base_sha=merge_base_sha,+ skipped_paths=files.skipped_paths,)diff --git a/products/review_hog/backend/temporal/__init__.py b/products/review_hog/backend/temporal/__init__.pyindex fa2c4f689e59..175b4561ae49 100644--- a/products/review_hog/backend/temporal/__init__.py+++ b/products/review_hog/backend/temporal/__init__.py@@ -13,6 +13,7 @@ from products.review_hog.backend.temporal.activities import (load_blind_spots_skill_activity,load_perspectives_activity,load_validation_skill_activity,+ nudge_stamphog_activity,post_status_comment_activity,publish_review_activity,record_turn_marker_activity,@@ -83,6 +84,7 @@ ACTIVITIES = [finalize_status_comment_activity,fail_status_comment_activity,add_review_reaction_activity,+ nudge_stamphog_activity,remove_review_reaction_activity,track_review_completed_activity,track_review_failed_activity,diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex 4bc314f06841..6d2f414bb77b 100644--- a/products/review_hog/backend/temporal/activities.py+++ b/products/review_hog/backend/temporal/activities.py@@ -203,6 +203,7 @@ from products.signals.backend.artefact_schemas import CodeReview, CodeReviewCounfrom products.signals.backend.enums import ReportPriorityfrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users+from products.stamphog.backend.facade.tasks import request_rereview_after_external_reviewfrom products.tasks.backend.facade.agents import AgentTurnFailedfrom products.tasks.backend.facade.contracts import SessionFilefrom products.tasks.backend.facade.run_config import ReasoningEffort@@ -594,6 +595,8 @@ class RecordTurnMarkerInput:flash_reasoning_effort: strreview_design: str = REVIEW_DESIGN_PIPELINEcoordinator: bool = False+ # None in payloads from before the field existed.+ publishes: bool | None = None@frozen@@ -665,6 +668,15 @@ class ReviewReactionInput:reaction_id: int | None = None+@frozen+class TurnEndedInput:+ """A review turn on a PR head that reached completed or failed, for the stamphog nudge."""++ repository: str+ pr_number: int+ head_sha: str++# --- Setup activities ------------------------------------------------------------------------------@@ -776,7 +788,7 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:if pr_number is not None:fetched = PRFetcher(owner=input.owner, repo=input.repo, pr_number=pr_number, token=token, installation_id=installation_id- ).fetch_pr_data(review_tests_and_text=single_agent, with_merge_base=single_agent)+ ).fetch_pr_data(review_tests_and_text=single_agent, with_merge_base=True)if fetched.pr_metadata.is_fork:raise ApplicationError(f"Refusing to review fork PR #{pr_number} in {input.repository}: a fork's head ref is "@@ -845,6 +857,7 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:pr_files=fetched.pr_files,review_design=design_choice.design,merge_base_sha=fetched.merge_base_sha,+ skipped_paths=fetched.skipped_paths,)lens_plan = plan_lens_chunks(fetched.pr_files) if single_agent else None# Checked on the fetched labels, because `gh pr create --label` adds labels after the `opened`@@ -1084,6 +1097,7 @@ def _record_turn_marker_safe(input: RecordTurnMarkerInput) -> ReviewHogMarker |flash_reasoning_effort=input.flash_reasoning_effort,review_design=input.review_design,coordinator=input.coordinator,+ publishes=input.publishes,)except Exception:logger.exception("Failed to record the turn marker for report %s; continuing", input.report_id)@@ -2516,7 +2530,8 @@ def _remove_eyes_reaction(input: ReviewReactionInput) -> None:async def add_review_reaction_activity(input: ReviewReactionInput) -> int | None:"""Put a 👀 on the PR while the turn runs, the way other review bots do. Returns the reaction id.- Stamphog waits while a trusted review bot has a fresh 👀 on the PR. Fail-open: never raises.+ The 👀 is a cue for people. Stamphog reads the review state from `head_review_status.py`.+ Fail-open: never raises."""return await database_sync_to_async(_add_eyes_reaction, thread_sensitive=False)(input)@@ -2529,6 +2544,25 @@ async def remove_review_reaction_activity(input: ReviewReactionInput) -> None:await database_sync_to_async(_remove_eyes_reaction, thread_sensitive=False)(input)+def _nudge_stamphog(input: TurnEndedInput) -> None:+ request_rereview_after_external_review(+ repository=input.repository, pr_number=input.pr_number, head_sha=input.head_sha+ )+++@scoped_temporal()+@close_db_connections+async def nudge_stamphog_activity(input: TurnEndedInput) -> None:+ """Tell stamphog that the turn on this head ended, so a stamphog WAIT for it can run again.++ Stamphog waits only a few minutes for a running review, and a Deep review takes longer.+ Stamphog decides whether to act. A dispatch error raises, so Temporal retries it. The workflow+ catches the final failure, because a lost nudge must never fail the review.+ """+ await database_sync_to_async(_nudge_stamphog, thread_sensitive=False)(input)++# --- The signals report's code_review receipt --------------------------------------------------------# `IssuePriority` values map 1:1 onto the CodeReviewCounts fields (the enum mirrors the threshold choices).diff --git a/products/review_hog/backend/temporal/client.py b/products/review_hog/backend/temporal/client.pyindex 0a0f963813f9..32d89e2f614a 100644--- a/products/review_hog/backend/temporal/client.py+++ b/products/review_hog/backend/temporal/client.py@@ -34,10 +34,11 @@ from typing import Any, castfrom django.conf import settingsfrom asgiref.sync import async_to_sync-from temporalio.client import WorkflowExecutionStatus-from temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicy+from temporalio.client import WorkflowExecutionStatus, WorkflowQueryRejectedError+from temporalio.common import QueryRejectCondition, RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom temporalio.service import RPCError, RPCStatusCode+from posthog.dataclasses import frozenfrom posthog.models.team.team import Teamfrom posthog.temporal.common.client import sync_connect@@ -88,6 +89,37 @@ def probe_workflow(workflow_id: str, rpc_timeout: timedelta | None = None) -> Woreturn WorkflowProbe.NOT_RUNNING+@frozen+class QueuedReviewHeads:+ """The heads the PR's review queue still has to review. None is a request for the live head."""++ # The request whose turn runs now, or waits for a resolution run to end before it starts.+ active: tuple[str | None, ...] = ()+ pending: tuple[str | None, ...] = ()+++def queued_review_heads(workflow_id: str, rpc_timeout: timedelta | None = None) -> QueuedReviewHeads:+ """The heads the PR's review queue still has to review. Empty when no queue runs.++ Raises when Temporal does not answer, so a caller cannot read an outage as "nothing queued".+ """+ try:+ client = sync_connect()+ handle = client.get_workflow_handle(workflow_id)+ # async_to_sync erases query's overloads, so mypy binds the wrong one.+ query = cast(Callable[..., Any], async_to_sync(handle.query))+ heads: dict[str, list[str | None]] = query(+ "requested_heads", reject_condition=QueryRejectCondition.NOT_OPEN, rpc_timeout=rpc_timeout+ )+ except WorkflowQueryRejectedError:+ return QueuedReviewHeads()+ except RPCError as e:+ if e.status == RPCStatusCode.NOT_FOUND:+ return QueuedReviewHeads()+ raise+ return QueuedReviewHeads(active=tuple(heads["active"]), pending=tuple(heads["pending"]))++def workflow_running(workflow_id: str) -> bool:"""Whether `workflow_id` has a live execution — the busy-guard's probe (CONTEXT.md — "Busy-guard").diff --git a/products/review_hog/backend/temporal/scheduling.py b/products/review_hog/backend/temporal/scheduling.pyindex 095e85376c70..01eded5ac431 100644--- a/products/review_hog/backend/temporal/scheduling.py+++ b/products/review_hog/backend/temporal/scheduling.py@@ -44,6 +44,13 @@ class ReviewRequestQueue:key = TRIGGER_AUTOMATIC if request.trigger_source == TRIGGER_AUTOMATIC else request.review_modeself.pending[key] = request+ def requested_heads(self) -> dict[str, list[str | None]]:+ """The heads the active request and the waiting requests ask for. None is a request for the live head."""+ return {+ "active": [self.active.requested_head_sha] if self.active is not None else [],+ "pending": [request.requested_head_sha for request in self.pending.values()],+ }+def take(self) -> ReviewPRWorkflowInputs:# Explicit requests take precedence over another automatic follow-up.key = next(key for key in (REVIEW_MODE_FULL, REVIEW_MODE_FLASH, TRIGGER_AUTOMATIC) if key in self.pending)@@ -85,6 +92,11 @@ class ReviewPRQueueWorkflow:def request_review(self, request: ReviewPRWorkflowInputs) -> None:self._requests.add(request)+ # Read by the status provider for stamphog, because a waiting request exists only in this state.+ @workflow.query+ def requested_heads(self) -> dict[str, list[str | None]]:+ return self._requests.requested_heads()+@workflow.runasync def run(self, inputs: ReviewPRQueueInputs) -> str:result = ""diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.pyindex 35c6c78382b8..e01d7a3b0b60 100644--- a/products/review_hog/backend/temporal/workflow.py+++ b/products/review_hog/backend/temporal/workflow.py@@ -76,6 +76,7 @@ from products.review_hog.backend.temporal.activities import (TrackReviewCompletedInput,TrackReviewFailedInput,TrackReviewStartedInput,+ TurnEndedInput,ValidateChunkInput,ValidateChunkResult,ValidateIntegrationInput,@@ -93,6 +94,7 @@ from products.review_hog.backend.temporal.activities import (load_blind_spots_skill_activity,load_perspectives_activity,load_validation_skill_activity,+ nudge_stamphog_activity,post_status_comment_activity,publish_review_activity,record_turn_marker_activity,@@ -709,6 +711,7 @@ class ReviewPRWorkflow:flash_reasoning_effort=acting.flash_reasoning_effort,review_design=review_design,coordinator=review_design == REVIEW_DESIGN_SINGLE_AGENT and meta.coordinator,+ publishes=publishes_to_pr,),start_to_close_timeout=_QUICK_TIMEOUT,retry_policy=_RETRY,@@ -840,6 +843,9 @@ class ReviewPRWorkflow:)except Exception:workflow.logger.warning("Could not mark the status comment as failed")+ # After the failure is recorded, so a stamphog re-run reads this head as failed.+ if workflow.patched("reviewhog-nudge-stamphog-2026-10") and meta.pr_number is not None:+ await self._nudge_stamphog(repository, meta.pr_number, head_sha)# The signal report's log records a failed turn too (a receipt per executed turn,# completion or failure); best-effort so it can never mask the original error.await self._append_code_review_receipt(@@ -873,6 +879,9 @@ class ReviewPRWorkflow:await self._remove_eyes_reaction(inputs.team_id, repository, meta.pr_number, eyes_reaction_id)posted = publish_result is not None and publish_result.posted+ # After publish, so a stamphog re-run finds this turn's findings on the PR.+ if workflow.patched("reviewhog-nudge-stamphog-2026-10") and publishes_to_pr and meta.pr_number is not None:+ await self._nudge_stamphog(repository, meta.pr_number, head_sha)# One analytics event per finalized turn (the review-level count dashboards aggregate);# best-effort — a review must never fail over its own telemetry.try:@@ -1155,6 +1164,18 @@ class ReviewPRWorkflow:workflow.logger.warning("Could not add the review reaction; continuing without it")return None+ @staticmethod+ async def _nudge_stamphog(repository: str, pr_number: int, head_sha: str) -> None:+ try:+ await workflow.execute_activity(+ nudge_stamphog_activity,+ TurnEndedInput(repository=repository, pr_number=pr_number, head_sha=head_sha),+ start_to_close_timeout=_QUICK_TIMEOUT,+ retry_policy=_RETRY,+ )+ except ActivityError:+ workflow.logger.warning("Could not ask stamphog to re-review")+@staticmethodasync def _remove_eyes_reaction(team_id: int, repository: str, pr_number: int, reaction_id: int) -> None:try:diff --git a/products/review_hog/backend/tests/test_fetch_review_tier.py b/products/review_hog/backend/tests/test_fetch_review_tier.pyindex f637d5fd5c63..d24797e2246a 100644--- a/products/review_hog/backend/tests/test_fetch_review_tier.py+++ b/products/review_hog/backend/tests/test_fetch_review_tier.py@@ -141,7 +141,7 @@ class TestFetchDecidesTheTier(BaseTest):single_agent = review_mode == REVIEW_MODE_FLASHassert mock_fetcher.return_value.fetch_pr_data.call_args.kwargs == {"review_tests_and_text": single_agent,- "with_merge_base": single_agent,+ "with_merge_base": True,}snapshot = load_pr_snapshot(team_id=self.team.id, report_id=meta.report_id, head_sha=meta.head_sha)assert snapshot is not None and snapshot.merge_base_sha == merge_base_shadiff --git a/products/review_hog/backend/tests/test_fingerprint.py b/products/review_hog/backend/tests/test_fingerprint.pyindex 4ffde06a498b..fc4ae376c544 100644--- a/products/review_hog/backend/tests/test_fingerprint.py+++ b/products/review_hog/backend/tests/test_fingerprint.py@@ -20,7 +20,7 @@ from products.review_hog.backend.reviewer.constants import ()from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarker, record_turn_markerfrom products.review_hog.backend.reviewer.models.github_meta import PRMetadata-from products.review_hog.backend.reviewer.persistence import upsert_review_report+from products.review_hog.backend.reviewer.persistence import persist_pr_snapshot, upsert_review_reportfrom products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENTfrom products.review_hog.backend.reviewer.skill_loader import REVIEW_HOG_VALIDATION_SKILL_NAMEfrom products.review_hog.backend.reviewer.tools.single_agent_review import SINGLE_AGENT_PROMPT_PATH@@ -33,26 +33,27 @@ class TestRecordTurnMarker(BaseTest):def setUp(self) -> None:super().setUp()_sync_review_skills(self.team.id)+ self.pr_metadata = PRMetadata(+ number=7,+ title="t",+ state="open",+ draft=False,+ created_at="",+ updated_at="",+ author="octocat",+ base_branch="main",+ head_branch="feat",+ head_sha="sha1",+ commits=1,+ additions=1,+ deletions=0,+ changed_files=1,+ )self.report_id = upsert_review_report(team_id=self.team.id,repository="o/r",pr_url="https://github.com/o/r/pull/7",- pr_metadata=PRMetadata(- number=7,- title="t",- state="open",- draft=False,- created_at="",- updated_at="",- author="octocat",- base_branch="main",- head_branch="feat",- head_sha="sha1",- commits=1,- additions=1,- deletions=0,- changed_files=1,- ),+ pr_metadata=self.pr_metadata,)def _record(@@ -63,6 +64,7 @@ class TestRecordTurnMarker(BaseTest):review_mode: str = REVIEW_MODE_FULL,review_design: str = REVIEW_DESIGN_PIPELINE,coordinator: bool = False,+ publishes: bool | None = None,) -> ReviewHogMarker:return record_turn_marker(team_id=team_id or self.team.id,@@ -74,6 +76,7 @@ class TestRecordTurnMarker(BaseTest):flash_reasoning_effort="medium",review_design=review_design,coordinator=coordinator,+ publishes=publishes,)def _record_single_agent(self, run_index: int, coordinator: bool = False) -> ReviewHogMarker:@@ -176,6 +179,37 @@ class TestRecordTurnMarker(BaseTest):(3, reverted.fingerprint),]+ def test_the_marker_records_what_the_turn_reviewed(self) -> None:+ for design, skipped in (+ (REVIEW_DESIGN_PIPELINE, ["yarn.lock", "tests/test_a.py"]),+ (REVIEW_DESIGN_SINGLE_AGENT, []),+ ):+ persist_pr_snapshot(+ team_id=self.team.id,+ report_id=self.report_id,+ head_sha="sha1",+ pr_metadata=self.pr_metadata,+ pr_comments=[],+ pr_files=[],+ review_design=design,+ merge_base_sha="b" * 40,+ skipped_paths=skipped,+ )++ self._record(run_index=1, publishes=True)++ row = ReviewReportArtefact.objects.for_team(self.team.id).get(+ report_id=self.report_id, type=ReviewReportArtefact.ArtefactType.TURN_MARKER+ )+ stored = parse_artefact_content(row.type, row.content)+ assert isinstance(stored, TurnMarkerArtefact)+ assert (stored.publishes, stored.base_branch, stored.base_sha, stored.skipped_paths) == (+ True,+ "main",+ "b" * 40,+ ["yarn.lock", "tests/test_a.py"],+ )+def test_an_archived_skill_sharing_name_and_version_with_the_live_one_is_ignored(self) -> None:original = self._record(run_index=1)live = LLMSkill.objects.get(team=self.team, name=REVIEW_HOG_VALIDATION_SKILL_NAME, is_latest=True)diff --git a/products/review_hog/backend/tests/test_head_review_status.py b/products/review_hog/backend/tests/test_head_review_status.pynew file mode 100644index 000000000000..d6674a1aefe8--- /dev/null+++ b/products/review_hog/backend/tests/test_head_review_status.py@@ -0,0 +1,277 @@+from datetime import timedelta++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.models.integration import Integration++from products.review_hog.backend.facade.review_status_types import HeadReviewState+from products.review_hog.backend.head_review_status import HeadReviewStatusLookup+from products.review_hog.backend.models import ReviewInstallationClaim, ReviewReport, ReviewReportArtefact+from products.review_hog.backend.receivers import review_evidence_for_stamphog+from products.review_hog.backend.reviewer.artefact_content import (+ ReviewIssueFinding,+ TurnMarkerArtefact,+ ValidationVerdict,+)+from products.review_hog.backend.reviewer.constants import (+ BLIND_SPOT_PASS_NUMBER,+ FLASH_ARM,+ REVIEW_MODE_FLASH,+ REVIEW_MODE_FULL,+)+from products.review_hog.backend.reviewer.models.issues_review import IssuePriority, IssuesReview, LineRange+from products.review_hog.backend.reviewer.models.split_pr_into_chunks import Chunk, ChunksList, FileInfo+from products.review_hog.backend.reviewer.persistence import persist_chunk_set, persist_perspective_results+from products.review_hog.backend.reviewer.progress import record_run_outcome+from products.review_hog.backend.temporal.client import QueuedReviewHeads+from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.stamphog.backend.facade.review_evidence import ReviewEvidenceState, get_review_evidence_providers++REPOSITORY = "PostHog/posthog"+HEAD = "sha1"+OLDER_HEAD = "sha0"+_QUEUE = "products.review_hog.backend.head_review_status.queued_review_heads"+++class TestHeadReviewStatus(BaseTest):+ def _report(self, **fields: object) -> ReviewReport:+ values: dict = {+ "team_id": self.team.id,+ "repository": REPOSITORY,+ "pr_number": 5,+ "pr_url": "https://github.com/PostHog/posthog/pull/5",+ "head_branch": "feat",+ "base_branch": "main",+ "status": ReviewReport.Status.IDLE,+ **fields,+ }+ return ReviewReport.objects.for_team(self.team.id).create(**values)++ def _completed_turn(+ self, review_mode: str, head_sha: str = HEAD, publishes: bool = True, **fields: object+ ) -> ReviewReport:+ report = self._report(run_count=1, head_sha=head_sha, completed_head_sha=head_sha, **fields)+ ReviewReportArtefact.add_turn_marker(+ team_id=self.team.id,+ report_id=str(report.id),+ content=TurnMarkerArtefact(+ head_sha=head_sha,+ run_index=1,+ review_mode=review_mode,+ reviewhog_version="v",+ reviewhog_fingerprint="f",+ publishes=publishes,+ base_branch="main",+ base_sha="b" * 40,+ skipped_paths=["pnpm-lock.yaml"],+ ),+ attribution=ArtefactAttribution.system(),+ )+ return report++ def _move_failure(self, report: ReviewReport, offset: timedelta) -> None:+ # Two writes in a row can share a timestamp, so the test sets the order the case needs.+ artefacts = ReviewReportArtefact.objects.for_team(self.team.id).filter(report_id=report.id)+ marker = artefacts.get(type=ReviewReportArtefact.ArtefactType.TURN_MARKER)+ artefacts.filter(type=ReviewReportArtefact.ArtefactType.NOTE).update(created_at=marker.created_at + offset)++ def _finding(self, report: ReviewReport, key: str, *, is_valid: bool) -> None:+ ReviewReportArtefact.append_finding(+ team_id=self.team.id,+ report_id=str(report.id),+ content=ReviewIssueFinding(+ issue_key=key,+ run_index=1,+ title="t",+ file="f.py",+ lines=[LineRange(start=1)],+ body="b",+ suggestion="s",+ priority=IssuePriority.MUST_FIX,+ ),+ attribution=ArtefactAttribution.system(),+ )+ ReviewReportArtefact.append_verdict(+ team_id=self.team.id,+ report_id=str(report.id),+ content=ValidationVerdict(issue_key=key, is_valid=is_valid, argumentation="a"),+ attribution=ArtefactAttribution.system(),+ )++ def _failed(self, report: ReviewReport, run_index: int) -> None:+ record_run_outcome(+ self.team.id,+ str(report.id),+ stage="review",+ outcome="failed",+ reason="review_failed",+ run_index=run_index,+ review_mode=REVIEW_MODE_FLASH,+ head_sha=HEAD,+ )++ def _nothing(self) -> None:+ pass++ def _running_turn(self) -> None:+ self._report(status=ReviewReport.Status.ACTIVE, run_count=0, head_sha=HEAD)++ def _publish_window(self) -> None:+ # Finalize already counted the turn, and the report stays ACTIVE until its findings are posted.+ self._completed_turn(REVIEW_MODE_FLASH, status=ReviewReport.Status.ACTIVE)++ def _turn_running_on_older_head(self) -> None:+ self._report(status=ReviewReport.Status.ACTIVE, run_count=0, head_sha=OLDER_HEAD)++ def _clean_standard_turn(self) -> None:+ self._completed_turn(REVIEW_MODE_FLASH)++ def _deep_turn_with_published_findings(self) -> None:+ report = self._completed_turn(REVIEW_MODE_FULL, published_head_shas={"1": HEAD})+ self._finding(report, "1-a", is_valid=True)+ self._finding(report, "1-b", is_valid=True)+ self._finding(report, "1-c", is_valid=False)++ def _eval_turn_with_findings(self) -> None:+ report = self._completed_turn(REVIEW_MODE_FULL, publishes=False)+ self._finding(report, "1-a", is_valid=True)++ def _turn_on_older_head(self) -> None:+ self._completed_turn(REVIEW_MODE_FLASH, head_sha=OLDER_HEAD)++ def _failed_first_turn(self) -> None:+ self._failed(self._report(run_count=0, head_sha=HEAD), run_index=1)++ def _failed_publish(self) -> None:+ report = self._completed_turn(REVIEW_MODE_FLASH)+ self._failed(report, run_index=1)+ self._move_failure(report, timedelta(minutes=1))++ def _retry_after_a_failed_attempt(self) -> None:+ report = self._completed_turn(REVIEW_MODE_FLASH)+ self._failed(report, run_index=1)+ self._move_failure(report, -timedelta(minutes=1))++ @parameterized.expand(+ [+ ("queued_request_for_the_head", "_nothing", ([], [HEAD]), (HeadReviewState.PENDING, "", 0, False)),+ ("queued_request_for_the_live_head", "_nothing", ([], [None]), (HeadReviewState.PENDING, "", 0, False)),+ ("queued_request_for_another_head", "_nothing", ([], [OLDER_HEAD]), None),+ ("running_turn", "_running_turn", ([], []), (HeadReviewState.PENDING, "", 0, False)),+ ("publish_window", "_publish_window", ([], []), (HeadReviewState.PENDING, "", 0, False)),+ # The active request without a head is the turn that runs on the older head.+ ("headless_request_of_a_turn_on_another_head", "_turn_running_on_older_head", ([None], []), None),+ # A waiting request without a head reviews the live head after the running turn ends.+ (+ "headless_request_waiting_behind_a_turn_on_another_head",+ "_turn_running_on_older_head",+ ([None], [None]),+ (HeadReviewState.PENDING, "", 0, False),+ ),+ (+ "clean_standard_turn",+ "_clean_standard_turn",+ ([], []),+ (HeadReviewState.COMPLETED, "Standard", 0, False),+ ),+ (+ "deep_turn_with_published_findings",+ "_deep_turn_with_published_findings",+ ([], []),+ (HeadReviewState.COMPLETED, "Deep", 2, True),+ ),+ # An eval or CLI turn posts nothing to the PR, so it is no review of the PR.+ ("eval_turn_with_findings", "_eval_turn_with_findings", ([], []), None),+ ("turn_on_an_older_head", "_turn_on_older_head", ([], []), None),+ ("failed_turn", "_failed_first_turn", ([], []), (HeadReviewState.FAILED, "", 0, False)),+ ("failed_publish", "_failed_publish", ([], []), (HeadReviewState.FAILED, "", 0, False)),+ (+ "retry_after_a_failed_attempt",+ "_retry_after_a_failed_attempt",+ ([], []),+ (HeadReviewState.COMPLETED, "Standard", 0, False),+ ),+ ]+ )+ def test_status_of_the_head(+ self,+ _name: str,+ scenario: str,+ queued_heads: tuple[list[str | None], list[str | None]],+ expected: tuple[HeadReviewState, str, int, bool] | None,+ ) -> None:+ getattr(self, scenario)()++ active, pending = queued_heads+ with patch(_QUEUE, return_value=QueuedReviewHeads(active=tuple(active), pending=tuple(pending))):+ status = HeadReviewStatusLookup(self.team.id, "posthog/PostHog", 5, HEAD).status()++ if expected is None:+ assert status is None+ return+ assert status is not None+ assert (status.state, status.review_kind, status.findings_count, status.published) == expected+ assert status.head_sha == HEAD++ @parameterized.expand([("owned", True), ("not_owned", False)])+ def test_provider_answers_only_for_a_repository_a_project_reviews(self, _name: str, owned: bool) -> None:+ # A lost registration in AppConfig.ready() would leave stamphog without this reviewer, silently.+ assert review_evidence_for_stamphog in get_review_evidence_providers()+ Integration.objects.create(+ team=self.team, kind="github", integration_id="1001", config={"account": {"name": "PostHog"}}+ )+ if owned:+ ReviewInstallationClaim.objects.for_team(self.team.id).create(+ team=self.team, installation_id="1001", scope=ReviewInstallationClaim.Scope.ALL+ )+ self._clean_standard_turn()++ with patch(_QUEUE, return_value=QueuedReviewHeads()):+ evidence = review_evidence_for_stamphog(REPOSITORY, 5, HEAD)++ if owned:+ assert evidence is not None+ assert (+ evidence.state,+ evidence.reviewer,+ evidence.review_kind,+ evidence.base_ref,+ evidence.base_sha,+ evidence.skipped_paths,+ ) == (ReviewEvidenceState.COMPLETED, "PostHog Review", "Standard", "main", "b" * 40, ("pnpm-lock.yaml",))+ else:+ assert evidence is None++ @parameterized.expand(+ [+ ("every_unit_of_a_chunk_failed", [(1, 1)], ("pnpm-lock.yaml", "c.py", "d.py")),+ ("only_the_blind_spot_read_a_chunk", [(1, 1), (BLIND_SPOT_PASS_NUMBER, 2)], ("pnpm-lock.yaml",)),+ ]+ )+ def test_deep_turn_reports_chunks_no_unit_read_as_skipped(+ self, _name: str, results: list[tuple[int, int]], expected_skipped: tuple[str, ...]+ ) -> None:+ report = self._completed_turn(REVIEW_MODE_FULL)+ chunks = ChunksList(+ chunks=[+ Chunk(chunk_id=1, files=[FileInfo(filename="a.py"), FileInfo(filename="b.py")]),+ Chunk(chunk_id=2, files=[FileInfo(filename="c.py"), FileInfo(filename="d.py")]),+ ]+ )+ persist_chunk_set(team_id=self.team.id, report_id=str(report.id), head_sha=HEAD, chunks=chunks)+ persist_perspective_results(+ team_id=self.team.id,+ report_id=str(report.id),+ head_sha=HEAD,+ results={unit: IssuesReview() for unit in results},+ review_arm=FLASH_ARM,+ )++ with patch(_QUEUE, return_value=QueuedReviewHeads()):+ status = HeadReviewStatusLookup(self.team.id, REPOSITORY, 5, HEAD).status()++ assert status is not None+ assert (status.state, status.skipped_paths) == (HeadReviewState.COMPLETED, expected_skipped)diff --git a/products/review_hog/backend/tests/test_review_scheduling.py b/products/review_hog/backend/tests/test_review_scheduling.pyindex 9cf3a27c6d69..aef327cbe62c 100644--- a/products/review_hog/backend/tests/test_review_scheduling.py+++ b/products/review_hog/backend/tests/test_review_scheduling.py@@ -94,6 +94,9 @@ async def test_pushes_coalesce_and_full_requests_survive_an_active_flash_review(start_signal="request_review",start_signal_args=[request],)+ # Stamphog reads the waiting heads from this query, because they exist only in the queue.+ heads = await handle.query("requested_heads")+ assert (heads["active"], sorted(heads["pending"])) == (["a"], ["c", "c"])release.set()assert await handle.result() == "report"diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.pyindex 268f94917adb..cc644e9925bc 100644--- a/products/review_hog/backend/tests/test_temporal_workflow.py+++ b/products/review_hog/backend/tests/test_temporal_workflow.py@@ -10,6 +10,7 @@ from datetime import timedeltafrom typing import ClassVarimport pytest+from unittest.mock import patchimport temporalio.workerimport temporalio.workflow@@ -63,9 +64,11 @@ from products.review_hog.backend.temporal.activities import (TrackReviewCompletedInput,TrackReviewFailedInput,TrackReviewStartedInput,+ TurnEndedInput,ValidateChunkInput,ValidateChunkResult,ValidateIntegrationInput,+ _nudge_stamphog,)from products.review_hog.backend.temporal.resolution import (FailResolutionInput,@@ -163,6 +166,8 @@ async def _run_full_review_pr_workflow(gate_skips: bool = False,fail_gate: bool = False,workflow_max_attempts: int | None = None,+ publish_posts: bool = True,+ fail_nudge: bool = False,) -> dict:# Runs the real ReviewPRWorkflow with activity stand-ins, recording what fanned out + published.# already_published / empty_diff drive the early-exit gates; acting_user_id None means the author@@ -382,7 +387,7 @@ async def _run_full_review_pr_workflow(_saw_mode("publish", input.review_mode)publish_calls.append(input.pr_number)threshold_calls.append(("publish", input.urgency_threshold))- return PublishResult(posted=True, review_url=_REVIEW_URL)+ return PublishResult(posted=publish_posts, review_url=_REVIEW_URL if publish_posts else None)@activity.defn(name="remove_trigger_label_activity")async def remove_label(input: RemoveTriggerLabelInput) -> None:@@ -428,6 +433,15 @@ async def _run_full_review_pr_workflow(async def remove_reaction(input: ReviewReactionInput) -> None:reaction_calls.append(("remove", input.reaction_id))+ # Each stamphog nudge as (repository, pr_number, head_sha).+ nudge_calls: list[tuple[str, int, str]] = []++ @activity.defn(name="nudge_stamphog_activity")+ async def nudge(input: TurnEndedInput) -> None:+ nudge_calls.append((input.repository, input.pr_number, input.head_sha))+ if fail_nudge:+ raise ApplicationError("stamphog unavailable", non_retryable=True)+# Records the analytics events' run_index and the turn's trigger — the completion-rate# denominator and the per-tier split rely on them; all three captures are swallowed best-effort# in the workflow, so without these stubs deleting any of them would leave every test green.@@ -501,6 +515,7 @@ async def _run_full_review_pr_workflow(fail_status,add_reaction,remove_reaction,+ nudge,track_failed,track_completed,track_started,@@ -575,6 +590,7 @@ async def _run_full_review_pr_workflow("status_posts": status_posts,"fail_status": fail_status_calls,"reactions": reaction_calls,+ "nudges": nudge_calls,}@@ -584,6 +600,7 @@ async def test_review_pr_workflow_runs_all_stages_and_fans_out():assert recorded["result"] == "rep-1"# An eval / CLI run keeps zero GitHub footprint.assert recorded["reactions"] == []+ assert recorded["nudges"] == []# Review fans out per (perspective × chunk), then the always-on blind-spot check adds one unit# per chunk; validate fans out one warm session per chunk.wave = [c for c in recorded["review"] if not c[2]]@@ -670,6 +687,36 @@ async def test_review_pr_workflow_publishes_only_when_publish_true():assert recorded["reactions"] == [("add",), ("remove", 42)]+ "fail_dedup, publish_posts, fail_nudge",+ [+ pytest.param(False, True, False, id="completed"),+ pytest.param(False, False, False, id="clean"),+ pytest.param(True, True, False, id="failed"),+ pytest.param(False, True, True, id="raising-nudge-keeps-the-turn"),+ ],+)+async def test_review_pr_workflow_nudges_stamphog_when_the_turn_ends(+ fail_dedup: bool, publish_posts: bool, fail_nudge: bool+):+ # Stamphog stops waiting before a Deep turn ends, so only this nudge re-runs a stamphog WAIT.+ recorded = await _run_full_review_pr_workflow(+ publish=True, fail_dedup=fail_dedup, publish_posts=publish_posts, fail_nudge=fail_nudge+ )+ assert recorded["failed"] is fail_dedup+ assert recorded["nudges"] == [("o/r", 7, "sha1")]+++def test_nudge_stamphog_raises_a_dispatch_error_so_temporal_retries_it():+ with patch(+ "products.review_hog.backend.temporal.activities.request_rereview_after_external_review",+ side_effect=ConnectionError("broker down"),+ ):+ with pytest.raises(ConnectionError):+ _nudge_stamphog(TurnEndedInput(repository="o/r", pr_number=7, head_sha="sha1"))++@pytest.mark.asyncioasync def test_review_pr_workflow_removes_label_trigger_after_completion():recorded = await _run_full_review_pr_workflow(publish=True, trigger_source="label")diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.mdindex 07454cf2f42b..c8add9f4b69a 100644--- a/products/stamphog/AGENTS.md+++ b/products/stamphog/AGENTS.md@@ -187,6 +187,15 @@ The requester's own GitHub access is not checked; the `stamphog:write` scope andThe run is stamped `manual_review` provenance and the `manual` trigger, and it enters the workflow through `dismiss_stale_approvals` like every other run.A refusal writes nothing to GitHub and creates no run, so it cannot leave or remove an approval.+## External review evidence++- `facade/review_evidence.py` is a registry of providers that stamphog owns. A product that reviews PRs and depends on stamphog (today review_hog, as PostHog Review) registers one at app-ready, for the same dependency-cycle reason as `inbox_hooks.py`. Stamphog never imports a provider's product.+- Each provider answers per head (`pending`, `completed`, `failed`, or None). `list_in_flight_reviewer_bots` asks every provider on every wait poll and stores the answers as `run.output["review_evidence"]`. Any pending review keeps the workflow waiting within the bot-wait budget. After any wait, or when a provider reports a completed review, `refresh_review_evidence` reads the reviews, the discussion and the threads again, because the context fetch ran before the polls.+- In the engine, any review still pending for the head is a WAIT, never an approval. Each completed review of the current head against the current merge base (`base_sha`) counts as current-head assurance in `_cap_assurance_facts` only when its `skipped_paths` is empty. The PR's `base.sha` is no match key, because it moves on every merge to the base branch. Each one gets its own line in the assurance summary and the posted verdict. Its published findings are review threads, so the unresolved-thread rule still applies to them.+- A provider error is logged and skipped without affecting the other providers. An error, an answer for another head, and `failed` add no evidence, so stamphog reviews as it would without that provider. An error must never read as a clean review. The one exception: a provider that reported `pending` earlier in the run keeps that pending answer (marked `provider_error`), so the run ends in WAIT.+- A WAIT has no automatic retry, and a Deep review outlasts the wait budget. So ReviewHog calls `facade/tasks.py::request_rereview_after_external_review` when a turn on a head completes or fails. The Celery task re-reviews only when the PR's latest run is COMPLETED with a WAIT verdict at that head, the head is still current, the run is not an inbox run, and every webhook gate passes again (open, payload pre-filters, trigger label unless the run was manual, author write access). It passes `revisit_wait` to `_queue_review_at_head`, so the head dedupe ignores every delivered WAIT at the head but still collapses repeated nudges into one live run. A re-run left QUEUED by a failed workflow start is restarted by the next call, and GitHub or Temporal errors retry with backoff. A nudge that arrives while the run is in flight finds no WAIT, so after a WAIT that waited on a pending review the workflow runs `rereview_after_external_review_finished`. It asks the providers once more and queues the re-review when that review has finished. A provider error keeps that review pending there too and raises, so Temporal retries the recheck. A dispatch error raises, so Temporal retries it.+- `posthog[bot]` is deliberately not a trusted reactor. Its 👀 is a cue for people, and the review evidence replaces it for stamphog.+## Trust boundaries- Turning reviews **off** (`enabled=False`, the soft-delete) and changing when they run (`review_mode`,diff --git a/products/stamphog/backend/facade/review_evidence.py b/products/stamphog/backend/facade/review_evidence.pynew file mode 100644index 000000000000..1cf28531d8db--- /dev/null+++ b/products/stamphog/backend/facade/review_evidence.py@@ -0,0 +1,66 @@+"""Registry of external reviewers that can tell stamphog where their review of a PR head stands.++A product that reviews pull requests registers a provider from its ``AppConfig.ready()``. Stamphog+cannot import such a product when that product already depends on stamphog, so the provider comes+to stamphog through this registry. Stamphog's review workflow asks every registered provider. A+pending review keeps stamphog waiting, and a completed review of the current head and merge base+counts as assurance only when it skipped no file. A provider that raises adds nothing, except that+a review it reported as pending earlier in the run stays pending. With no provider stamphog+reviews as before. Mirrors ``inbox_hooks.py``.++Keep this module light. ``AppConfig.ready()`` imports it on the django.setup() path, so it must+never import Django models or heavy product internals.+"""++from __future__ import annotations++from collections.abc import Callable+from dataclasses import dataclass+from enum import StrEnum+++class ReviewEvidenceState(StrEnum):+ # Accepted but not started, or running. A review stays pending until its findings are on the PR.+ PENDING = "pending"+ COMPLETED = "completed"+ FAILED = "failed"+++@dataclass(frozen=True, kw_only=True)+class ReviewEvidence:+ """Where one external review of one PR head stands."""++ state: ReviewEvidenceState+ # The reviewer's name as people see it on the PR.+ reviewer: str+ # The review depth as people see it. Empty when the reviewer does not know it yet.+ review_kind: str+ # Valid findings of a completed review. Zero while pending or failed.+ findings_count: int+ # True when the review posted on the PR. A clean review can post nothing, so it stays False.+ published: bool+ head_sha: str+ # The base branch the review took the diff against, for people to read.+ base_ref: str = ""+ # The merge base the review took the diff against. A retarget or a base merge into the head+ # changes the diff, so a review with another or an empty merge base does not count.+ base_sha: str = ""+ # The changed files the review left out. It is no assurance for those files.+ skipped_paths: tuple[str, ...] = ()+++# (repository "owner/name", pr_number, head_sha) -> the evidence for exactly that head, or None+# when the reviewer knows no review of that head.+ReviewEvidenceProvider = Callable[[str, int, str], ReviewEvidence | None]++_review_evidence_providers: list[ReviewEvidenceProvider] = []+++def register_review_evidence_provider(fn: ReviewEvidenceProvider) -> None:+ # AppConfig.ready() can run more than once in one process, for example in tests.+ if fn not in _review_evidence_providers:+ _review_evidence_providers.append(fn)+++def get_review_evidence_providers() -> tuple[ReviewEvidenceProvider, ...]:+ return tuple(_review_evidence_providers)diff --git a/products/stamphog/backend/facade/tasks.py b/products/stamphog/backend/facade/tasks.pyindex b6d3974ec17e..aa16c52ba592 100644--- a/products/stamphog/backend/facade/tasks.py+++ b/products/stamphog/backend/facade/tasks.py@@ -13,6 +13,7 @@ from products.stamphog.backend.tasks.tasks import (process_inbox_pr_review,process_installation_event,process_pull_request_event,+ request_rereview_after_external_review,)__all__ = [@@ -20,6 +21,7 @@ __all__ = ["process_installation_event","process_pull_request_event","queue_inbox_pr_review",+ "request_rereview_after_external_review","send_daily_digests",]diff --git a/products/stamphog/backend/logic/reviewer.py b/products/stamphog/backend/logic/reviewer.pyindex c666be8f68e9..f322478bf4e8 100644--- a/products/stamphog/backend/logic/reviewer.py+++ b/products/stamphog/backend/logic/reviewer.py@@ -121,6 +121,7 @@ def build_reviewer_invocation(context_path: str,self_driving_review: bool = False,review_trigger: str = "",+ review_evidence: list[dict] | None = None,) -> ReviewerInvocation:"""Assemble the context payload + command that reviews this PR in the sandbox.@@ -135,6 +136,9 @@ def build_reviewer_invocation(``author_team_slugs`` are every GitHub team the author belongs to, which theengine intersects with the teams owning the changed paths to tell the reviewerwhether the author owns the code (another `gh` call the sandbox can't make).+ ``review_evidence`` holds each registered external reviewer's status for this head+ (``facade/review_evidence.py``). The engine waits on a pending one and counts a completed one+ as assurance.``familiarity_facts`` are the blame and author-history facts the server read from GitHub(``logic/familiarity_facts.py``), or None when that failed. The key is always set, becauseits presence tells the engine to take familiarity from the facts and never from git history.@@ -165,6 +169,7 @@ def build_reviewer_invocation("review_threads": review_threads,"check_runs": check_runs,"pr_reactions": pr_reactions,+ "review_evidence": list(review_evidence or []),"author_pr_numbers": list(author_pr_numbers),"author_team_slugs": list(author_team_slugs),"familiarity_facts": familiarity_facts,diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.pyindex d7e1be80fd85..7a72127e6336 100644--- a/products/stamphog/backend/tasks/tasks.py+++ b/products/stamphog/backend/tasks/tasks.py@@ -18,7 +18,7 @@ from django.utils.dateparse import parse_datetimeimport requestsimport structlog-from celery import shared_task+from celery import Task, shared_taskfrom posthog.dataclasses import frozenfrom posthog.egress.github.transport import GitHubRateLimitError@@ -138,6 +138,9 @@ WRITE_PERMISSIONS = frozenset({"admin", "write"})_AUTHOR_PERMISSION_ALLOW_CACHE_SECONDS = 60_AUTHOR_PERMISSION_DENY_CACHE_SECONDS = 10 * 60+_REREVIEW_MAX_RETRIES = 4+_REREVIEW_RETRY_BASE_SECONDS = 30+# Anchored to the canonical host so a lookalike ("fakegithub.com", a github.com path segment on# another host) never parses; output.pr_url is caller-writable, and the host must not be one more@@ -1399,7 +1402,12 @@ class _HeadQueueResult:def _queue_review_at_head(- repo_config: StamphogRepoConfig, pr: dict[str, Any], head_sha: str, *, output: dict[str, Any]+ repo_config: StamphogRepoConfig,+ pr: dict[str, Any],+ head_sha: str,+ *,+ output: dict[str, Any],+ revisit_wait: bool = False,) -> _HeadQueueResult:"""Create a QUEUED run for the PR's current head, or return the run that already covers it.@@ -1408,6 +1416,10 @@ def _queue_review_at_head(delivered run at this head is returned as is, and a QUEUED one lost its workflow start, so itsworkflow restarts on commit. Otherwise older live runs are superseded and a fresh run startsonce the row commits. Errors propagate so the caller can retry or report them.++ ``revisit_wait`` stops a delivered WAIT at this head from counting as covering it, because+ the caller wants that verdict revisited. A live run at this head still counts, so repeated+ requests collapse into one run."""team_id = repo_config.team_idrun_write_db = router.db_for_write(ReviewRun)@@ -1423,15 +1435,16 @@ def _queue_review_at_head():return _HeadQueueResult(run=None, created=False)# Dedupe repeat requests against the current head; the row lock serializes races.- existing = (+ covering_runs = (ReviewRun.objects.for_team(team_id).using(run_write_db).select_for_update().filter(pull_request=pr_obj, head_sha=head_sha).exclude(status__in=(ReviewRunStatus.SUPERSEDED, ReviewRunStatus.FAILED))- .order_by("-created_at")- .first())+ if revisit_wait:+ covering_runs = covering_runs.exclude(status=ReviewRunStatus.COMPLETED, verdict=ReviewVerdict.WAIT)+ existing = covering_runs.order_by("-created_at").first()# A retarget changes the diff without moving the head, and in label mode no webhook run# replaces the old verdict. A run that reviewed another base branch does not cover this one.reviewed_base_ref = _reviewed_base_ref(existing) if existing is not None else ""@@ -1697,3 +1710,89 @@ def request_manual_review(team_id: int, user_id: int | None, repository: str, prteam_id=team_id,)return QueuedReview(run=queued.run, created=queued.created)+++def _rereview_waiting_run(repo_config: StamphogRepoConfig, pr_number: int, head_sha: str) -> None:+ """Queue a new review when this PR's latest verdict is a WAIT at ``head_sha`` that is still the PR head."""+ team_id = repo_config.team_id+ latest = (+ ReviewRun.objects.for_team(team_id)+ .using(router.db_for_write(ReviewRun))+ .filter(pull_request__repo_config=repo_config, pull_request__pr_number=pr_number)+ .order_by("-created_at")+ .first()+ )+ if latest is None or latest.head_sha != head_sha:+ return+ previous_output = latest.output or {}+ # Only an engine WAIT can change when another reviewer finishes. A GATED WAIT waits on a check.+ waiting = latest.status == ReviewRunStatus.COMPLETED and latest.verdict == ReviewVerdict.WAIT+ # A run that an earlier call queued and whose workflow start failed stays QUEUED. Queueing again+ # restarts its workflow, so a retry or a later call recovers it.+ stranded = latest.status == ReviewRunStatus.QUEUED and bool(previous_output.get("rereview_after_external_review"))+ if not (waiting or stranded):+ return+ # Inbox runs carry the self-driving carve-out, which only the inbox trigger paths may grant.+ if previous_output.get("inbox_review"):+ return+ repo = repo_config.repository+ pr = StamphogGitHubClient(repo_config.installation_id).get_pr(repo, pr_number)+ if (pr.get("state") or "") != "open" or (pr.get("head") or {}).get("sha") != head_sha:+ return+ if _review_skip_reason(pr) is not None:+ return+ is_manual = bool(previous_output.get("manual_review"))+ label_names = {(label or {}).get("name") for label in pr.get("labels") or []}+ if repo_config.review_mode == ReviewMode.LABEL and not is_manual and repo_config.trigger_label not in label_names:+ return+ if _author_lacks_write_permission(repo_config, repo, pr):+ return+ output: dict[str, Any] = {"rereview_after_external_review": True}+ for key in ("manual_review", "review_trigger"):+ if key in previous_output:+ output[key] = previous_output[key]+ queued = _queue_review_at_head(repo_config, pr, head_sha, output=output, revisit_wait=True)+ logger.info(+ "stamphog_rereview_after_external_review",+ repository=repo,+ pr_number=pr_number,+ review_run_id=str(queued.run.id) if queued.run is not None else None,+ created=queued.created,+ team_id=team_id,+ )+++@shared_task(bind=True, ignore_result=True, max_retries=_REREVIEW_MAX_RETRIES)+def rereview_after_external_review(self: Task, repository: str, pr_number: int, head_sha: str) -> None:+ """Re-run a review that ended in WAIT, because an automated reviewer finished with ``head_sha``.++ The caller knows only the repository, so the configs are read across teams. Each config acts on+ its own runs, and every check runs again here, so a stray call never starts a review that the+ webhook path would refuse. A GitHub or Temporal error retries with backoff, because no webhook+ redelivery stands behind this call. A retry is safe: every step checks the state again.+ """+ repo_configs = (+ StamphogRepoConfig.objects.unscoped()+ .using(router.db_for_write(StamphogRepoConfig))+ .filter(provider="github", repository__iexact=repository, enabled=True, connected_by_user_id__isnull=False)+ .exclude(installation_id="")+ )+ try:+ for repo_config in repo_configs:+ _rereview_waiting_run(repo_config, pr_number, head_sha)+ except GitHubRateLimitError as e:+ logger.warning("stamphog_rereview_rate_limited", repository=repository, pr_number=pr_number)+ raise self.retry(exc=e, countdown=max(e.retry_after or 0, 60))+ except Exception as e:+ logger.exception("stamphog_rereview_failed", repository=repository, pr_number=pr_number, error=str(e))+ raise self.retry(exc=e, countdown=_REREVIEW_RETRY_BASE_SECONDS * 2**self.request.retries)+++def request_rereview_after_external_review(*, repository: str, pr_number: int, head_sha: str) -> None:+ """Tell stamphog that an automated review of ``head_sha`` finished, without waiting.++ Called by review_hog when a review turn ends, completed or failed. Stamphog decides whether+ anything happens: it re-reviews only a PR whose latest verdict is a WAIT at that head, while the+ head is still current. Any other call is a no-op, so a caller may call it for every turn.+ """+ rereview_after_external_review.delay(repository=repository, pr_number=pr_number, head_sha=head_sha)diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.pyindex 561aa9dc25d4..8c2749b01197 100644--- a/products/stamphog/backend/temporal/activities.py+++ b/products/stamphog/backend/temporal/activities.py@@ -63,6 +63,11 @@ from products.stamphog.backend.facade.enums import (ReviewTrigger,ReviewVerdict,)+from products.stamphog.backend.facade.review_evidence import (+ ReviewEvidenceProvider,+ ReviewEvidenceState,+ get_review_evidence_providers,+)from products.stamphog.backend.logic.approvals import dismiss_stale_approvals_for_headfrom products.stamphog.backend.logic.audiences import resolve_audiencesfrom products.stamphog.backend.logic.engine_pregate import (@@ -87,6 +92,7 @@ from products.stamphog.backend.logic.reviewer import ()from products.stamphog.backend.logic.scrubbing import neutralize_active_markdown, scrub_credentialsfrom products.stamphog.backend.models import PullRequest, PullRequestAudience, ReviewRun, StamphogRepoConfig+from products.stamphog.backend.tasks.tasks import request_rereview_after_external_reviewfrom products.stamphog.backend.temporal.constants import (CLONE_STEP_TIMEOUT_SECONDS,NETWORK_RESTRICTED_AGENT_ENV,@@ -683,20 +689,72 @@ def signal_review_started(input: StamphogReviewInput) -> dict:return {"reaction_id": reaction_id}+def _provider_key(provider: ReviewEvidenceProvider) -> str:+ """A name for the provider that stays the same across activity attempts and workers."""+ return f"{provider.__module__}.{getattr(provider, '__qualname__', '')}"+++def _read_review_evidence(run: ReviewRun, earlier: list[dict]) -> list[dict]:+ """Each registered external reviewer's evidence for the run's head, as the engine reads it.++ A provider that answers None or answers for another head adds nothing. A provider that raises+ adds nothing too, unless ``earlier`` (the evidence of an earlier poll in this run) holds a+ pending review from it. That review stays pending, marked ``provider_error``, so an error after+ a pending answer ends the run in WAIT and never lets it approve. An error can never read as a+ clean review, and one failing provider never hides another's answer.+ """+ pending_earlier = {+ item.get("provider"): item+ for item in earlier+ if item.get("state") == ReviewEvidenceState.PENDING and item.get("head_sha") == run.head_sha+ }+ pull_request = run.pull_request+ evidence: list[dict] = []+ for provider in get_review_evidence_providers():+ key = _provider_key(provider)+ try:+ item = provider(pull_request.repo_config.repository, pull_request.pr_number, run.head_sha)+ except Exception:+ activity.logger.warning(f"Run {run.id}: review evidence provider {key} failed", exc_info=True)+ if key in pending_earlier:+ evidence.append({**pending_earlier[key], "provider_error": True})+ continue+ if item is None or item.head_sha != run.head_sha:+ continue+ evidence.append(+ {+ "provider": key,+ "provider_error": False,+ "state": str(item.state),+ "reviewer": item.reviewer,+ "review_kind": item.review_kind,+ "findings_count": item.findings_count,+ "published": item.published,+ "head_sha": item.head_sha,+ "base_ref": item.base_ref,+ "base_sha": item.base_sha,+ "skipped_paths": list(item.skipped_paths),+ }+ )+ return evidence++@activity.defn@asyncifydef list_in_flight_reviewer_bots(input: StamphogReviewInput) -> dict:- """Allowlisted reviewer bots with a fresh 👀 on the PR, refreshing the stored snapshot.+ """Reviewers still working on the PR, refreshing the stored reactions and review status.- The Action waits these bots out by polling GitHub from the runner; the hosted sandbox holds no+ Two signals count. An allowlisted reviewer bot with a fresh 👀 on the PR, and a registered+ external reviewer (``facade/review_evidence.py``) reporting a pending review of this head.+ The Action waits bots out by polling GitHub from the runner; the hosted sandbox holds notoken, so the WORKFLOW polls this activity instead, sleeping on durable timers between calls.- Each call re-fetches the reactions and refreshes ``run.output["pr_reactions"]`` so the sandbox- context reflects the latest snapshot — if the wait budget expires with a bot still in flight,- the engine sees the fresh 👀 and returns WAIT rather than approving over an unfinished review.+ Each call refreshes ``run.output["pr_reactions"]`` and ``run.output["review_evidence"]`` so the+ sandbox context reflects the latest snapshot. If the wait budget expires with a reviewer still+ in flight, the engine sees it and returns WAIT rather than approving over an unfinished review."""run = _load_run(input)if run.status == ReviewRunStatus.SUPERSEDED:- return {"in_flight": []}+ return {"in_flight": [], "reviews_completed": False}started_at = timezone.now()repo_config = run.pull_request.repo_configclient = StamphogGitHubClient(repo_config.installation_id)@@ -711,7 +769,8 @@ def list_in_flight_reviewer_bots(input: StamphogReviewInput) -> dict:"polls": int(bot_wait.get("polls") or 0) + 1,"ms": int((now - first_started_at).total_seconds() * 1000),}- _merge_run_output(run, {"pr_reactions": reactions, "bot_wait": bot_wait})+ review_evidence = _read_review_evidence(run, (run.output or {}).get("review_evidence") or [])+ _merge_run_output(run, {"pr_reactions": reactions, "review_evidence": review_evidence, "bot_wait": bot_wait})# Exclude stamphog's own bot login: STAMPHOG_TRUSTED_REACTOR_BOTS is a hardcoded set of OTHER# reviewer bots' logins, so this app's own 👀 (posted by signal_review_started) can't collide@@ -729,9 +788,39 @@ def list_in_flight_reviewer_bots(input: StamphogReviewInput) -> dict:and (now - created).total_seconds() <= STAMPHOG_BOT_EYES_MAX_AGE_SECONDS})+ in_flight += [item["reviewer"] for item in review_evidence if item["state"] == ReviewEvidenceState.PENDING]if in_flight:- activity.logger.info(f"Run {run.id}: reviewer bot(s) in flight: {', '.join(in_flight)}")- return {"in_flight": in_flight}+ activity.logger.info(f"Run {run.id}: reviewer(s) in flight: {', '.join(in_flight)}")+ reviews_completed = any(item["state"] == ReviewEvidenceState.COMPLETED for item in review_evidence)+ return {"in_flight": in_flight, "reviews_completed": reviews_completed}+++@asyncify+def refresh_review_evidence(input: StamphogReviewInput) -> dict:+ """Re-read the reviews, discussion and inline threads before the engine counts an external review.++ ``fetch_review_context`` reads them before the wait polls. A review posted during the wait, or+ one that completed just before the first poll, can be missing from that read, and the engine+ would then count the completed review over threads it never saw. The reactions and the review+ evidence are already fresh, because the last wait poll read them.+ """+ run = _load_run(input)+ if run.status == ReviewRunStatus.SUPERSEDED:+ return {"skipped": "superseded"}+ repo_config = run.pull_request.repo_config+ repo = repo_config.repository+ number = run.pull_request.pr_number+ client = StamphogGitHubClient(repo_config.installation_id)+ _merge_run_output(+ run,+ {+ "reviews": client.get_pr_reviews(repo, number),+ "discussion": client.get_pr_discussion(repo, number),+ "review_threads": client.get_pr_review_threads(repo, number),+ },+ )+ return {"refreshed": True}def _sandbox_deadline(timeout: timedelta) -> float:@@ -799,6 +888,7 @@ def _review_invocation(run: ReviewRun, merge_base_sha: str | None) -> ReviewerInreview_threads=output.get("review_threads", []),check_runs=output.get("check_runs", []),pr_reactions=output.get("pr_reactions", []),+ review_evidence=output.get("review_evidence") or [],author_pr_numbers=output.get("author_pr_numbers", []),author_team_slugs=output.get("author_team_slugs", []),# A run whose context predates the server facts gets None, which the engine reads as an@@ -1532,6 +1622,46 @@ def _capture_review_timings(run: ReviewRun, verdict: str, post_verdict_ms: int)activity.logger.exception(f"Failed to capture review timings for run {run.id}")+def _waited_on_external_review(run: ReviewRun) -> bool:+ """True when the run saved a WAIT while an external review of its head was pending."""+ if run.status != ReviewRunStatus.COMPLETED or run.verdict != ReviewVerdict.WAIT:+ return False+ return any(+ item.get("state") == ReviewEvidenceState.PENDING and item.get("head_sha") == run.head_sha+ for item in (run.output or {}).get("review_evidence") or []+ )+++@asyncify+def rereview_after_external_review_finished(input: StamphogReviewInput) -> dict:+ """Queue a re-review when this WAIT waited on an external review that finished since the last poll.++ The external reviewer asks stamphog to re-review when its review ends, but that request finds+ no WAIT while this run is still in flight and does nothing. So the run asks the providers once+ more after it saved its WAIT. A dispatch error raises, so Temporal retries it, because a lost+ dispatch leaves the PR at WAIT until the next push.+ """+ run = _load_run(input)+ if not _waited_on_external_review(run):+ return {"requested": False}+ # The run's own evidence is the earlier answer, so a provider error keeps the review pending. A+ # re-review queued on an error would start without that evidence and could approve too early.+ earlier = (run.output or {}).get("review_evidence") or []+ pending = [item for item in _read_review_evidence(run, earlier) if item["state"] == ReviewEvidenceState.PENDING]+ # The reviewer's nudge can come before the WAIT is saved and find nothing to re-review, so an+ # unanswered provider must retry here rather than leave the PR at WAIT.+ if any(item.get("provider_error") for item in pending):+ raise RuntimeError(f"Run {run.id}: a review evidence provider failed; retrying the recheck")+ if pending:+ return {"requested": False}+ pull_request = run.pull_request+ request_rereview_after_external_review(+ repository=pull_request.repo_config.repository, pr_number=pull_request.pr_number, head_sha=run.head_sha+ )+ return {"requested": True}++@activity.defn@asyncifydef post_verdict(input: StamphogReviewInput) -> dict:@@ -1765,7 +1895,7 @@ def post_verdict(input: StamphogReviewInput) -> dict:_capture_review_timings(run, str(parsed.verdict), int((time.monotonic() - post_started) * 1000))activity.logger.info(f"Posted verdict {parsed.verdict} for run {run.id}")- return {"verdict": str(parsed.verdict)}+ return {"verdict": str(parsed.verdict), "waited_on_external_review": _waited_on_external_review(run)}@activity.defndiff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.pyindex c6635dee1254..42a4dad150a0 100644--- a/products/stamphog/backend/temporal/constants.py+++ b/products/stamphog/backend/temporal/constants.py@@ -31,8 +31,6 @@ STAMPHOG_TRUSTED_REACTOR_BOTS = frozenset("copilot-pull-request-reviewer[bot]","greptile-apps[bot]","hex-security-app[bot]",- # PostHog Review, which posts as the PostHog GitHub App.- "posthog[bot]","veria-ai[bot]",})diff --git a/products/stamphog/backend/temporal/registry.py b/products/stamphog/backend/temporal/registry.pyindex 9c58f9fe4675..9b2e943b1299 100644--- a/products/stamphog/backend/temporal/registry.py+++ b/products/stamphog/backend/temporal/registry.py@@ -14,7 +14,9 @@ from products.stamphog.backend.temporal.activities import (list_in_flight_reviewer_bots,mark_review_failed,post_verdict,+ refresh_review_evidence,refuse_on_pre_gates,+ rereview_after_external_review_finished,review_in_sandbox,run_review_in_sandbox,signal_review_started,@@ -32,9 +34,11 @@ ACTIVITIES = [checkout_review_sandbox,refuse_on_pre_gates,list_in_flight_reviewer_bots,+ refresh_review_evidence,review_in_sandbox,run_review_in_sandbox,destroy_review_sandbox,+ rereview_after_external_review_finished,post_verdict,mark_review_failed,]diff --git a/products/stamphog/backend/temporal/workflow.py b/products/stamphog/backend/temporal/workflow.pyindex edc0c297eb1c..43a31f6066cc 100644--- a/products/stamphog/backend/temporal/workflow.py+++ b/products/stamphog/backend/temporal/workflow.py@@ -46,7 +46,9 @@ with temporalio.workflow.unsafe.imports_passed_through():list_in_flight_reviewer_bots,mark_review_failed,post_verdict,+ refresh_review_evidence,refuse_on_pre_gates,+ rereview_after_external_review_finished,review_in_sandbox,run_review_in_sandbox,signal_review_started,@@ -132,11 +134,14 @@ class StamphogReviewWorkflow(PostHogWorkflow):workflow.logger.warning(f"stamphog pre-gates failed for run {input.review_run_id}")if not refused_on_pre_gates:- # Wait out in-flight reviewer bots (fresh trusted-bot 👀) before the review: the- # sandbox holds no token to poll GitHub with, so the Action's wait-and-poll lives here- # as durable timers. Each poll refreshes the stored reactions snapshot; if the budget- # expires with a bot still in flight, the run proceeds and the engine sees the fresh 👀- # and returns WAIT rather than approving over an unfinished review.+ # Wait out in-flight reviewers (fresh trusted-bot 👀, or a pending external review of+ # this head) before the review: the sandbox holds no token to poll GitHub with, so the+ # Action's wait-and-poll lives here as durable timers. Each poll refreshes the stored+ # reactions and review status; if the budget expires with a reviewer still in flight,+ # the run proceeds and the engine sees it and returns WAIT rather than approving over+ # an unfinished review.+ waited = False+ reviews_completed = Falsefor _ in range(STAMPHOG_BOT_REVIEW_MAX_POLLS):bots = await workflow.execute_activity(list_in_flight_reviewer_bots,@@ -144,10 +149,23 @@ class StamphogReviewWorkflow(PostHogWorkflow):start_to_close_timeout=FETCH_CONTEXT_TIMEOUT,retry_policy=ACTIVITY_RETRY_POLICY,)+ reviews_completed = bool(bots.get("reviews_completed"))if not bots["in_flight"]:break+ waited = Trueawait asyncio.sleep(STAMPHOG_BOT_REVIEW_POLL_SECONDS)+ # The context was read before the polls, so a review posted during the wait, or by an+ # external reviewer that completed before the first poll, would be missing. Gated for+ # replay like the eyes reaction above.+ if (waited or reviews_completed) and workflow.patched("stamphog-refresh-after-wait"):+ await workflow.execute_activity(+ refresh_review_evidence,+ input,+ start_to_close_timeout=FETCH_CONTEXT_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+if sandbox_checkout is None:await workflow.execute_activity(run_review_in_sandbox,@@ -169,6 +187,18 @@ class StamphogReviewWorkflow(PostHogWorkflow):start_to_close_timeout=POST_VERDICT_TIMEOUT,retry_policy=ACTIVITY_RETRY_POLICY,)+ # A final dispatch failure must not fail the run, because the verdict is already posted.+ # Gated for replay like the eyes reaction above.+ if result.get("waited_on_external_review") and workflow.patched("stamphog-rereview-activity"):+ try:+ await workflow.execute_activity(+ rereview_after_external_review_finished,+ input,+ start_to_close_timeout=POST_VERDICT_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ except ActivityError:+ workflow.logger.warning(f"stamphog re-review dispatch failed for run {input.review_run_id}")if refused_on_pre_gates and sandbox_start is not None:# After the verdict, so a pre-check verdict posts without waiting for the clone.await self._discard_sandbox(input, sandbox_start, sandbox_checkout)diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.pyindex d0037e2c205d..c32ab5483993 100644--- a/products/stamphog/backend/tests/test_integration.py+++ b/products/stamphog/backend/tests/test_integration.py@@ -3,15 +3,17 @@ import jsonimport uuidimport threadingfrom contextlib import nullcontext+from datetime import timedeltafrom pathlib import Pathimport pytest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchfrom django.test import override_settingsfrom django.utils import timezoneimport requests+from celery.exceptions import Retryfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models import OAuthAccessToken, Team@@ -27,6 +29,7 @@ from products.stamphog.backend.facade.enums import (ReviewRunStatus,ReviewVerdict,)+from products.stamphog.backend.facade.review_evidence import ReviewEvidence, ReviewEvidenceProvider, ReviewEvidenceStatefrom products.stamphog.backend.logic.channel_resolution import (RoutingContext,build_routing_context,@@ -37,7 +40,7 @@ from products.stamphog.backend.logic.github_client import STICKY_COMMENT_MARKER,from products.stamphog.backend.logic.slack_digest import _THREAD_LEADfrom products.stamphog.backend.models import DigestRun, PullRequest, PullRequestAudience, ReviewRun, StamphogRepoConfigfrom products.stamphog.backend.tasks.digest import send_daily_digests-from products.stamphog.backend.tasks.tasks import process_inbox_pr_review+from products.stamphog.backend.tasks.tasks import process_inbox_pr_review, rereview_after_external_reviewfrom products.stamphog.backend.temporal import activitiesfrom products.stamphog.backend.temporal.activities import (MarkReviewFailedInput,@@ -49,6 +52,8 @@ from products.stamphog.backend.temporal.activities import (list_in_flight_reviewer_bots,mark_review_failed,post_verdict,+ refresh_review_evidence,+ rereview_after_external_review_finished,run_review_in_sandbox,start_review_sandbox,)@@ -1245,7 +1250,7 @@ def test_post_verdict_adopts_own_orphan_approval_instead_of_reposting(with override_settings(STAMPHOG_GITHUB_APP_SLUG=slug):result = _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))- assert result == {"verdict": str(ReviewVerdict.APPROVED)}+ assert result == {"verdict": str(ReviewVerdict.APPROVED), "waited_on_external_review": False}approvals = [w for w in recorder.github_writes if w["kind"] == "approve_review"]run.refresh_from_db()assert run.status == ReviewRunStatus.COMPLETED@@ -1312,7 +1317,7 @@ def test_non_approve_terminal_sweeps_supersession_orphan(with override_settings(STAMPHOG_GITHUB_APP_SLUG="stamphog"):result = _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))- assert result == {"verdict": str(ReviewVerdict.REFUSED)}+ assert result == {"verdict": str(ReviewVerdict.REFUSED), "waited_on_external_review": False}run.refresh_from_db()assert run.verdict == ReviewVerdict.REFUSED# The orphan is always swept; a peer run's live persisted approval (9191) is never touched.@@ -1626,10 +1631,7 @@ def test_post_verdict_skips_when_the_base_moved_under_the_run(@pytest.mark.django_db(databases=PRODUCT_DATABASES)[email protected]("bot_login", ["greptile-apps[bot]", "posthog[bot]"])-def test_bot_eyes_on_a_later_reactions_page_still_counts_as_in_flight(- team, stamphog_chain: StamphogChain, bot_login: str-) -> None:+def test_bot_eyes_on_a_later_reactions_page_still_counts_as_in_flight(team, stamphog_chain: StamphogChain) -> None:# Anyone can react on a public PR, so an author could bury the trusted bot's fresh 👀 past the# first page with junk reactions; a first-page-only fetch would treat the bot as absent and let# stamphog approve while that reviewer is still mid-review.@@ -1642,14 +1644,353 @@ def test_bot_eyes_on_a_later_reactions_page_still_counts_as_in_flight()now_iso = timezone.now().strftime("%Y-%m-%dT%H:%M:%SZ")junk = [{"user": {"login": f"rando-{i}"}, "content": "heart", "created_at": now_iso} for i in range(100)]- eyes = {"user": {"login": bot_login}, "content": "eyes", "created_at": now_iso}+ eyes = {"user": {"login": "greptile-apps[bot]"}, "content": "eyes", "created_at": now_iso}stamphog_chain.recorder.pr_reactions[(REPO, 115)] = [*junk, eyes]result = _run_activity(list_in_flight_reviewer_bots, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))- assert result["in_flight"] == [bot_login]+ assert result["in_flight"] == ["greptile-apps[bot]"]+++def _evidence(state: ReviewEvidenceState, head_sha: str, reviewer: str = "Reviewer A") -> ReviewEvidence:+ return ReviewEvidence(+ state=state,+ reviewer=reviewer,+ review_kind="Standard",+ findings_count=0,+ published=False,+ head_sha=head_sha,+ )+++def _failing_provider(repository: str, pr_number: int, head_sha: str) -> ReviewEvidence | None:+ raise RuntimeError("review evidence unavailable")+++def _pending_a(repository: str, pr_number: int, head_sha: str) -> ReviewEvidence:+ return _evidence(ReviewEvidenceState.PENDING, head_sha)+++def _completed_b(repository: str, pr_number: int, head_sha: str) -> ReviewEvidence:+ return _evidence(ReviewEvidenceState.COMPLETED, head_sha, reviewer="Reviewer B")+++def _pending_on_older_head(repository: str, pr_number: int, head_sha: str) -> ReviewEvidence:+ return _evidence(ReviewEvidenceState.PENDING, "sha-older")++[email protected]_db(databases=PRODUCT_DATABASES)+ "providers, in_flight, stored",+ [+ pytest.param((_pending_a,), ["Reviewer A"], [("Reviewer A", "pending")], id="pending-on-the-head-waits"),+ pytest.param((_completed_b,), [], [("Reviewer B", "completed")], id="completed-is-stored-for-the-engine"),+ pytest.param(+ (_pending_a, _completed_b),+ ["Reviewer A"],+ [("Reviewer A", "pending"), ("Reviewer B", "completed")],+ id="one-pending-keeps-waiting-beside-a-completed-one",+ ),+ pytest.param(+ (_failing_provider, _completed_b),+ [],+ [("Reviewer B", "completed")],+ id="a-failing-provider-does-not-hide-another",+ ),+ pytest.param((_pending_on_older_head,), [], [], id="another-head-is-ignored"),+ pytest.param((), [], [], id="no-provider"),+ ],+)+def test_review_evidence_providers_drive_the_reviewer_wait(+ team, stamphog_chain: StamphogChain, providers: tuple, in_flight: list[str], stored: list[tuple[str, str]]+) -> None:+ # A provider error must read as "no review known", never as a finished one: stored completed+ # evidence is assurance the engine trusts without asking the model.+ repo_config = _repo_config(team.id)+ pull_request = PullRequest.objects.for_team(team.id).create(+ team_id=team.id, repo_config=repo_config, pr_number=121, author_login="devex-dev"+ )+ run = ReviewRun.objects.for_team(team.id).create(+ team_id=team.id, pull_request=pull_request, head_sha="sha121a", status=ReviewRunStatus.QUEUED+ )++ with patch.object(activities, "get_review_evidence_providers", return_value=providers):+ result = _run_activity(+ list_in_flight_reviewer_bots, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id)+ )++ assert result["in_flight"] == in_flight+ assert result["reviews_completed"] is any(state == "completed" for _, state in stored)+ run.refresh_from_db()+ assert [(item["reviewer"], item["state"]) for item in run.output["review_evidence"]] == stored+++def _pending_then_failing_provider() -> ReviewEvidenceProvider:+ answers = 0++ def provider(repository: str, pr_number: int, head_sha: str) -> ReviewEvidence:+ nonlocal answers+ answers += 1+ if answers > 1:+ raise RuntimeError("review evidence unavailable")+ return _evidence(ReviewEvidenceState.PENDING, head_sha)++ return provider++[email protected]_db(databases=PRODUCT_DATABASES)+def test_provider_error_after_a_pending_answer_keeps_the_review_pending(team, stamphog_chain: StamphogChain) -> None:+ # Dropping the pending review on an error would let the run approve over a review that still runs.+ repo_config = _repo_config(team.id)+ pull_request = PullRequest.objects.for_team(team.id).create(+ team_id=team.id, repo_config=repo_config, pr_number=127, author_login="devex-dev"+ )+ run = ReviewRun.objects.for_team(team.id).create(+ team_id=team.id, pull_request=pull_request, head_sha="sha127a", status=ReviewRunStatus.QUEUED+ )+ inp = StamphogReviewInput(review_run_id=str(run.id), team_id=team.id)++ with patch.object(activities, "get_review_evidence_providers", return_value=(_pending_then_failing_provider(),)):+ _run_activity(list_in_flight_reviewer_bots, inp)+ result = _run_activity(list_in_flight_reviewer_bots, inp)++ assert result["in_flight"] == ["Reviewer A"]+ run.refresh_from_db()+ assert [(item["state"], item["provider_error"]) for item in run.output["review_evidence"]] == [("pending", True)]++[email protected]_db(databases=PRODUCT_DATABASES)+def test_engine_context_after_the_wait_holds_the_review_posted_during_it(team, stamphog_chain: StamphogChain) -> None:+ # The context fetch runs before the wait. Without the refresh, the engine judges reviews and+ # threads from before the wait, next to a review status that already says the review finished.+ repo_config = _repo_config(team.id)+ recorder = stamphog_chain.recorder+ head_sha = "sha122a"+ recorder.register_pr(REPO, 122, _pr_object(122, "devex-dev", head_sha), _pr_files())+ pull_request = PullRequest.objects.for_team(team.id).create(+ team_id=team.id, repo_config=repo_config, pr_number=122, author_login="devex-dev"+ )+ run = ReviewRun.objects.for_team(team.id).create(+ team_id=team.id, pull_request=pull_request, head_sha=head_sha, status=ReviewRunStatus.REVIEWING+ )+ inp = StamphogReviewInput(review_run_id=str(run.id), team_id=team.id)+ _run_activity(fetch_review_context, inp)++ recorder.pr_reviews[(REPO, 122)] = [+ {"id": 7171, "state": "COMMENTED", "commit_id": head_sha, "user": {"login": "posthog[bot]", "type": "Bot"}}+ ]+ with patch.object(activities, "get_review_evidence_providers", return_value=(_completed_b,)):+ _run_activity(list_in_flight_reviewer_bots, inp)+ _run_activity(refresh_review_evidence, inp)++ run.refresh_from_db()+ context = json.loads(activities._review_invocation(run, None).context_json)+ assert [review["id"] for review in context["reviews"]] == [7171]+ assert [item["state"] for item in context["review_evidence"]] == ["completed"]++[email protected]_db(databases=PRODUCT_DATABASES)+ "verdict, nudged_heads, live_head, enabled, earlier_wait, expected_new_runs",+ [+ pytest.param(ReviewVerdict.WAIT, ["sha123b"], "sha123b", True, False, 1, id="wait-on-the-head-reruns"),+ pytest.param(+ ReviewVerdict.WAIT, ["sha123b", "sha123b"], "sha123b", True, False, 1, id="repeated-nudge-reruns-once"+ ),+ # The re-run waited again. The original WAIT it replaced must not count as covering the head.+ pytest.param(ReviewVerdict.WAIT, ["sha123b"], "sha123b", True, True, 1, id="rerun-that-waited-again-reruns"),+ pytest.param(ReviewVerdict.WAIT, ["sha123a"], "sha123b", True, False, 0, id="nudge-for-an-older-head"),+ pytest.param(ReviewVerdict.WAIT, ["sha123b"], "sha123c", True, False, 0, id="head-moved-since"),+ pytest.param(ReviewVerdict.APPROVED, ["sha123b"], "sha123b", True, False, 0, id="approved-verdict"),+ pytest.param(ReviewVerdict.WAIT, ["sha123b"], "sha123b", False, False, 0, id="disconnected-repo"),+ ],+)+def test_finished_external_review_reruns_only_a_waiting_verdict(+ team,+ stamphog_chain: StamphogChain,+ verdict: ReviewVerdict,+ nudged_heads: list[str],+ live_head: str,+ enabled: bool,+ earlier_wait: bool,+ expected_new_runs: int,+) -> None:+ # A WAIT keeps a PR unapproved until something runs stamphog again. Any other verdict, head or+ # repo state must stay as it is, because a stray re-run can retract or replace a real verdict.+ repo_config = _repo_config(team.id)+ repo_config.enabled = enabled+ repo_config.save()+ live_pr = _pr_object(123, "devex-dev", live_head) | {"state": "open", "author_association": "MEMBER"}+ stamphog_chain.recorder.register_pr(REPO, 123, live_pr, _pr_files())+ pull_request = PullRequest.objects.for_team(team.id).create(+ team_id=team.id, repo_config=repo_config, pr_number=123, author_login="devex-dev"+ )+ waiting = ReviewRun.objects.for_team(team.id).create(+ team_id=team.id,+ pull_request=pull_request,+ head_sha="sha123b",+ status=ReviewRunStatus.COMPLETED,+ verdict=verdict,+ )+ existing_ids = [waiting.id]+ if earlier_wait:+ earlier = ReviewRun.objects.for_team(team.id).create(+ team_id=team.id,+ pull_request=pull_request,+ head_sha="sha123b",+ status=ReviewRunStatus.COMPLETED,+ verdict=ReviewVerdict.WAIT,+ )+ ReviewRun.objects.for_team(team.id).filter(id=earlier.id).update(+ created_at=waiting.created_at - timedelta(minutes=10)+ )+ existing_ids.append(earlier.id)++ with patch("products.stamphog.backend.tasks.tasks.execute_stamphog_review_workflow") as start:+ for head_sha in nudged_heads:+ rereview_after_external_review(REPO, 123, head_sha)++ new_runs = ReviewRun.objects.for_team(team.id).filter(pull_request=pull_request).exclude(id__in=existing_ids)+ assert new_runs.count() == expected_new_runs+ # A repeated nudge restarts the still-QUEUED run, which is a no-op for a live workflow.+ assert start.call_count == (len(nudged_heads) if expected_new_runs else 0)+ assert all(run.output.get("rereview_after_external_review") for run in new_runs)++[email protected]_db(databases=PRODUCT_DATABASES)+ "error, countdown",+ [+ pytest.param(GitHubRateLimitError("secondary rate limit", retry_after=1), 60, id="github-rate-limit"),+ pytest.param(RuntimeError("temporal unreachable"), 30, id="other-error"),+ ],+)+def test_rereview_after_external_review_retries_a_failure_with_backoff(+ team, stamphog_chain: StamphogChain, error: Exception, countdown: int+) -> None:+ # No webhook redelivery stands behind this call, so a dropped error loses the re-review.+ repo_config = _repo_config(team.id)+ pull_request = PullRequest.objects.for_team(team.id).create(+ team_id=team.id, repo_config=repo_config, pr_number=124, author_login="devex-dev"+ )+ ReviewRun.objects.for_team(team.id).create(+ team_id=team.id,+ pull_request=pull_request,+ head_sha="sha124b",+ status=ReviewRunStatus.COMPLETED,+ verdict=ReviewVerdict.WAIT,+ )++ with patch.object(StamphogGitHubClient, "get_pr", side_effect=error), pytest.raises(Retry) as retry:+ rereview_after_external_review.apply(args=(REPO, 124, "sha124b"))++ assert retry.value.when == countdown++[email protected]_db(databases=PRODUCT_DATABASES)+def test_rereview_after_external_review_restarts_a_rerun_left_queued(team, stamphog_chain: StamphogChain) -> None:+ # The workflow start of an earlier re-run failed after its row committed. A later call must+ # restart that run instead of treating it as a live review.+ repo_config = _repo_config(team.id)+ live_pr = _pr_object(126, "devex-dev", "sha126b") | {"state": "open", "author_association": "MEMBER"}+ stamphog_chain.recorder.register_pr(REPO, 126, live_pr, _pr_files())+ pull_request = PullRequest.objects.for_team(team.id).create(+ team_id=team.id, repo_config=repo_config, pr_number=126, author_login="devex-dev"+ )+ waiting = ReviewRun.objects.for_team(team.id).create(+ team_id=team.id,+ pull_request=pull_request,+ head_sha="sha126b",+ status=ReviewRunStatus.COMPLETED,+ verdict=ReviewVerdict.WAIT,+ )+ stranded = ReviewRun.objects.for_team(team.id).create(+ team_id=team.id,+ pull_request=pull_request,+ head_sha="sha126b",+ status=ReviewRunStatus.QUEUED,+ output={"rereview_after_external_review": True},+ )+ ReviewRun.objects.for_team(team.id).filter(id=waiting.id).update(+ created_at=stranded.created_at - timedelta(minutes=10)+ )++ with patch("products.stamphog.backend.tasks.tasks.execute_stamphog_review_workflow") as start:+ rereview_after_external_review(REPO, 126, "sha126b")++ assert start.call_args_list == [call(review_run_id=str(stranded.id), team_id=team.id)]+ assert ReviewRun.objects.for_team(team.id).filter(pull_request=pull_request).count() == 2++[email protected]_db(databases=PRODUCT_DATABASES)+ "state_now, dispatch_error, expected_dispatches",+ [+ pytest.param(ReviewEvidenceState.COMPLETED, None, 1, id="review-finished-since"),+ pytest.param(ReviewEvidenceState.PENDING, None, 0, id="review-still-pending"),+ pytest.param(ReviewEvidenceState.COMPLETED, RuntimeError("broker unreachable"), 1, id="dispatch-fails"),+ pytest.param(None, None, 0, id="provider-fails-after-pending"),+ ],+)+def test_wait_on_a_pending_external_review_reruns_once_that_review_finished(+ team,+ stamphog_chain: StamphogChain,+ state_now: ReviewEvidenceState | None,+ dispatch_error: Exception | None,+ expected_dispatches: int,+) -> None:+ # The external reviewer's own re-review request arrives while this run is still in flight and+ # finds no WAIT, so the run itself must ask once more after it saved its WAIT.+ repo_config = _repo_config(team.id)+ head_sha = "sha125a"+ stamphog_chain.recorder.register_pr(REPO, 125, _pr_object(125, "devex-dev", head_sha))+ pull_request = PullRequest.objects.for_team(team.id).create(+ team_id=team.id, repo_config=repo_config, pr_number=125, author_login="devex-dev"+ )+ pending = _evidence(ReviewEvidenceState.PENDING, head_sha)+ now = _evidence(state_now, head_sha) if state_now is not None else None++ def provider(*_: object) -> ReviewEvidence:+ if now is None:+ raise RuntimeError("provider unreachable")+ return now++ run = ReviewRun.objects.for_team(team.id).create(+ team_id=team.id,+ pull_request=pull_request,+ head_sha=head_sha,+ status=ReviewRunStatus.REVIEWING,+ output={+ "reviewer_raw": _waiting_engine_output(),+ "review_evidence": [+ {+ "provider": f"{provider.__module__}.{provider.__qualname__}",+ "state": "pending",+ "reviewer": pending.reviewer,+ "head_sha": head_sha,+ }+ ],+ },+ )+ inp = StamphogReviewInput(review_run_id=str(run.id), team_id=team.id)++ with (+ patch.object(activities, "get_review_evidence_providers", return_value=(provider,)),+ patch.object(activities, "request_rereview_after_external_review", side_effect=dispatch_error) as rereview,+ ):+ posted = _run_activity(post_verdict, inp)+ if dispatch_error is None and now is not None:+ _run_activity(rereview_after_external_review_finished, inp)+ else:+ with pytest.raises(RuntimeError):+ _run_activity(rereview_after_external_review_finished, inp)++ run.refresh_from_db()+ assert run.verdict == ReviewVerdict.WAIT+ assert posted["waited_on_external_review"] is True+ assert rereview.call_args_list == [call(repository=REPO, pr_number=125, head_sha=head_sha)] * expected_dispatches@pytest.mark.django_db(databases=PRODUCT_DATABASES)@@ -1710,6 +2051,16 @@ def test_mark_review_failed_never_rewrites_a_terminal_run(team) -> None:assert not run.error+def _waiting_engine_output() -> str:+ payload = {+ "final_verdict": "WAIT",+ "reviewer": {"reasoning": "PostHog Review is still reviewing this commit.", "issues": []},+ "gates": [{"name": "size", "passed": True}],+ "review_body": "Waiting for PostHog Review.",+ }+ return json.dumps(payload)++def _refused_engine_output() -> str:payload = {"final_verdict": "REFUSED",diff --git a/products/stamphog/backend/tests/test_workflow.py b/products/stamphog/backend/tests/test_workflow.pynew file mode 100644index 000000000000..740fe31bc711--- /dev/null+++ b/products/stamphog/backend/tests/test_workflow.py@@ -0,0 +1,132 @@+import uuid++import pytest++from temporalio import activity+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from products.stamphog.backend.temporal.activities import StamphogReviewInput+from products.stamphog.backend.temporal.constants import STAMPHOG_BOT_REVIEW_MAX_POLLS+from products.stamphog.backend.temporal.workflow import StamphogReviewWorkflow+++def _stub_activities(+ calls: list[str],+ in_flight_polls: int,+ reviews_completed: bool,+ verdict: dict | None = None,+ rereview_fails: bool = False,+) -> list:+ def stub(name: str, result: dict):+ @activity.defn(name=name)+ async def run(input: StamphogReviewInput) -> dict:+ calls.append(name)+ return result++ return run++ @activity.defn(name="list_in_flight_reviewer_bots")+ async def list_in_flight(input: StamphogReviewInput) -> dict:+ calls.append("list_in_flight_reviewer_bots")+ polls = calls.count("list_in_flight_reviewer_bots")+ in_flight = polls <= in_flight_polls+ return {+ "in_flight": ["PostHog Review"] if in_flight else [],+ "reviews_completed": reviews_completed and not in_flight,+ }++ @activity.defn(name="rereview_after_external_review_finished")+ async def rereview(input: StamphogReviewInput) -> dict:+ calls.append("rereview_after_external_review_finished")+ if rereview_fails:+ raise RuntimeError("broker unreachable")+ return {"requested": True}++ return [+ list_in_flight,+ rereview,+ stub("dismiss_stale_approvals", {}),+ stub("signal_review_started", {}),+ # No sandbox id, so the workflow skips the checkout and the sandbox review.+ stub("start_review_sandbox", {"sandbox_id": ""}),+ stub("fetch_review_context", {}),+ stub("refuse_on_pre_gates", {"refused": False}),+ stub("refresh_review_evidence", {}),+ stub("post_verdict", verdict or {"verdict": "approved"}),+ ]+++ "in_flight_polls, reviews_completed, refreshed",+ [+ pytest.param(0, False, False, id="nothing-in-flight"),+ # The engine counts the completed review, so it must also see the threads that review left.+ pytest.param(0, True, True, id="review-completed-before-the-first-poll"),+ pytest.param(2, False, True, id="reviewer-finishes-within-the-budget"),+ pytest.param(STAMPHOG_BOT_REVIEW_MAX_POLLS, False, True, id="budget-runs-out"),+ ],+)+async def test_evidence_is_read_again_after_waiting_for_reviewers(+ in_flight_polls: int, reviews_completed: bool, refreshed: bool+) -> None:+ # The context fetch runs before the wait. A review posted during the wait must reach the engine,+ # so the evidence is read again after the last poll and before the verdict.+ calls: list[str] = []+ async with await WorkflowEnvironment.start_time_skipping() as env:+ queue = str(uuid.uuid4())+ async with Worker(+ env.client,+ task_queue=queue,+ workflows=[StamphogReviewWorkflow],+ activities=_stub_activities(calls, in_flight_polls, reviews_completed),+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(+ StamphogReviewWorkflow.run,+ StamphogReviewInput(review_run_id=str(uuid.uuid4()), team_id=1),+ id=queue,+ task_queue=queue,+ )++ review_steps = [name for name in calls if name in ("list_in_flight_reviewer_bots", "refresh_review_evidence")]+ expected_polls = min(in_flight_polls + 1, STAMPHOG_BOT_REVIEW_MAX_POLLS)+ assert review_steps == ["list_in_flight_reviewer_bots"] * expected_polls + (+ ["refresh_review_evidence"] if refreshed else []+ )+ assert calls[-1] == "post_verdict"+++ "waited_on_external_review, rereview_fails, expected_attempts",+ [+ pytest.param(False, False, 0, id="no-external-review-to-wait-for"),+ pytest.param(True, False, 1, id="dispatches-once"),+ pytest.param(True, True, 3, id="retries-a-failed-dispatch"),+ ],+)+async def test_wait_on_an_external_review_dispatches_the_rereview_in_its_own_activity(+ waited_on_external_review: bool, rereview_fails: bool, expected_attempts: int+) -> None:+ calls: list[str] = []+ verdict = {"verdict": "wait", "waited_on_external_review": waited_on_external_review}+ async with await WorkflowEnvironment.start_time_skipping() as env:+ queue = str(uuid.uuid4())+ async with Worker(+ env.client,+ task_queue=queue,+ workflows=[StamphogReviewWorkflow],+ activities=_stub_activities(calls, 0, False, verdict=verdict, rereview_fails=rereview_fails),+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ StamphogReviewWorkflow.run,+ StamphogReviewInput(review_run_id=str(uuid.uuid4()), team_id=1),+ id=queue,+ task_queue=queue,+ )++ assert result == {"status": "completed", "verdict": "wait"}+ assert calls.count("rereview_after_external_review_finished") == expected_attemptsdiff --git a/products/stamphog/packages/pr-approval-agent/README.md b/products/stamphog/packages/pr-approval-agent/README.mdindex a074a3a74dd3..c971358bf26e 100644--- a/products/stamphog/packages/pr-approval-agent/README.md+++ b/products/stamphog/packages/pr-approval-agent/README.md@@ -111,7 +111,7 @@ Tier classification│▼Wait for in-flight bot reviews (skipped when gates already denied)- - Reviewer bots (greptile, hex-security, codex, PostHog Review) put 👀 on the PR while+ - Reviewer bots (greptile, hex-security, codex) put 👀 on the PR whilereviewing and swap it for a verdict reaction minutes later; the review istriggered at the same moment, so an 👀 at fetch time is a race, not alasting state@@ -123,6 +123,12 @@ Wait for in-flight bot reviews (skipped when gates already denied)- Human 👀 reactions are not waited on; the LLM refuses over them instead- If the wait refetched the PR, classification and gates re-run on thefresh data before the LLM sees it+ - Hosted runs also get external reviewers' status for the head from the+ server (`review_evidence` in the context, for example PostHog Review). Any+ pending review is WAIT; each completed one against the current merge base+ counts as a current-head review only when it skipped no changed file. Each+ gets its own line in the assurance summary and the verdict, which says why+ a review with skipped files does not count│▼LLM Reviewdiff --git a/products/stamphog/packages/pr-approval-agent/github.py b/products/stamphog/packages/pr-approval-agent/github.pyindex c3ccc57e1863..d1af9b16f59e 100644--- a/products/stamphog/packages/pr-approval-agent/github.py+++ b/products/stamphog/packages/pr-approval-agent/github.py@@ -48,6 +48,34 @@ class PRData:# Every path the diff touches, unquoted: a rename's old and new name both. `files` names a# rename once, so a deny pattern would miss code moved out of a protected directory.touched_paths: list[str] = field(default_factory=list)+ # Set by the hosted server from the external reviewers it asked: one dict per reviewer with state,+ # reviewer, review_kind, findings_count, published, head_sha, base_ref, base_sha and skipped_paths. Trusted+ # metadata, never PR text. Empty for the Action, which has no such source.+ review_evidence: list[dict] = field(default_factory=list)++ def pending_review_evidence(self) -> list[dict]:+ """The external reviews still running on the current head."""+ return [+ item+ for item in self.review_evidence+ if item.get("head_sha") == self.head_sha and item.get("state") == "pending"+ ]++ def completed_review_evidence(self) -> list[dict]:+ """The completed external reviews of the current head against the current merge base.++ A retarget keeps the head SHA but changes the diff, so a review of another merge base does+ not count. The base branch SHA is no match key, because it moves on every merge to the base+ while the diff stays the same. An unknown merge base on either side never matches.+ """+ return [+ item+ for item in self.review_evidence+ if item.get("head_sha") == self.head_sha+ and item.get("state") == "completed"+ and self.merge_base_sha+ and item.get("base_sha") == self.merge_base_sha+ ]@propertydef stacked(self) -> bool:@@ -80,6 +108,27 @@ class PRData:return any(f.get("status") == "A" for f in self.files)+def describe_review_evidence(evidence: dict) -> str:+ """One line on a completed external review of the current head, for the prompt and the verdict."""+ count = int(evidence.get("findings_count") or 0)+ if count == 0:+ findings = "no findings"+ elif evidence.get("published"):+ findings = f"{count} finding{'' if count == 1 else 's'}, posted on the PR"+ else:+ findings = f"{count} finding{'' if count == 1 else 's'}, not posted on the PR"+ reviewer = evidence.get("reviewer")+ kind = evidence.get("review_kind")+ name = f"{reviewer} ({kind})" if kind else str(reviewer)+ skipped = len(evidence.get("skipped_paths") or [])+ if skipped:+ return (+ f"{name} reviewed the current head ({findings}) but skipped {skipped} changed "+ f"file{'' if skipped == 1 else 's'}, so it does not count as assurance"+ )+ return f"{name} reviewed the current head: {findings}"++_TRUSTED_ASSOCIATIONS = {"MEMBER", "OWNER", "COLLABORATOR"}# Machine users that are real org members (type "User") but should still be@@ -95,8 +144,6 @@ TRUSTED_REACTOR_BOTS = {"copilot-pull-request-reviewer[bot]","greptile-apps[bot]","hex-security-app[bot]",- # PostHog Review, which posts as the PostHog GitHub App.- "posthog[bot]","veria-ai[bot]",}diff --git a/products/stamphog/packages/pr-approval-agent/review_local.py b/products/stamphog/packages/pr-approval-agent/review_local.pyindex 141246c7ab90..07e7a83f682c 100644--- a/products/stamphog/packages/pr-approval-agent/review_local.py+++ b/products/stamphog/packages/pr-approval-agent/review_local.py@@ -251,6 +251,8 @@ def _build_pr_data(context: dict, *, checkout: bool = True) -> PRData:})+ review_evidence = [item for item in context.get("review_evidence") or [] if isinstance(item, dict)]+return PRData(number=int(pr.get("number") or 0),repo=context.get("repo") or "",@@ -274,6 +276,7 @@ def _build_pr_data(context: dict, *, checkout: bool = True) -> PRData:body=pr.get("body") or "",discussion=_normalize_discussion_for_prompt(context.get("discussion") or []),default_branch=default_branch,+ review_evidence=review_evidence,)@@ -659,6 +662,23 @@ def run(context: dict) -> dict:}return pipeline.to_dict()+ # The server waited for these reviews too, so a review still pending here outlasted the+ # server's budget. Same answer as an in-flight bot: WAIT, never approve over it.+ if gate_verdict != "DENIED" and (pending := pipeline.pr.pending_review_evidence()):+ reviewers = " and ".join(str(item.get("reviewer")) for item in pending)+ verb = "are" if len(pending) > 1 else "is"+ pipeline.final_verdict = "WAIT"+ pipeline.reviewer_output = {+ "verdict": "WAIT",+ "reasoning": (+ f"{reviewers} {verb} still reviewing this commit, so stamphog does not approve yet. "+ "The review runs again on the next push, or you can re-request it once that review finishes."+ ),+ "risk": "unknown",+ "issues": [],+ }+ return pipeline.to_dict()+with _timed_phase("familiarity"):_attach_familiarity(pipeline, context)with _timed_phase("llm"):diff --git a/products/stamphog/packages/pr-approval-agent/review_pr.py b/products/stamphog/packages/pr-approval-agent/review_pr.pyindex 3e8701ba57a1..bf841a231043 100644--- a/products/stamphog/packages/pr-approval-agent/review_pr.py+++ b/products/stamphog/packages/pr-approval-agent/review_pr.py@@ -64,6 +64,7 @@ from github import (CommitProvenance,PRData,check_team_membership,+ describe_review_evidence,fetch_pr,is_in_flight_bot_eyes,pr_provenance,@@ -539,9 +540,10 @@ class Pipeline:def _summarize_assurance(self) -> dict:"""Deterministic pre-digest of review state for the TRUSTED prompt block.- Derived only from GitHub review metadata (states, head-ness) — never- author-controlled text — so the reviewer gets a trustworthy at-a-glance- summary of who has actually vouched for the current head.+ Derived only from GitHub review metadata (states, head-ness) and the+ hosted server's external review evidence — never author-controlled text —+ so the reviewer gets a trustworthy at-a-glance summary of who has+ actually vouched for the current head."""pr = self.pr# Exclude the author's own reviews: an author commenting on or replying@@ -577,6 +579,9 @@ class Pipeline:"head_commented": len(head_commented_users),"unresolved_threads": unresolved_threads,"discussion": len(pr.discussion),+ # A completed external review of this head counts like a current-head review. Its+ # published findings are review threads, so unresolved_threads above already holds them.+ "head_review_evidence": pr.completed_review_evidence(),}def _maybe_compute_familiarity(self) -> None:@@ -1100,6 +1105,8 @@ class Pipeline:thumbs = sorted({_sanitize_untrusted(r["user"], max_len=50) for r in self.pr.pr_reactions if r.get("emoji") == "👍"})+ for completed_review in assurance.get("head_review_evidence") or []:+ bullets.append(f"{describe_review_evidence(completed_review)}.")if head_reviewers:bullets.append(f"{', '.join(head_reviewers)} reviewed the current head.")elif thumbs:diff --git a/products/stamphog/packages/pr-approval-agent/reviewer.py b/products/stamphog/packages/pr-approval-agent/reviewer.pyindex 8dee8f83f839..d975bc4aaa5a 100644--- a/products/stamphog/packages/pr-approval-agent/reviewer.py+++ b/products/stamphog/packages/pr-approval-agent/reviewer.py@@ -19,7 +19,7 @@ from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, queryfrom claude_agent_sdk.types import AssistantMessage, ToolUseBlockfrom gates import manifest_basenamesfrom gateway import CLAUDE_REVIEWER_MODEL, analytics_extra_properties, gateway_env, resolve_gateway_config-from github import PRData, drop_abandoned_bot_eyes, new_diff_file, write_pr_diff+from github import PRData, describe_review_evidence, drop_abandoned_bot_eyes, new_diff_file, write_pr_difffrom policy import _sanitize_untrusted, review_guidance_path, steering_pathfrom verdict_rule import FACT_FIELDS, FACTS_SCHEMA, InvalidFactsError, ReviewFacts, derive_verdictfrom version import STAMPHOG_VERSION@@ -147,15 +147,26 @@ def _cap_assurance_facts(facts: ReviewFacts, classification: dict, head_reviewedthe current head. The model judges whether that team owns the risky part and whether thatreview covers it, so both must hold. An injected claim or a misread can then narrowassurance for a risky change but never create it.++ A completed external review of the current head is the one assurance the pipeline adds by+ itself. It comes from the hosted server's records, not from the model or the PR. It counts only+ when it skipped no changed file, because the risky part could be in any file it did not read."""on_owning_team = bool(classification.get("ownership", {}).get("teams")) and bool(classification.get("author_on_owning_team", True))familiarity = classification.get("familiarity")strong = familiarity is not None and familiarity.band == "STRONG"+ reviews_on_current_head = facts.reviews_on_current_head if head_reviewed else ()+ for completed_review in (classification.get("assurance") or {}).get("head_review_evidence") or []:+ if completed_review.get("skipped_paths"):+ continue+ reviewer = str(completed_review.get("reviewer"))+ if reviewer not in reviews_on_current_head:+ reviews_on_current_head = (*reviews_on_current_head, reviewer)return dataclasses.replace(facts,- reviews_on_current_head=facts.reviews_on_current_head if head_reviewed else (),+ reviews_on_current_head=reviews_on_current_head,owning_team_author=facts.owning_team_author and on_owning_team,strong_familiarity=facts.strong_familiarity and strong,)@@ -812,8 +823,9 @@ class Reviewer:def _format_assurance(self, cl: dict) -> str:"""Render the TRUSTED one-line assurance digest of review state.- Computed from GitHub review metadata (states, head-ness), not from- author-controlled text, so it sits with the other trusted gate facts.+ Computed from GitHub review metadata (states, head-ness) and the hosted+ server's external review evidence, not from author-controlled text, so it+ sits with the other trusted gate facts."""a = cl.get("assurance") or {}approvers = [_sanitize_untrusted(u, max_len=50) for u in a.get("head_approvals", [])]@@ -822,6 +834,8 @@ class Reviewer:discussion = a.get("discussion", 0)parts = []+ for completed_review in a.get("head_review_evidence") or []:+ parts.append(describe_review_evidence(completed_review))if approvers:names = ", ".join(f"@{u}" for u in approvers)parts.append(f"{_plural(len(approvers), 'current-head approval')} ({names})")diff --git a/products/stamphog/packages/pr-approval-agent/test_github.py b/products/stamphog/packages/pr-approval-agent/test_github.pyindex a8bbeafd4862..60896399981f 100644--- a/products/stamphog/packages/pr-approval-agent/test_github.py+++ b/products/stamphog/packages/pr-approval-agent/test_github.py@@ -285,7 +285,6 @@ def test_reaction_emoji_normalizes_rest_and_graphql(content: str, expected: str)pytest.param("ghost", False, id="deleted-user"),pytest.param("", False, id="empty-login"),pytest.param("greptile-apps[bot]", True, id="allowlisted-bot"),- pytest.param("posthog[bot]", True, id="posthog-review-bot"),pytest.param("inkeep[bot]", False, id="unlisted-bot"),pytest.param("teammate", True, id="org-member"),pytest.param("outsider", False, id="external-non-member"),diff --git a/products/stamphog/packages/pr-approval-agent/test_review_local.py b/products/stamphog/packages/pr-approval-agent/test_review_local.pyindex 82fb37a9931f..786e1b880698 100644--- a/products/stamphog/packages/pr-approval-agent/test_review_local.py+++ b/products/stamphog/packages/pr-approval-agent/test_review_local.py@@ -160,6 +160,52 @@ def test_pending_migration_check_waits_instead_of_refusing(monkeypatch) -> None:assert "Migration risk" in result["reviewer"]["reasoning"]+def _evidence(state: str, head_sha: str, reviewer: str = "PostHog Review") -> dict:+ return {+ "state": state,+ "reviewer": reviewer,+ "review_kind": "Standard",+ "findings_count": 0,+ "published": False,+ "head_sha": head_sha,+ }+++ "review_evidence, expected",+ [+ pytest.param([_evidence("pending", "h" * 40)], "WAIT", id="pending-on-the-head-waits"),+ pytest.param([_evidence("pending", "o" * 40)], "APPROVED", id="pending-on-an-older-head-is-ignored"),+ pytest.param([_evidence("failed", "h" * 40)], "APPROVED", id="failed-reviews-as-without-it"),+ pytest.param(+ [_evidence("completed", "h" * 40), _evidence("pending", "h" * 40, reviewer="Other Reviewer")],+ "WAIT",+ id="one-pending-among-completed-waits",+ ),+ ],+)+def test_pending_external_review_waits_instead_of_approving(+ monkeypatch, review_evidence: list[dict], expected: str+) -> None:+ # The server stops waiting when its poll budget runs out. An approval over a review that is still+ # running would stand before that review's findings reach the PR.+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])+ monkeypatch.setattr(review_local, "pr_provenance", lambda *a, **k: None)++ def fake_llm(self, gate_verdict: str) -> None:+ self.final_verdict = "APPROVED"+ self.reviewer_output = {"verdict": "APPROVE", "reasoning": "ok", "risk": "low", "issues": []}++ monkeypatch.setattr(Pipeline, "_llm_review", fake_llm)+ context = {**_run_context([_api_file("src/app.py")]), "review_evidence": review_evidence}++ result = review_local.run(context)++ assert result["final_verdict"] == expected+ if expected == "WAIT":+ assert "still reviewing this commit" in result["reviewer"]["reasoning"]++_GIT_PROVENANCE = CommitProvenance(commit_count=3, agent_commit_count=2, generated_by=("claude",), task_ids=("t-1",))diff --git a/products/stamphog/packages/pr-approval-agent/test_review_pr.py b/products/stamphog/packages/pr-approval-agent/test_review_pr.pyindex 1dd0d961f809..6b13b5ce9bfe 100644--- a/products/stamphog/packages/pr-approval-agent/test_review_pr.py+++ b/products/stamphog/packages/pr-approval-agent/test_review_pr.py@@ -84,6 +84,48 @@ def test_summarize_assurance_excludes_author_self_review() -> None:assert assurance["head_commented_users"] == ["bob"]+_EVIDENCE = {+ "reviewer": "PostHog Review",+ "review_kind": "Deep",+ "findings_count": 0,+ "published": False,+}+_COMPLETED_ON_HEAD = {**_EVIDENCE, "state": "completed", "head_sha": "abc123", "base_ref": "master", "base_sha": "mb1"}+++ "review_evidence, pr_merge_base, counted",+ [+ pytest.param([_COMPLETED_ON_HEAD], "mb1", [_COMPLETED_ON_HEAD], id="completed-on-the-head"),+ pytest.param([{**_COMPLETED_ON_HEAD, "head_sha": "old999"}], "mb1", [], id="completed-on-an-older-head"),+ # A retarget or a base merge keeps the head SHA, so only the merge base shows that the reviewed diff is stale.+ pytest.param([{**_COMPLETED_ON_HEAD, "base_sha": "mb0"}], "mb1", [], id="completed-against-another-merge-base"),+ pytest.param([{**_COMPLETED_ON_HEAD, "base_sha": ""}], "mb1", [], id="completed-against-an-unknown-merge-base"),+ pytest.param([{**_COMPLETED_ON_HEAD, "base_sha": ""}], "", [], id="merge-base-unknown-on-both-sides"),+ pytest.param([{**_EVIDENCE, "state": "pending", "head_sha": "abc123"}], "mb1", [], id="pending"),+ pytest.param([{**_EVIDENCE, "state": "failed", "head_sha": "abc123"}], "mb1", [], id="failed"),+ pytest.param(+ [{**_EVIDENCE, "state": "pending", "head_sha": "abc123", "reviewer": "Other"}, _COMPLETED_ON_HEAD],+ "mb1",+ [_COMPLETED_ON_HEAD],+ id="each-reviewer-counts-on-its-own",+ ),+ pytest.param([], "mb1", [], id="no-evidence"),+ ],+)+def test_summarize_assurance_counts_only_completed_reviews_of_the_head(+ review_evidence: list[dict], pr_merge_base: str, counted: list[dict]+) -> None:+ # A review of an older head says nothing about the commits pushed since, and a pending or+ # failed one has not looked at the diff. Only a finished review of this head may assure it.+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")+ pipeline.pr = _fake_pr(head_sha="abc123")+ pipeline.pr.merge_base_sha = pr_merge_base+ pipeline.pr.review_evidence = review_evidence++ assert pipeline._summarize_assurance()["head_review_evidence"] == counted++def test_to_dict_includes_reviewed_base_and_head_shas() -> None:# The verdict is posted against the base_sha and head_sha from the JSON output. This locks# the GitHub review to the diff the LLM actually saw, and skips the approval when the basediff --git a/products/stamphog/packages/pr-approval-agent/test_reviewer.py b/products/stamphog/packages/pr-approval-agent/test_reviewer.pyindex f975f2a95d07..9ecf80b3eba9 100644--- a/products/stamphog/packages/pr-approval-agent/test_reviewer.py+++ b/products/stamphog/packages/pr-approval-agent/test_reviewer.py@@ -143,6 +143,19 @@ def test_prompt_truncates_long_review_body() -> None:assert "X" * 2501 not in prompt+_COMPLETED_REVIEW = {+ "state": "completed",+ "reviewer": "PostHog Review",+ "review_kind": "Deep",+ "findings_count": 0,+ "published": False,+ "head_sha": "abc123",+ "base_ref": "master",+ "base_sha": "mb1",+ "skipped_paths": [],+}++@pytest.mark.parametrize("assurance,expected",[@@ -161,6 +174,30 @@ def test_prompt_truncates_long_review_body() -> None:"Assurance: no reviews or comments yet",id="nothing-yet",),+ pytest.param(+ {+ "head_approvals": [],+ "head_commented": 0,+ "unresolved_threads": 2,+ "discussion": 0,+ "head_review_evidence": [{**_COMPLETED_REVIEW, "findings_count": 2, "published": True}],+ },+ "Assurance: PostHog Review (Deep) reviewed the current head: 2 findings, posted on the PR; "+ "2 unresolved inline threads",+ id="completed-automated-review",+ ),+ pytest.param(+ {+ "head_approvals": [],+ "head_commented": 0,+ "unresolved_threads": 0,+ "discussion": 0,+ "head_review_evidence": [{**_COMPLETED_REVIEW, "skipped_paths": ["a.lock", "b.py", "c.py"]}],+ },+ "Assurance: PostHog Review (Deep) reviewed the current head (no findings) but skipped 3 changed "+ "files, so it does not count as assurance",+ id="automated-review-with-skipped-files",+ ),],)def test_format_assurance_line(assurance: dict, expected: str) -> None:@@ -244,6 +281,32 @@ _ON_OWNING_TEAM = {"ownership": {"teams": ["@PostHog/team-core"]}, "author_on_ow"ESCALATE",id="claimed-review-github-does-not-show",),+ pytest.param(+ _RISKY_FACTS,+ {"assurance": {"head_review_evidence": [_COMPLETED_REVIEW]}},+ False,+ "APPROVE",+ id="completed-automated-review-assures",+ ),+ pytest.param(+ _RISKY_FACTS,+ {+ "assurance": {+ "head_review_evidence": [{**_COMPLETED_REVIEW, "skipped_paths": ["posthog/models/team.py"]}]+ }+ },+ False,+ "ESCALATE",+ id="automated-review-skipped-the-risky-file",+ ),+ # A risky area is free text, so a skipped file it does not name may still hold the risky part.+ pytest.param(+ _RISKY_FACTS,+ {"assurance": {"head_review_evidence": [{**_COMPLETED_REVIEW, "skipped_paths": ["pnpm-lock.yaml"]}]}},+ False,+ "ESCALATE",+ id="automated-review-skipped-any-file",+ ),],)def test_verdict_from_facts_keeps_the_consumer_contract(