: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(commands): post the result of a slack command when its work ends (#117540)
Julian Bez85ef36612658
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex f871a09c880b..f0d849ad3c17 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -199,6 +199,7 @@ post_save:products.cohorts.backend.models.dependencies.cohort_behavioral_shape_cpost_save:products.cohorts.backend.models.dependencies.cohort_changedpost_save:products.cohorts.backend.models.dependencies.cohort_person_shape_changed_backfillpost_save:products.cohorts.backend.models.dependencies.cohort_person_shape_changed_supersede+post_save:products.commands.backend.receivers.on_task_run_savedpost_save:products.conversations.backend.signals.emit_ticket_created_eventpost_save:products.conversations.backend.signals.post_github_reply_on_team_messagepost_save:products.conversations.backend.signals.post_slack_reply_on_team_messagediff --git a/products/commands/README.md b/products/commands/README.mdindex 55b072418e38..694339a15403 100644--- a/products/commands/README.md+++ b/products/commands/README.md@@ -51,6 +51,7 @@ The same commands run from a Slack message that mentions the PostHog app and nam- Only a message that opens with the app's mention and reads exactly as a command runs one. Free text, such as "can you review this deeply", and a mistyped option go to the agent as before.- The `slack-commands` flag decides the rollout per organization, once, inside the Slack webhook. Outside it, the message also goes to the agent.- Every command that ran gets an answer in the thread, refusals included, because the message no longer reaches the agent.+- When the work a command started ends, its result follows in the same thread: the review's findings count, Stamphog's outcome, or the end of the QA run. A pull request comment needs no follow-up, because the work posts its result on the pull request.- The Slack app asks `may_hold_command` first, a check with no queries, so most mentions never reach this product. It hands the rest to `accept_slack_mention` inside its webhook, as plain text. This product reads it (`channels/slack/`), runs it in its own task like a pull request comment, and answers in the thread through the Slack integration the mention came in on.- A Slack command has no GitHub permission check. It runs as a PostHog account that is a member of the project, like the review trigger in the PostHog API and MCP.- It may run as the accounts the Slack app resolves for the person, the ones its agent acts as: first their linked PostHog account, else the member of a connected organization with their Slack email, then every other account linked to their Slack user. The command picks the project first, and the first of these accounts that is a member of it acts there.@@ -76,6 +77,14 @@ To add a kind of subject:3. Teach the channels that can name it to read it, for example a URL pattern in `channels/slack/parsing.py`.4. Add the kind to `subject_kinds` of the commands that accept it.+## Results that come later++The first answer says that the work started.+A channel that wants the result later gives an address (`follow_up` on the channel), and the handler saves it with `logic/follow_ups.py` before the work ends.+The products report the end without importing this product: Stamphog and PostHog Review call the callbacks registered in their `facade/finished_review_hooks.py`, and a QA run's terminal save fires the task run signal.+`receivers.py` registers all three at app start, builds the message in `logic/results.py`, and queues it.+A follow-up record lives in the cache for a day, so a lost record loses only the follow-up message.+## Adding a commandDeclare the command in `logic/schema.py`: an args dataclass built with `flag()`, `option()` and `text()`, and a `CommandDeclaration` in `COMMAND_DECLARATIONS`.diff --git a/products/commands/backend/apps.py b/products/commands/backend/apps.pyindex 166ccb3f0c22..b4d1a4a7c891 100644--- a/products/commands/backend/apps.py+++ b/products/commands/backend/apps.py@@ -6,3 +6,8 @@ from django.apps import AppConfigclass CommandsConfig(AppConfig):name = "products.commands.backend"label = "commands"++ def ready(self) -> None:+ from products.commands.backend import receivers # noqa: PLC0415 — needs the app registry++ receivers.connect()diff --git a/products/commands/backend/channels/github/comments.py b/products/commands/backend/channels/github/comments.pyindex 9ff03bc68c33..f9584fb6f591 100644--- a/products/commands/backend/channels/github/comments.py+++ b/products/commands/backend/channels/github/comments.py@@ -29,7 +29,7 @@ from posthog.models.user import Userfrom posthog.models.user_integration import UserIntegrationfrom ...logic.admission import claim, release, rolled_out_team_ids, within_rate_limit-from ...logic.commands import Answer, CommandRequest, DispatchOutcome, PullRequestRef+from ...logic.commands import Answer, CommandRequest, DispatchOutcome, FollowUpAddress, PullRequestReffrom ...logic.dispatcher import Admission, CommandDispatcherfrom ...logic.github import CommandGitHub, GitHubCallFailed, InstallationGitHub, Reactionfrom ...logic.subjects import open_subject@@ -64,6 +64,8 @@ def _linked_users(github_user_id: int) -> list[User]:class GitHubCommentChannel:name = "github"+ # The work posts its result on the pull request the comment sits on.+ follow_up: FollowUpAddress | None = Noneunlinked_message = ("Your GitHub account is not linked to a PostHog account, so I can't tell who to run this as. ""Connect GitHub in your PostHog personal settings, then comment again."diff --git a/products/commands/backend/channels/slack/mentions.py b/products/commands/backend/channels/slack/mentions.pyindex cf824ea4d702..91e6f5442312 100644--- a/products/commands/backend/channels/slack/mentions.py+++ b/products/commands/backend/channels/slack/mentions.py@@ -26,7 +26,7 @@ from posthog.slack.markdown import slack_markdown_blockfrom ...facade.contracts import SlackMentionfrom ...logic.admission import claim, rolled_out_team_ids, within_rate_limit-from ...logic.commands import Answer, CommandRequest, DispatchOutcome, PullRequestRef, SubjectRef+from ...logic.commands import Answer, CommandRequest, DispatchOutcome, FollowUpAddress, PullRequestRef, SubjectReffrom ...logic.dispatcher import Admission, CommandDispatcherfrom ...logic.github import CommandGitHubfrom ...logic.registry import COMMANDS@@ -114,6 +114,55 @@ def read_slack_command(mention: SlackMention) -> SlackCommandRequest | None:)+@frozen+class SlackThread:+ """The thread a command answers in, through the Slack integration the mention came in on."""++ integration_id: int+ integration_team_id: int+ channel: str+ thread_ts: str++ def to_address(self) -> FollowUpAddress:+ return {+ "channel": "slack",+ "integration_id": self.integration_id,+ "integration_team_id": self.integration_team_id,+ "slack_channel": self.channel,+ "thread_ts": self.thread_ts,+ }++ @classmethod+ def from_address(cls, address: FollowUpAddress) -> "SlackThread":+ return cls(+ integration_id=int(address["integration_id"]),+ integration_team_id=int(address["integration_team_id"]),+ channel=str(address["slack_channel"]),+ thread_ts=str(address["thread_ts"]),+ )+++def post_in_thread(thread: SlackThread, message: str) -> None:+ integration = Integration.objects.filter(+ id=thread.integration_id, team_id=thread.integration_team_id, kind="slack"+ ).first()+ if integration is None:+ logger.warning("slack_command_reply_integration_missing", integration_id=thread.integration_id)+ return+ try:+ post_message(+ SlackIntegration(integration),+ thread.channel,+ [slack_markdown_block(message)],+ message,+ thread_ts=thread.thread_ts,+ )+ except Exception:+ # Best effort, as for pull request comments: a lost answer must not turn a run that+ # started into a failure.+ logger.warning("slack_command_reply_failed", exc_info=True)++class SlackMentionChannel:name = "slack"unlinked_message = (@@ -124,6 +173,13 @@ class SlackMentionChannel:def __init__(self, command: SlackCommandRequest, github: CommandGitHub | None = None) -> None:self._command = commandself._github = github+ self._thread = SlackThread(+ integration_id=command.integration_id,+ integration_team_id=command.integration_team_id,+ channel=command.channel,+ thread_ts=command.thread_ts,+ )+ self.follow_up: FollowUpAddress | None = self._thread.to_address()self.request = CommandRequest(subject=command.subject,verb=command.verb,@@ -159,25 +215,7 @@ class SlackMentionChannel:return [users[user_id] for user_id in user_ids if user_id in users and users[user_id].is_active]def reply(self, message: str) -> None:- command = self._command- integration = Integration.objects.filter(- id=command.integration_id, team_id=command.integration_team_id, kind="slack"- ).first()- if integration is None:- logger.warning("slack_command_reply_integration_missing", integration_id=command.integration_id)- return- try:- post_message(- SlackIntegration(integration),- command.channel,- [slack_markdown_block(message)],- message,- thread_ts=command.thread_ts,- )- except Exception:- # Best effort, as for pull request comments: a lost answer must not turn a run that- # started into a failure.- logger.warning("slack_command_reply_failed", exc_info=True)+ post_in_thread(self._thread, message)def dispatch_slack_command(command: SlackCommandRequest, *, github: CommandGitHub | None = None) -> DispatchOutcome:diff --git a/products/commands/backend/logic/commands.py b/products/commands/backend/logic/commands.pyindex 2e4715d79e2c..a44b26a157ab 100644--- a/products/commands/backend/logic/commands.py+++ b/products/commands/backend/logic/commands.py@@ -116,6 +116,11 @@ class PullRequestFacts:SubjectFacts = PullRequestFacts+# Where a channel wants the result of work that finishes after the command answered. Only the+# channel reads it, so the core keeps it as plain data.+FollowUpAddress = dict[str, str | int]++@frozenclass ProjectMember:"""A project the commenter may act in, and the commenter's PostHog account that acts there.@@ -135,6 +140,7 @@ class CommandContext:# Best candidate first. Every entry passed the membership, rollout and resource-access checks# for this command. A project appears once per linked account that is a member of it.members: tuple[ProjectMember, ...]+ follow_up: FollowUpAddress | None = None@propertydef pull_request(self) -> PullRequestFacts:diff --git a/products/commands/backend/logic/dispatcher.py b/products/commands/backend/logic/dispatcher.pyindex 5168d923ac1a..ff278eb62932 100644--- a/products/commands/backend/logic/dispatcher.py+++ b/products/commands/backend/logic/dispatcher.py@@ -29,7 +29,15 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.permissions import UserAccessControl-from .commands import SUBJECT_NAMES, Answer, CommandContext, CommandRequest, DispatchOutcome, ProjectMember+from .commands import (+ SUBJECT_NAMES,+ Answer,+ CommandContext,+ CommandRequest,+ DispatchOutcome,+ FollowUpAddress,+ ProjectMember,+)from .identity import Requester, resolve_requesterfrom .registry import COMMANDS, CommandSpec, Invocation, help_textfrom .schema import HELP_VERB, ArgumentError, ResourceAccess, resolve_verb, usage@@ -60,6 +68,8 @@ class CommandChannel(Protocol):name: strrequest: CommandRequestunlinked_message: str+ # Where the result of work that finishes later goes. None when the work reports it itself.+ follow_up: FollowUpAddress | Nonedef admit(self) -> Admission | Answer | DispatchOutcome:"""The channel's own checks. A bare outcome refuses in silence, and an ``Answer`` refuses@@ -165,7 +175,7 @@ class CommandDispatcher:outcome="access_denied",message=f"You need {access.level} access to {access.resource} in PostHog to use `{declaration.verb}`.",)- return CommandContext(request=request, subject=subject, members=members)+ return CommandContext(request=request, subject=subject, members=members, follow_up=self._channel.follow_up)def _run(self, command: Invocation[Any], admission: Admission) -> DispatchOutcome:"""Builds the context and runs the handler. A failure in either answers the requester."""diff --git a/products/commands/backend/logic/follow_ups.py b/products/commands/backend/logic/follow_ups.pynew file mode 100644index 000000000000..9c28e45469a9--- /dev/null+++ b/products/commands/backend/logic/follow_ups.py@@ -0,0 +1,79 @@+"""Remembers where a command's result goes, for work that finishes after the command answered.++The first answer only says that the work started. When the product reports the outcome, the+receivers in ``receivers.py`` look up the follow-up and send the result there. The channel decides+the address: a Slack command answers in its thread, and a pull request comment needs none, because+the work posts its result on the pull request itself.++The record lives in the cache with a time limit, so a lost record only loses the follow-up message.+"""++from typing import Any++from django.core.cache import cache++import structlog++from posthog.dataclasses import frozen++from .commands import FollowUpAddress++logger = structlog.get_logger(__name__)++# Longer than any review or QA run takes.+_TTL_SECONDS = 24 * 60 * 60+++@frozen+class FollowUp:+ address: FollowUpAddress+ subject_label: str+ subject_url: str++ def to_payload(self) -> dict[str, Any]:+ return {"address": dict(self.address), "subject_label": self.subject_label, "subject_url": self.subject_url}++ @classmethod+ def from_payload(cls, payload: dict[str, Any]) -> "FollowUp":+ return cls(+ address=dict(payload["address"]),+ subject_label=str(payload["subject_label"]),+ subject_url=str(payload["subject_url"]),+ )+++def stamphog_run_key(run_id: str) -> str:+ return f"commands:follow_up:stamphog_run:{run_id}"+++def review_key(project_id: int, repository: str, number: int, review_mode: str) -> str:+ # A request can wait behind a running turn of the other mode, and the head can move while it+ # waits, so the mode names the turn and the head does not. Each project reviews on its own.+ return f"commands:follow_up:review:{project_id}:{repository.lower()}#{number}:{review_mode}"+++def task_run_key(run_id: str) -> str:+ return f"commands:follow_up:task_run:{run_id}"+++def remember(key: str, follow_up: FollowUp) -> None:+ """Saves the follow-up next to any other request that waits for the same outcome."""+ try:+ waiting = cache.get(key) or []+ cache.set(key, [*waiting, follow_up.to_payload()], timeout=_TTL_SECONDS)+ except Exception:+ # The command already started its work. Only the follow-up message is lost.+ logger.warning("command_follow_up_not_saved", key=key, exc_info=True)+++def take(key: str) -> list[FollowUp]:+ """The follow-ups saved under ``key``, once. A retried or repeated outcome gets none."""+ try:+ waiting = cache.get(key)+ # The delete decides between two callers that read the same outcome at once.+ if not waiting or not cache.delete(key):+ return []+ return [FollowUp.from_payload(payload) for payload in waiting]+ except Exception:+ logger.warning("command_follow_up_not_read", key=key, exc_info=True)+ return []diff --git a/products/commands/backend/logic/handlers.py b/products/commands/backend/logic/handlers.pyindex a52f48844642..347f6fb342b5 100644--- a/products/commands/backend/logic/handlers.py+++ b/products/commands/backend/logic/handlers.py@@ -12,6 +12,7 @@ from collections.abc import Collectionimport structlog+from posthog.models.scoping.manager import resolve_effective_team_idfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.utils import absolute_uri@@ -22,6 +23,7 @@ from products.review_hog.backend.facade import ()from products.stamphog.backend.facade import (contracts as stamphog_contracts,+ enums as stamphog_enums,review_requests as stamphog_requests,)from products.tasks.backend.facade import (@@ -30,6 +32,7 @@ from products.tasks.backend.facade import (usage as tasks_usage,)+from . import follow_upsfrom .commands import Answer, CommandContext, CommandOutcome, CommandTarget, PullRequestReffrom .schema import LoopArgs, QaArgs, ReviewArgs, StampArgs@@ -65,6 +68,16 @@ def stamp_target(ref: PullRequestRef, team_ids: tuple[int, ...]) -> CommandTarge)+def _follow_up(context: CommandContext) -> follow_ups.FollowUp | None:+ if context.follow_up is None:+ return None+ return follow_ups.FollowUp(+ address=context.follow_up,+ subject_label=context.request.subject.describe(),+ subject_url=context.subject.url,+ )++def handle_stamp(context: CommandContext, args: StampArgs) -> CommandOutcome:"""Ask Stamphog to review the pull request. Stamphog alone decides whether to approve."""pull_request = context.pull_request@@ -79,6 +92,9 @@ def handle_stamp(context: CommandContext, args: StampArgs) -> CommandOutcome:except stamphog_contracts.ReviewRequestRefusedError as error:# Stamphog writes its refusals for the requester, from the repository name and PR number only.return CommandOutcome(accepted=False, message=error.message)+ follow_up = _follow_up(context)+ if follow_up is not None and result.run.status not in stamphog_enums.TERMINAL_STATUSES:+ follow_ups.remember(follow_ups.stamphog_run_key(str(result.run.id)), follow_up)if result.created:return CommandOutcome(accepted=True, message="Stamphog is reviewing this pull request.")return CommandOutcome(@@ -112,6 +128,11 @@ def handle_review(context: CommandContext, args: ReviewArgs) -> CommandOutcome:if outcome.status == review_hog_facade.PRReviewRequestStatus.ALREADY_REVIEWED:return CommandOutcome(accepted=True, message="PostHog Review already reviewed the current commit.")if outcome.started:+ follow_up = _follow_up(context)+ if follow_up is not None and outcome.review_mode:+ project_id = resolve_effective_team_id(member.team_id)+ key = follow_ups.review_key(project_id, pull_request.repository, pull_request.number, outcome.review_mode)+ follow_ups.remember(key, follow_up)return CommandOutcome(accepted=True, message="PostHog Review is reviewing this pull request.")# PostHog Review writes its refusals from the repository name, the PR number and fixed text.return CommandOutcome(accepted=False, message=outcome.error)@@ -151,6 +172,9 @@ def handle_qa(context: CommandContext, args: QaArgs) -> CommandOutcome:branch=pull_request.head_branch,create_pr=False,)+ follow_up = _follow_up(context)+ if follow_up is not None and created.latest_run is not None:+ follow_ups.remember(follow_ups.task_run_key(str(created.latest_run.id)), follow_up)task_url = absolute_uri(f"/project/{team_id}/tasks/{created.task_id}")return CommandOutcome(accepted=True, message=f"Started a QA run. Follow it in [PostHog Code]({task_url}).")diff --git a/products/commands/backend/logic/results.py b/products/commands/backend/logic/results.pynew file mode 100644index 000000000000..26025eb0feea--- /dev/null+++ b/products/commands/backend/logic/results.py@@ -0,0 +1,56 @@+"""The follow-up messages that tell a requester how the work their command started ended.++Each message names the subject with its label and link and adds a link to the result. It is built+from fixed text and values PostHog produced, never from the review text, so a pull request cannot+make the bot post its words.+"""++from products.review_hog.backend.facade.finished_review_hooks import FinishedReview+from products.stamphog.backend.facade.enums import ReviewRunStatus, ReviewVerdict+from products.stamphog.backend.facade.finished_review_hooks import FinishedReviewRun++from .follow_ups import FollowUp+++def _subject(follow_up: FollowUp) -> str:+ return f"[{follow_up.subject_label}]({follow_up.subject_url})"+++def review_result(finished: FinishedReview, follow_up: FollowUp) -> str:+ subject = _subject(follow_up)+ if finished.failed:+ return f"PostHog Review couldn't finish reviewing {subject}. Try `review` again in a few minutes."+ if finished.findings_count == 0:+ found = "found nothing to fix"+ elif finished.findings_count == 1:+ found = "found 1 issue"+ else:+ found = f"found {finished.findings_count} issues"+ return f"PostHog Review finished reviewing {subject} and {found}. [Open the review]({finished.review_url})"+++def stamphog_result(finished: FinishedReviewRun, follow_up: FollowUp) -> str:+ subject = _subject(follow_up)+ if finished.status == ReviewRunStatus.FAILED:+ return f"Stamphog couldn't finish reviewing {subject}. Try `stamp` again in a few minutes."+ if finished.status == ReviewRunStatus.GATED:+ return f"Stamphog can't approve {subject} on its own, so it needs a person to review it."+ if finished.verdict == ReviewVerdict.APPROVED:+ return f"Stamphog approved {subject}."+ if finished.verdict == ReviewVerdict.REFUSED:+ return f"Stamphog didn't approve {subject}. Its review on the pull request says why."+ if finished.verdict == ReviewVerdict.ESCALATE:+ return f"Stamphog wants a person to review {subject}. Its review on the pull request says why."+ if finished.verdict == ReviewVerdict.WAIT:+ return f"Stamphog is waiting before it decides on {subject}. Its review on the pull request says what for."+ return f"Stamphog finished reviewing {subject}. Its review is on the pull request."+++def qa_result(status: str, task_url: str, follow_up: FollowUp) -> str:+ subject = _subject(follow_up)+ run = f"[Open the run in PostHog Code]({task_url})"+ if status == "completed":+ return f"The QA run on {subject} finished, and its report is on the pull request. {run}"+ if status == "cancelled":+ return f"The QA run on {subject} was cancelled. {run}"+ return f"The QA run on {subject} failed. {run}"diff --git a/products/commands/backend/receivers.py b/products/commands/backend/receivers.pynew file mode 100644index 000000000000..0152165741e7--- /dev/null+++ b/products/commands/backend/receivers.py@@ -0,0 +1,71 @@+"""Sends a command's result to where the command came from, once the work it started ends.++The products report the end through their own hook registries, because they cannot import this+product: Stamphog and PostHog Review call a registered callback, and a QA run's save fires the task+run signal. Each callback finds the follow-up the handler saved and queues the message, so the+product's worker never waits on Slack.++This module loads at Django setup, so it imports only the light hook modules.+"""++from typing import Any++from django.db import transaction++from posthog.models.scoping.manager import resolve_effective_team_id+from posthog.utils import absolute_uri++from products.review_hog.backend.facade.finished_review_hooks import (+ FinishedReview,+ register_finished_review_hook as register_review_hook,+)+from products.stamphog.backend.facade.finished_review_hooks import (+ FinishedReviewRun,+ register_finished_review_hook as register_stamphog_hook,+)+from products.tasks.backend.facade.task_run_signals import connect_task_run_post_save++from .logic import follow_ups, results+++def connect() -> None:+ register_review_hook(on_review_finished)+ register_stamphog_hook(on_stamphog_review_finished)+ connect_task_run_post_save(on_task_run_saved, dispatch_uid="commands_qa_result")+++def _deliver(follow_up: follow_ups.FollowUp, message: str) -> None:+ from .tasks.tasks import deliver_follow_up # noqa: PLC0415 — keeps Celery task modules off the setup import path++ deliver_follow_up.delay(address=dict(follow_up.address), message=message)+++def on_review_finished(finished: FinishedReview) -> None:+ project_id = resolve_effective_team_id(finished.team_id)+ key = follow_ups.review_key(project_id, finished.repository, finished.pr_number, finished.review_mode)+ for follow_up in follow_ups.take(key):+ _deliver(follow_up, results.review_result(finished, follow_up))+++def on_stamphog_review_finished(finished: FinishedReviewRun) -> None:+ for follow_up in follow_ups.take(follow_ups.stamphog_run_key(str(finished.run_id))):+ _deliver(follow_up, results.stamphog_result(finished, follow_up))+++def on_task_run_saved(sender: type, instance: Any, created: bool, **kwargs: Any) -> None:+ # Every task run save calls this, so the checks that need no query come first.+ if created or not instance.is_terminal:+ return+ update_fields = kwargs.get("update_fields")+ if update_fields is not None and "status" not in update_fields:+ return+ key = follow_ups.task_run_key(str(instance.id))+ status = str(instance.status)+ task_url = absolute_uri(f"/project/{instance.team_id}/tasks/{instance.task_id}")++ # After the commit, so a rolled-back save takes no follow-up with it.+ def deliver() -> None:+ for follow_up in follow_ups.take(key):+ _deliver(follow_up, results.qa_result(status, task_url, follow_up))++ transaction.on_commit(deliver, robust=True)diff --git a/products/commands/backend/tasks/tasks.py b/products/commands/backend/tasks/tasks.pyindex 34e6c01c7785..4545e068facb 100644--- a/products/commands/backend/tasks/tasks.py+++ b/products/commands/backend/tasks/tasks.py@@ -4,7 +4,7 @@ from celery import shared_taskfrom ..channels.github.comments import dispatch_comment_commandfrom ..channels.github.intake import CommentCommandRequest-from ..channels.slack.mentions import SlackCommandRequest, dispatch_slack_command+from ..channels.slack.mentions import SlackCommandRequest, SlackThread, dispatch_slack_command, post_in_threadfrom ..logic.subjects import subject_from_payload@@ -72,3 +72,11 @@ def run_slack_command(user_ids=tuple(user_ids),))+++@shared_task(ignore_result=True, max_retries=0)+def deliver_follow_up(*, address: dict[str, str | int], message: str) -> None:+ """Posts the result of a command's work where the command came from. Slack is the only channel+ that asks for one."""+ if address.get("channel") == "slack":+ post_in_thread(SlackThread.from_address(address), message)diff --git a/products/commands/backend/tests/test_dispatch.py b/products/commands/backend/tests/test_dispatch.pyindex 212664af3815..c1ba0d1c32f2 100644--- a/products/commands/backend/tests/test_dispatch.py+++ b/products/commands/backend/tests/test_dispatch.py@@ -1,6 +1,7 @@import hmacimport jsonimport hashlib+import dataclassesfrom datetime import timedeltafrom itertools import countfrom typing import Any@@ -35,7 +36,9 @@ from products.commands.backend.logic.commands import CommandContext, CommandRequfrom products.commands.backend.logic.github import InstallationGitHub, Reaction, UnsupportedPullRequestfrom products.commands.backend.logic.handlers import handle_loop, handle_qafrom products.commands.backend.logic.schema import LoopArgs, QaArgs-from products.commands.backend.tasks.tasks import run_slack_command+from products.commands.backend.receivers import on_review_finished+from products.commands.backend.tasks.tasks import deliver_follow_up, run_slack_command+from products.review_hog.backend.facade.finished_review_hooks import FinishedReviewfrom products.review_hog.backend.facade.reviews import (RUN_MODE_FLASH,RUN_MODE_REVIEW,@@ -59,6 +62,7 @@ CLAIM_CACHE = "products.commands.backend.logic.admission.cache"CONSUME_BUDGET = "products.commands.backend.logic.admission.consume"RUN_COMMENT_COMMAND = "products.commands.backend.tasks.tasks.run_comment_command.delay"RUN_SLACK_COMMAND = "products.commands.backend.tasks.tasks.run_slack_command.delay"+DELIVER_FOLLOW_UP = "products.commands.backend.tasks.tasks.deliver_follow_up.delay"SLACK_INSTALLATION_GITHUB = "products.commands.backend.logic.subjects.InstallationGitHub.for_installation"SLACK_POST = "products.commands.backend.channels.slack.mentions.post_message"@@ -243,7 +247,9 @@ class TestDispatchCommentCommand(BaseTest):Integration.objects.create(team=owner_team, kind="github", integration_id=INSTALLATION_ID, config={})self._link_github_account(self.user, days_ago=10)self._link_github_account(second_user, days_ago=1 if second_linked_last else 30)- started = PRReviewRequestOutcome(status=PRReviewRequestStatus.STARTED, workflow_id="wf-1")+ started = PRReviewRequestOutcome(+ status=PRReviewRequestStatus.STARTED, workflow_id="wf-1", head_sha="abc123", review_mode="flash"+ )with (patch(@@ -413,7 +419,9 @@ class TestDispatchCommentCommand(BaseTest):None: None,}github = FakeGitHub()- started = PRReviewRequestOutcome(status=PRReviewRequestStatus.STARTED, workflow_id="wf-1")+ started = PRReviewRequestOutcome(+ status=PRReviewRequestStatus.STARTED, workflow_id="wf-1", head_sha="abc123", review_mode="flash"+ )with (patch(OWNING_TEAM_ID, return_value=owner_team_ids[owner]),@@ -547,7 +555,9 @@ class TestDispatchCommentCommand(BaseTest):team=self.team, kind="slack", integration_id="T1", config={}, sensitive_config={"access_token": "xoxb-x"})mention = self._slack_mention("review", (str(self.organization.id),), integration_id=slack.id)- started = PRReviewRequestOutcome(status=PRReviewRequestStatus.STARTED, workflow_id="wf-1")+ started = PRReviewRequestOutcome(+ status=PRReviewRequestStatus.STARTED, workflow_id="wf-1", head_sha="abc123", review_mode="flash"+ )budget = BucketDecision(allowed=within_budget, remaining=0, limit=5, retry_after=60, reset=600)with (@@ -570,6 +580,35 @@ class TestDispatchCommentCommand(BaseTest):else:request_pr_review.assert_not_called()+ finished = FinishedReview(+ team_id=self.team.id,+ report_id="r1",+ repository=REPOSITORY,+ pr_number=7,+ review_mode="flash",+ failed=False,+ findings_count=2,+ published=True,+ review_url="https://example.com/review",+ )+ with (+ patch(DELIVER_FOLLOW_UP, side_effect=lambda **kwargs: deliver_follow_up(**kwargs)),+ patch(SLACK_POST) as follow_up_post,+ ):+ # A Deep turn that was already running is not the review this thread asked for, and neither+ # is the same review in another project.+ on_review_finished(dataclasses.replace(finished, review_mode="full"))+ other_project = Team.objects.create(organization=self.organization, name="Other project")+ on_review_finished(dataclasses.replace(finished, team_id=other_project.id))+ on_review_finished(finished)+ on_review_finished(finished)+ if within_budget and github_reachable:+ follow_up_post.assert_called_once()+ assert follow_up_post.call_args.kwargs["thread_ts"] == "100.1"+ assert "found 2 issues" in follow_up_post.call_args.args[3]+ else:+ follow_up_post.assert_not_called()+@patch("posthog.ingress.github.provider.get_instance_setting", return_value="test-webhook-secret")def test_a_signed_comment_with_a_command_is_queued(self, _secret: MagicMock) -> None:reset_consumer_registry()diff --git a/products/commands/backend/tests/test_results.py b/products/commands/backend/tests/test_results.pynew file mode 100644index 000000000000..92242d88a46a--- /dev/null+++ b/products/commands/backend/tests/test_results.py@@ -0,0 +1,83 @@+from types import SimpleNamespace+from uuid import UUID, uuid4++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.cache import cache+from django.test import SimpleTestCase++from parameterized import parameterized++from products.commands.backend.logic.follow_ups import FollowUp, remember, task_run_key+from products.commands.backend.logic.results import stamphog_result+from products.commands.backend.receivers import on_task_run_saved+from products.stamphog.backend.facade.enums import ReviewRunStatus, ReviewVerdict+from products.stamphog.backend.facade.finished_review_hooks import FinishedReviewRun++FOLLOW_UP = FollowUp(+ address={+ "channel": "slack",+ "integration_id": 1,+ "integration_team_id": 1,+ "slack_channel": "C1",+ "thread_ts": "1",+ },+ subject_label="acme/widgets#7",+ subject_url="https://github.com/acme/widgets/pull/7",+)+DELIVER_FOLLOW_UP = "products.commands.backend.tasks.tasks.deliver_follow_up.delay"+++class TestStamphogResult(SimpleTestCase):+ @parameterized.expand(+ [+ ("approved", ReviewRunStatus.COMPLETED, ReviewVerdict.APPROVED, "Stamphog approved"),+ ("refused", ReviewRunStatus.COMPLETED, ReviewVerdict.REFUSED, "Stamphog didn't approve"),+ ("escalated", ReviewRunStatus.COMPLETED, ReviewVerdict.ESCALATE, "wants a person to review"),+ # A gated run stores WAIT, but the gate is the answer, not a wait.+ ("gated", ReviewRunStatus.GATED, ReviewVerdict.WAIT, "can't approve"),+ ("waiting", ReviewRunStatus.COMPLETED, ReviewVerdict.WAIT, "is waiting"),+ # A failed run keeps the verdict it had, which must not read as a decision.+ ("failed", ReviewRunStatus.FAILED, ReviewVerdict.APPROVED, "couldn't finish"),+ ]+ )+ def test_names_the_outcome_the_run_saved(+ self, _name: str, status: ReviewRunStatus, verdict: ReviewVerdict, expected: str+ ) -> None:+ finished = FinishedReviewRun(+ run_id=uuid4(), team_id=1, repository="acme/widgets", pr_number=7, status=status, verdict=verdict+ )++ assert expected in stamphog_result(finished, FOLLOW_UP)+++class TestQaResult(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ cache.clear()++ def _run(self, run_id: UUID, status: str, *, is_terminal: bool, state: dict | None = None) -> SimpleNamespace:+ return SimpleNamespace(+ id=run_id, team_id=self.team.id, task_id=uuid4(), status=status, is_terminal=is_terminal, state=state+ )++ def test_a_qa_run_reports_once_when_it_ends(self) -> None:+ run_id = uuid4()+ remember(task_run_key(str(run_id)), FOLLOW_UP)+ # The task run API lets the run's owner write its state, so an address there must not count.+ planted = self._run(+ uuid4(), "completed", is_terminal=True, state={"commands_follow_up": FOLLOW_UP.to_payload()}+ )++ with patch(DELIVER_FOLLOW_UP) as deliver, self.captureOnCommitCallbacks(execute=True):+ on_task_run_saved(type(None), self._run(run_id, "in_progress", is_terminal=False), created=False)+ on_task_run_saved(type(None), planted, created=False, update_fields=["status"])+ # A terminal run can be saved again, for example with its output.+ finished = self._run(run_id, "completed", is_terminal=True)+ on_task_run_saved(type(None), finished, created=False, update_fields=["status"])+ on_task_run_saved(type(None), finished, created=False, update_fields=None)++ deliver.assert_called_once()+ assert deliver.call_args.kwargs["address"]["thread_ts"] == "1"+ assert "finished" in deliver.call_args.kwargs["message"]diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 67c40e833f08..5c4964ef6e6f 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -486,6 +486,7 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /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.+ After the completed or failed analytics event, the same activity calls every callback in `facade/finished_review_hooks.py` with the turn's outcome, the valid findings count and the review's deep link. The commands product registers one to post the result in the Slack thread that asked for the review. A product that depends on review_hog registers there instead of being imported, and a callback that raises is logged and never fails the turn.**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`). The 👍 does not come back: a clean turn adds it only while no turn of the PR published findings (`published_head_sha` unset).A clean Standard turn that a person asked for (`REQUESTED_TRIGGERS`: the label, a comment, the UI, or the CLI) also posts a one-line review that says it found nothing, because the 👍 is easy to miss next to other bots' reactions. It has a hidden `reviewhog:clean-reply:<report>:<head>` marker, so each head gets one reply, also when a workflow retry starts a new turn. A second request on the same head reuses the findings stored for that head (`load_perspective_results`), runs no sandbox and posts nothing new, because the first reply already answers it. Automatic and inbox turns keep only the 👍.diff --git a/products/review_hog/backend/facade/finished_review_hooks.py b/products/review_hog/backend/facade/finished_review_hooks.pynew file mode 100644index 000000000000..b31ead334c1c--- /dev/null+++ b/products/review_hog/backend/facade/finished_review_hooks.py@@ -0,0 +1,46 @@+"""Registry of callbacks that hear about a PostHog Review turn once it completes, or fails for good.++A product that asks for a review registers a callback from its ``AppConfig.ready()``, for example+to tell the person who asked how it went. review_hog cannot import such a product when that product+already depends on review_hog, so the callback comes here through this registry. A callback that+raises is logged and never fails the review. Mirrors ``products/stamphog/backend/facade/review_evidence.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+++@dataclass(frozen=True, kw_only=True)+class FinishedReview:+ team_id: int+ report_id: str+ repository: str+ pr_number: int+ # REVIEW_MODE_FULL or REVIEW_MODE_FLASH, as the review request reported it.+ review_mode: str+ failed: bool+ # Valid findings of this turn. Zero for a failed turn.+ findings_count: int+ # False when the turn posted nothing on the pull request, for example a clean review.+ published: bool+ review_url: str+++FinishedReviewHook = Callable[[FinishedReview], None]++_finished_review_hooks: list[FinishedReviewHook] = []+++def register_finished_review_hook(fn: FinishedReviewHook) -> None:+ # AppConfig.ready() can run more than once in one process, for example in tests.+ if fn not in _finished_review_hooks:+ _finished_review_hooks.append(fn)+++def get_finished_review_hooks() -> tuple[FinishedReviewHook, ...]:+ return tuple(_finished_review_hooks)diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex eea1da21db95..664d79e0fd8a 100644--- a/products/review_hog/backend/temporal/activities.py+++ b/products/review_hog/backend/temporal/activities.py@@ -39,6 +39,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.review_hog.backend.app_identity import posthog_app_loginfrom products.review_hog.backend.automatic_reviews import automatic_flash_allowed, observe_dispatchfrom products.review_hog.backend.facade.enums import ReviewRequestRefusal+from products.review_hog.backend.facade.finished_review_hooks import FinishedReview, get_finished_review_hooksfrom products.review_hog.backend.label_reviews import comment_commands_enabled, draft_review_notice, label_commands_hintfrom products.review_hog.backend.models import ReviewProjectSettings, ReviewReport, ReviewUserSettingsfrom products.review_hog.backend.pr_owner import PullRequestOwnerResolver@@ -151,6 +152,7 @@ from products.review_hog.backend.reviewer.status_comment import (finalize_status_comment,maybe_refresh_status_comment,post_failure_comment,+ report_deep_link,)from products.review_hog.backend.reviewer.telemetry import review_event_uuid, review_routing_propertiesfrom products.review_hog.backend.reviewer.tools.coordinator_review import (@@ -650,6 +652,8 @@ class TrackReviewFailedInput:review_mode: str = REVIEW_MODE_FULLflash_reasoning_effort: str = ReasoningEffort.MEDIUM.valuereview_design: str = REVIEW_DESIGN_PIPELINE+ # The workflow retries a failed turn, and only the last failure is the outcome.+ last_attempt: bool = True@frozen@@ -2470,11 +2474,53 @@ def _track_review_completed_safe(input: TrackReviewCompletedInput) -> None:logger.exception("Failed to capture reviewhog_review_completed for report %s; continuing", input.report_id)+def _notify_review_finished(+ *,+ team_id: int,+ report_id: str,+ run_index: int,+ review_mode: str,+ failed: bool,+ published: bool,+) -> None:+ """Tell the registered callbacks how the turn ended. Like the analytics, it never fails a review."""+ hooks = get_finished_review_hooks()+ if not hooks:+ return+ try:+ report = ReviewReport.objects.for_team(team_id).get(id=report_id)+ if report.pr_number is None:+ return+ findings_count = (+ 0 if failed else len(load_valid_findings(team_id=team_id, report_id=report_id, run_index=run_index))+ )+ except Exception:+ logger.exception("Could not load report %s for the finished-review callbacks; continuing", report_id)+ return+ finished = FinishedReview(+ team_id=team_id,+ report_id=report_id,+ repository=report.repository,+ pr_number=report.pr_number,+ review_mode=review_mode,+ failed=failed,+ findings_count=findings_count,+ published=published,+ review_url=report_deep_link(team_id, report_id),+ )+ for hook in hooks:+ try:+ hook(finished)+ except Exception:+ logger.exception("A finished-review callback failed for report %s; continuing", report_id)++@activity.defn@scoped_temporal()@close_db_connectionsasync def track_review_completed_activity(input: TrackReviewCompletedInput) -> None:- """Capture the turn's `reviewhog_review_completed` product-analytics event.+ """Capture the turn's `reviewhog_review_completed` product-analytics event, then tell the+ finished-review callbacks.One event per finalized turn (published or stored), across every trigger and repo — theper-review count product dashboards aggregate, which the step-level `task_*` events can't@@ -2482,6 +2528,14 @@ async def track_review_completed_activity(input: TrackReviewCompletedInput) -> Na review, so any failure is logged, not raised."""await database_sync_to_async(_track_review_completed_safe, thread_sensitive=False)(input)+ await database_sync_to_async(_notify_review_finished, thread_sensitive=False)(+ team_id=input.team_id,+ report_id=input.report_id,+ run_index=input.run_index,+ review_mode=input.review_mode,+ failed=False,+ published=input.published,+ )def _track_review_failed(input: TrackReviewFailedInput) -> None:@@ -2531,9 +2585,18 @@ async def track_review_failed_activity(input: TrackReviewFailedInput) -> None:counts: a parent retry can fail and then complete at the same (report_id, run_index, review_mode),so a turn counts as failed only when that combination has a failed event and no completed event.Anti-join on report_id + run_index + review_mode, treating an absent mode as Full for legacy events.- Best-effort, like the completed event.+ Best-effort, like the completed event. The finished-review callbacks hear about the last failure too."""await database_sync_to_async(_track_review_failed_safe, thread_sensitive=False)(input)+ if input.last_attempt:+ await database_sync_to_async(_notify_review_finished, thread_sensitive=False)(+ team_id=input.team_id,+ report_id=input.report_id,+ run_index=input.run_index,+ review_mode=input.review_mode,+ failed=True,+ published=False,+ )# --- The PR's live status comment -------------------------------------------------------------------diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.pyindex e1aee744d060..576a1e904706 100644--- a/products/review_hog/backend/temporal/workflow.py+++ b/products/review_hog/backend/temporal/workflow.py@@ -868,6 +868,7 @@ class ReviewPRWorkflow:review_mode=inputs.review_mode,flash_reasoning_effort=acting.flash_reasoning_effort,review_design=review_design,+ last_attempt=_non_retryable_cause(e) is not None or _out_of_attempts(),),start_to_close_timeout=_QUICK_TIMEOUT,retry_policy=_RETRY,diff --git a/products/review_hog/backend/tests/test_review_completed_tracking.py b/products/review_hog/backend/tests/test_review_completed_tracking.pyindex 6f7e066ff098..faa414f3297c 100644--- a/products/review_hog/backend/tests/test_review_completed_tracking.py+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py@@ -41,6 +41,7 @@ from products.review_hog.backend.temporal.activities import (TrackReviewFailedInput,TrackReviewStartedInput,_gate_push,+ _notify_review_finished,_track_review_completed,_track_review_completed_safe,_track_review_failed,@@ -211,6 +212,21 @@ class TestTrackReviewCompleted(BaseTest):assert props["reviewhog_version"] == "reviewhog-full-9-9"assert props["reviewhog_fingerprint"] == "abc1234"+ hooks = (MagicMock(side_effect=RuntimeError("callback down")), MagicMock())+ with patch("products.review_hog.backend.temporal.activities.get_finished_review_hooks", return_value=hooks):+ _notify_review_finished(+ team_id=self.team.id,+ report_id=report_id,+ run_index=1,+ review_mode="full",+ failed=False,+ published=published,+ )+ finished = hooks[1].call_args.args[0]+ assert (finished.repository, finished.pr_number, finished.findings_count) == ("o/r", 7, 1)+ assert (finished.failed, finished.published) == (False, published)+ assert finished.review_url.endswith(f"/project/{self.team.id}/code-review?review={report_id}")+def test_single_agent_turn_reports_its_finding_funnel_and_sessions(self) -> None:# The cap, the dedup calls, and the lens sessions are only measurable through these# properties, the must-fix share is how priority inflation shows up before the must-fixdiff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.mdindex 2425898952ec..7257fa8af1e3 100644--- a/products/stamphog/AGENTS.md+++ b/products/stamphog/AGENTS.md@@ -194,6 +194,7 @@ A refusal writes nothing to GitHub and creates no run, so it cannot leave or rem- 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.+- `facade/finished_review_hooks.py` is the other direction: callbacks that hear a run's outcome. `post_verdict` calls them right after the terminal save wins, before its trailing GitHub steps, and `mark_review_failed` right after its FAILED save, before its cleanup. A superseded run, or a save that lost to a supersession, calls nothing. A callback that raises is logged and never fails the run, because the outcome is already saved and posted. The commands product registers one to post the outcome in the Slack thread that asked for the review.- `posthog[bot]` is deliberately not a trusted reactor. Its 👀 is a cue for people, and the review evidence replaces it for stamphog.## Trust boundariesdiff --git a/products/stamphog/backend/facade/finished_review_hooks.py b/products/stamphog/backend/facade/finished_review_hooks.pynew file mode 100644index 000000000000..e9b15f683324--- /dev/null+++ b/products/stamphog/backend/facade/finished_review_hooks.py@@ -0,0 +1,47 @@+"""Registry of callbacks that hear about a stamphog review run once it reaches its outcome.++A product that asks stamphog for a review registers a callback from its ``AppConfig.ready()``, for+example to tell the person who asked how it went. Stamphog cannot import such a product when that+product already depends on stamphog, so the callback comes to stamphog through this registry.+Stamphog calls every callback after the run's terminal save, and a callback that raises is logged+and never fails the review. A superseded run calls nothing, because it has no outcome. Mirrors+``review_evidence.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 uuid import UUID++from .enums import ReviewRunStatus, ReviewVerdict+++@dataclass(frozen=True, kw_only=True)+class FinishedReviewRun:+ """One review run's outcome. GATED and FAILED runs carry the verdict they stored."""++ run_id: UUID+ team_id: int+ repository: str+ pr_number: int+ status: ReviewRunStatus+ verdict: ReviewVerdict+++FinishedReviewHook = Callable[[FinishedReviewRun], None]++_finished_review_hooks: list[FinishedReviewHook] = []+++def register_finished_review_hook(fn: FinishedReviewHook) -> None:+ # AppConfig.ready() can run more than once in one process, for example in tests.+ if fn not in _finished_review_hooks:+ _finished_review_hooks.append(fn)+++def get_finished_review_hooks() -> tuple[FinishedReviewHook, ...]:+ return tuple(_finished_review_hooks)diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.pyindex 79bf8f475bd9..375d6e30584d 100644--- a/products/stamphog/backend/temporal/activities.py+++ b/products/stamphog/backend/temporal/activities.py@@ -63,6 +63,7 @@ from products.stamphog.backend.facade.enums import (ReviewTrigger,ReviewVerdict,)+from products.stamphog.backend.facade.finished_review_hooks import FinishedReviewRun, get_finished_review_hooksfrom products.stamphog.backend.facade.review_evidence import (ReviewEvidenceProvider,ReviewEvidenceState,@@ -1842,6 +1843,10 @@ def post_verdict(input: StamphogReviewInput) -> dict:activity.logger.info(f"Run {run.id} superseded during verdict posting; verdict not saved")return {"verdict": "skipped_superseded"}+ # Right after the save wins: the GitHub steps below can still fail the activity, and the+ # outcome must not wait on them.+ _notify_finished_review(run, input.team_id, ReviewRunStatus(run.status))+# Hand a refused/escalated PR to ReviewHog only AFTER the refusal verdict wins the terminal save# above — running it before would trigger ReviewHog for a stale refusal that a superseding delivery# then overrode (a newer run might approve the same head). Adding the ReviewHog trigger label starts@@ -1892,6 +1897,25 @@ def post_verdict(input: StamphogReviewInput) -> dict:return {"verdict": str(parsed.verdict), "waited_on_external_review": _waited_on_external_review(run)}+def _notify_finished_review(run: ReviewRun, team_id: int, status: ReviewRunStatus) -> None:+ """Tell the registered callbacks the outcome the run just saved. Called after the terminal save."""+ pull_request = run.pull_request+ finished = FinishedReviewRun(+ run_id=run.id,+ team_id=team_id,+ repository=pull_request.repo_config.repository,+ pr_number=pull_request.pr_number,+ status=status,+ verdict=ReviewVerdict(run.verdict),+ )+ for hook in get_finished_review_hooks():+ # A callback belongs to another product, and the outcome is already saved and posted.+ try:+ hook(finished)+ except Exception:+ activity.logger.exception(f"stamphog: finished-review callback failed for run {run.id}")++@activity.defn@asyncifydef mark_review_failed(input: MarkReviewFailedInput) -> None:@@ -1930,6 +1954,10 @@ def mark_review_failed(input: MarkReviewFailedInput) -> None:.exclude(status__in=TERMINAL_STATUSES).update(status=ReviewRunStatus.FAILED, error=first_error_line, completed_at=now, updated_at=now))+ # Right after the save wins, before the cleanup below can fail the activity: a retry stops at+ # the terminal guard and would never report.+ if marked_failed:+ _notify_finished_review(run, input.team_id, ReviewRunStatus.FAILED)# This run is done reviewing (unrecoverably) — clean up its own "review in flight" 👀 too. After# the terminal save on purpose: the removal's live-peer check must see this run as terminal, or# two concurrently failing runs could each defer to the other and leak the reaction.@@ -1963,9 +1991,9 @@ def mark_review_failed(input: MarkReviewFailedInput) -> None:},)- # Last, because this step raises. A retry returns through the terminal guard, which posts the- # notice and nothing else, so the event above must reach PostHog on this attempt.if marked_failed:+ # Last, because this step raises. A retry returns through the terminal guard, which posts the+ # notice and nothing else, so the event above must reach PostHog on this attempt._post_failure_notice(client, run, input.team_id)diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.pyindex 380b66db8c3c..37bc5c16f1e2 100644--- a/products/stamphog/backend/tests/test_integration.py+++ b/products/stamphog/backend/tests/test_integration.py@@ -78,6 +78,7 @@ from products.tasks.backend.models import Task, TaskRunREPO = "acme/widgets"INSTALLATION_ID = "2001"BASE_SHA = "base000"+FINISHED_REVIEW_HOOKS = "products.stamphog.backend.temporal.activities.get_finished_review_hooks"POLICY_DEFAULTS_DIR = Path(__file__).resolve().parents[2] / "packages" / "pr-approval-agent" / "defaults"@@ -1418,7 +1419,11 @@ def test_mark_review_failed_captures_failure_event(team, stamphog_chain, raw_err# ph_scoped_capture is a context manager yielding the capture callable, so the patch# provides a context manager whose __enter__ returns the mock to assert against.capture_fn = MagicMock()- with patch("products.stamphog.backend.temporal.activities.ph_scoped_capture") as mock_capture_cm:+ finished_hook = MagicMock()+ with (+ patch("products.stamphog.backend.temporal.activities.ph_scoped_capture") as mock_capture_cm,+ patch(FINISHED_REVIEW_HOOKS, return_value=(finished_hook,)),+ ):mock_capture_cm.return_value.__enter__.return_value = capture_fnmock_capture_cm.return_value.__exit__.return_value = False_run_activity(mark_review_failed, MarkReviewFailedInput(str(run.id), team.id, raw_error))@@ -1426,6 +1431,7 @@ def test_mark_review_failed_captures_failure_event(team, stamphog_chain, raw_errrun.refresh_from_db()assert run.status == ReviewRunStatus.FAILEDassert run.error == expected_stored+ assert finished_hook.call_args.args[0].status == ReviewRunStatus.FAILEDassert capture_fn.call_args.kwargs["event"] == "stamphog_review_failed"assert capture_fn.call_args.kwargs["distinct_id"] == "devex-dev"props = capture_fn.call_args.kwargs["properties"]@@ -1502,10 +1508,15 @@ def test_approval_posted_while_losing_supersession_race_is_dismissed(team, stampReviewRun.objects.for_team(team.id).filter(id=run.id).update(status=ReviewRunStatus.SUPERSEDED)return original_comment_id(obj)- with patch.object(activities, "_comment_id", side_effect=_supersede_then_extract):+ finished_hook = MagicMock()+ with (+ patch.object(activities, "_comment_id", side_effect=_supersede_then_extract),+ patch(FINISHED_REVIEW_HOOKS, return_value=(finished_hook,)),+ ):result = _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))assert result == {"verdict": "skipped_superseded"}+ finished_hook.assert_not_called()approvals = [w for w in recorder.github_writes if w["kind"] == "approve_review"]dismissals = [w for w in recorder.github_writes if w["kind"] == "dismiss_review"]assert len(approvals) == 1@@ -2701,6 +2712,7 @@ def test_each_non_approval_posts_its_own_review(team_id=team.id, repo_config=repo_config, pr_number=101, author_login="devex-dev")+ finished_hook = MagicMock(side_effect=RuntimeError("callback down"))for _ in range(2):run = ReviewRun.objects.for_team(team.id).create(team_id=team.id,@@ -2710,8 +2722,12 @@ def test_each_non_approval_posts_its_own_review(output={"reviewer_raw": engine_output},)# Twice per run: a Temporal retry after the post must not repeat the review.- _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))- _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))+ with patch(FINISHED_REVIEW_HOOKS, return_value=(finished_hook,)):+ _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))+ _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))+ run.refresh_from_db()+ finished = finished_hook.call_args.args[0]+ assert (finished.status, finished.verdict) == (run.status, run.verdict)writes = stamphog_chain.recorder.github_writesassert [w for w in writes if w["kind"] in ("issue_comment", "issue_comment_edit")] == []