: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): tell the reviewer why it was asked to look (#86753)
Julian Bez22c7c7fa1ab5
diff --git a/products/stamphog/backend/facade/api.py b/products/stamphog/backend/facade/api.pyindex a4f225d0b6b4..1f516a8a8e61 100644--- a/products/stamphog/backend/facade/api.py+++ b/products/stamphog/backend/facade/api.py@@ -18,6 +18,7 @@ from django.utils import timezoneimport structlog+from ..logic.review_trigger import derive_review_triggerfrom ..models import DigestChannel, DigestRun, PullRequest, ReviewRun, StamphogRepoConfigfrom . import contractsfrom .enums import (@@ -147,16 +148,12 @@ _RunQS = TypeVar("_RunQS", bound=QuerySet)def _derive_trigger(obj: ReviewRun) -> ReviewTrigger:- """Why stamphog looked at this PR: inbox provenance first, then the repo's review mode.-- Inbox provenance outranks the repo mode: a self-driving run is dispatched from the inbox- whether or not the repo also reviews every PR event.- """- if (obj.output or {}).get("inbox_review"):- return ReviewTrigger.SELF_DRIVING- if obj.pull_request.repo_config.review_mode == ReviewMode.LABEL:- return ReviewTrigger.LABEL- return ReviewTrigger.ALL+ """Why stamphog looked at this PR. The rule itself lives in logic/review_trigger.py, because+ the reviewer invocation has to answer the same question before a run exists to read."""+ return derive_review_trigger(+ has_inbox_review=bool((obj.output or {}).get("inbox_review")),+ review_mode=obj.pull_request.repo_config.review_mode,+ )def _filter_by_trigger(qs: _RunQS, trigger: str) -> _RunQS:diff --git a/products/stamphog/backend/logic/review_trigger.py b/products/stamphog/backend/logic/review_trigger.pynew file mode 100644index 000000000000..8dc353aeb2f4--- /dev/null+++ b/products/stamphog/backend/logic/review_trigger.py@@ -0,0 +1,45 @@+"""Why stamphog looked at a PR, derived from its provenance and the repo's review mode.++One rule, two Python callers: the API derives it for a stored run, and the invocation builder sends+it to the reviewer. A third expression of the same precedence lives in SQL+(``facade/api.py::_filter_by_trigger``) and cannot share this code, so that one stays hand-synced.+"""++from __future__ import annotations++from typing import Any++from ..facade.enums import ReviewMode, ReviewTrigger+++def derive_review_trigger(*, has_inbox_review: bool, review_mode: ReviewMode | str) -> ReviewTrigger:+ """Inbox provenance outranks the repo mode.++ A self-driving run is dispatched from the inbox whether or not the repo also reviews every PR+ event, so a repo in ALL mode still reports SELF_DRIVING for those PRs.+ """+ if has_inbox_review:+ return ReviewTrigger.SELF_DRIVING+ if review_mode == ReviewMode.LABEL:+ return ReviewTrigger.LABEL+ return ReviewTrigger.ALL+++def trigger_for_run(*, output: dict[str, Any] | None, review_mode: ReviewMode | str) -> str:+ """The trigger to tell the reviewer, preferring what was stamped when the run was created.++ The reviewer reads this as fact in its trusted block, so it has to describe the delivery that+ admitted the run. Deriving it live would read a ``review_mode`` an admin may have changed since,+ and an ALL to LABEL switch would assert a request label the PR does not carry.++ Runs created before the stamp existed have nothing to read, so they derive it live as before.+ The facade deliberately keeps deriving instead of calling this: its display value is paired with+ a SQL filter that cannot read the stamp, and a display that disagreed with its own filter would+ hide rows the caller just saw.+ """+ stamped = (output or {}).get("review_trigger")+ if stamped:+ return str(stamped)+ return derive_review_trigger(+ has_inbox_review=bool((output or {}).get("inbox_review")), review_mode=review_mode+ ).valuediff --git a/products/stamphog/backend/logic/reviewer.py b/products/stamphog/backend/logic/reviewer.pyindex 3c59e14db7ec..4df8d2660150 100644--- a/products/stamphog/backend/logic/reviewer.py+++ b/products/stamphog/backend/logic/reviewer.py@@ -112,6 +112,7 @@ def build_reviewer_invocation(engine_dir: str,context_path: str,self_driving_review: bool = False,+ review_trigger: str = "",) -> ReviewerInvocation:"""Assemble the context payload + command that reviews this PR in the sandbox.@@ -129,6 +130,11 @@ def build_reviewer_invocation(``self_driving_review`` lets the engine review a bot-authored draft, the one exceptionto its bot-author refusal. It defaults closed here and in the engine, the Action runtimenever sets it, and only a run stamped with inbox provenance turns it on.+ ``review_trigger`` is a ReviewTrigger value naming why stamphog is looking at this PR, which+ the reviewer otherwise cannot tell: a requested review and an automatic one reach it identically.+ It stays separate from ``self_driving_review`` on purpose. That flag relaxes two security gates,+ this string only describes, and folding them together would put the carve-out back in play for+ a change to descriptive text. Empty for a local run, where there is no trigger to report."""context = {"repo": repo,@@ -144,6 +150,7 @@ def build_reviewer_invocation("author_pr_numbers": list(author_pr_numbers),"author_team_slugs": list(author_team_slugs),"self_driving_review": self_driving_review,+ "review_trigger": review_trigger,}command = ["uv", "run", f"{engine_dir}/review_local.py", "--context", context_path]return ReviewerInvocation(diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.pyindex 69f98f43b201..067273fa7734 100644--- a/products/stamphog/backend/tasks/tasks.py+++ b/products/stamphog/backend/tasks/tasks.py@@ -22,7 +22,13 @@ from celery import shared_taskfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.instance_setting import get_instance_setting-from products.stamphog.backend.facade.enums import TERMINAL_STATUSES, ReviewMode, ReviewRunStatus, ReviewVerdict+from products.stamphog.backend.facade.enums import (+ TERMINAL_STATUSES,+ ReviewMode,+ ReviewRunStatus,+ ReviewTrigger,+ ReviewVerdict,+)from products.stamphog.backend.facade.inbox_hooks import get_inbox_acting_reviewer_resolverfrom products.stamphog.backend.logic.approval_retention import (MAX_RETAINED_HEADS,@@ -33,6 +39,7 @@ from products.stamphog.backend.logic.approval_retention import (from products.stamphog.backend.logic.approvals import dismiss_stale_approvals_for_headfrom products.stamphog.backend.logic.audiences import ResolvedAudience, resolve_audiencesfrom products.stamphog.backend.logic.github_client import StamphogGitHubClient+from products.stamphog.backend.logic.review_trigger import derive_review_triggerfrom products.stamphog.backend.models import PullRequest, PullRequestAudience, ReviewRun, StamphogRepoConfigfrom products.stamphog.backend.temporal.client import execute_stamphog_review_workflowfrom products.tasks.backend.facade.api import find_signal_implementation_run@@ -1304,7 +1311,15 @@ def process_pull_request_event(payload: dict[str, Any], delivery_id: str) -> Nonstatus=ReviewRunStatus.QUEUED,# Inbox provenance for a carved-out re-review. The engine turns on its self-driving# behavior from this, and it attributes the run in the UI and analytics.- output={"inbox_review": inbox_review} if inbox_review is not None else {},+ # review_trigger is stamped now, not derived when the sandbox runs: the reviewer is+ # told this as fact in its trusted block, and re-deriving it later would read a+ # review_mode an admin may have changed since this delivery was admitted.+ output={+ **({"inbox_review": inbox_review} if inbox_review is not None else {}),+ "review_trigger": derive_review_trigger(+ has_inbox_review=inbox_review is not None, review_mode=repo_config.review_mode+ ).value,+ },)# Only start the workflow once the row is durably committed — an aborted# transaction must not leave a workflow chasing a run that never existed.@@ -1514,7 +1529,8 @@ def process_inbox_pr_review(head_sha=head_sha,delivery_id=None,status=ReviewRunStatus.QUEUED,- output={"inbox_review": inbox_review},+ # Always self-driving on this leg: it exists only for inbox-linked PRs.+ output={"inbox_review": inbox_review, "review_trigger": ReviewTrigger.SELF_DRIVING.value},)review_run_id = str(review_run.id)# A post-commit start failure propagates into the retry below; the retry re-entersdiff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.pyindex 73b4ee63a107..1006778f88a6 100644--- a/products/stamphog/backend/temporal/activities.py+++ b/products/stamphog/backend/temporal/activities.py@@ -43,6 +43,7 @@ from products.stamphog.backend.facade.enums import TERMINAL_STATUSES, ReviewModefrom products.stamphog.backend.logic.approvals import dismiss_stale_approvals_for_headfrom products.stamphog.backend.logic.audiences import resolve_audiencesfrom products.stamphog.backend.logic.github_client import StamphogGitHubClient, expected_app_bot_login+from products.stamphog.backend.logic.review_trigger import trigger_for_runfrom products.stamphog.backend.logic.reviewer import (ReviewerInvocation,ReviewerVerdict,@@ -459,6 +460,9 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:# The engine's carve-out for bot-authored drafts keys off this flag alone. It comes only# from the run's inbox provenance, stamped after the PR is linked to a signals run.self_driving_review=bool(output.get("inbox_review")),+ # Read as a description rather than a permission: the reviewer is told why it was asked,+ # and decides for itself what that means for this diff.+ review_trigger=trigger_for_run(output=output, review_mode=run.pull_request.repo_config.review_mode),)sandbox_class = get_sandbox_class_for_backend(_resolve_sandbox_backend())diff --git a/products/stamphog/backend/tests/test_logic.py b/products/stamphog/backend/tests/test_logic.pyindex c93e96fb2580..71f74c952141 100644--- a/products/stamphog/backend/tests/test_logic.py+++ b/products/stamphog/backend/tests/test_logic.py@@ -9,7 +9,7 @@ from django.test import SimpleTestCase, override_settingsimport jwtfrom parameterized import parameterized-from products.stamphog.backend.facade.enums import AudienceReason+from products.stamphog.backend.facade.enums import AudienceReason, ReviewMode, ReviewTriggerfrom products.stamphog.backend.logic.approval_retention import approved_diff_unchangedfrom products.stamphog.backend.logic.audiences import resolve_audiencesfrom products.stamphog.backend.logic.digest import (@@ -26,6 +26,7 @@ from products.stamphog.backend.logic.github_client import (StamphogGitHubError,_build_app_jwt,)+from products.stamphog.backend.logic.review_trigger import derive_review_trigger, trigger_for_runfrom products.stamphog.backend.logic.reviewer import build_reviewer_invocation, parse_reviewer_outputfrom products.stamphog.backend.logic.slack_digest import _build_blocks, _build_fallback_textfrom products.stamphog.backend.models import StamphogRepoConfig@@ -137,6 +138,68 @@ class BuildReviewerInvocationTests(SimpleTestCase):assert context["reviews"] == reviewsassert context["review_threads"] == review_threads+ def test_review_trigger_reaches_the_sandbox_context(self) -> None:+ # The reviewer cannot derive why it was asked; dropping the key silently returns it to a+ # prompt that reads a requested review and an automatic one the same way.+ def context_for(**kwargs: object) -> dict:+ invocation = build_reviewer_invocation(+ pr={"number": 1},+ files=[],+ reviews=[],+ discussion=[],+ review_threads=[],+ check_runs=[],+ pr_reactions=[],+ author_pr_numbers=[],+ author_team_slugs=[],+ base_sha="base",+ head_sha="head",+ repo="owner/repo",+ engine_dir="/engine",+ context_path="/ctx.json",+ **kwargs, # type: ignore[arg-type]+ )+ return json.loads(invocation.context_json)++ assert context_for(review_trigger="label")["review_trigger"] == "label"+ # Separate keys on purpose: self_driving_review relaxes gates, the trigger only describes.+ assert context_for()["review_trigger"] == ""+ assert context_for()["self_driving_review"] is False+++class ReviewTriggerTests(SimpleTestCase):+ @parameterized.expand(+ [+ # Inbox provenance outranks the repo mode, so a self-driving PR in an ALL-mode repo is+ # still reported as self-driving rather than as an ambient review.+ ("inbox_beats_all_mode", True, ReviewMode.ALL, ReviewTrigger.SELF_DRIVING),+ ("inbox_beats_label_mode", True, ReviewMode.LABEL, ReviewTrigger.SELF_DRIVING),+ ("label_mode_is_a_request", False, ReviewMode.LABEL, ReviewTrigger.LABEL),+ ("all_mode_is_ambient", False, ReviewMode.ALL, ReviewTrigger.ALL),+ ]+ )+ def test_precedence(self, _name: str, has_inbox: bool, mode: ReviewMode, expected: ReviewTrigger) -> None:+ assert derive_review_trigger(has_inbox_review=has_inbox, review_mode=mode) == expected++ def test_a_stamped_trigger_survives_a_mode_change(self) -> None:+ # The reviewer reads this as fact. An admin switching the repo to LABEL while the run sat in+ # the queue must not make it claim a request label the PR never carried.+ stamped = {"review_trigger": ReviewTrigger.ALL.value}+ assert trigger_for_run(output=stamped, review_mode=ReviewMode.LABEL) == "all"++ @parameterized.expand(+ [+ ("no_output", None, ReviewMode.ALL, "all"),+ ("empty_output", {}, ReviewMode.LABEL, "label"),+ ("inbox_only", {"inbox_review": {"trigger": "inbox"}}, ReviewMode.ALL, "self_driving"),+ ]+ )+ def test_an_unstamped_run_derives_live(+ self, _name: str, output: dict | None, mode: ReviewMode, expected: str+ ) -> None:+ # Runs queued before the stamp existed still have to answer, or their reviewer loses the slot.+ assert trigger_for_run(output=output, review_mode=mode) == expected+class DigestCapTests(SimpleTestCase):def test_the_cap_names_what_it_removed(self) -> None:diff --git a/products/stamphog/backend/tests/test_tasks.py b/products/stamphog/backend/tests/test_tasks.pyindex 918477c3bf61..f9eead42efe9 100644--- a/products/stamphog/backend/tests/test_tasks.py+++ b/products/stamphog/backend/tests/test_tasks.py@@ -845,6 +845,9 @@ def test_inbox_carve_out_rereviews_a_selfdriving_pr_past_every_gate(team, repo_c"task_run_id": str(dto.run_id),"acting_user_id": 777,}+ # Stamped at creation, so a later review_mode change can't rewrite what the reviewer is told.+ # The repo is in LABEL mode here, so this also pins the precedence at the stamping site.+ assert run.output["review_trigger"] == "self_driving"mock_execute.assert_called_once_with(review_run_id=str(run.id), team_id=team.id)# Fork-safety feeds the lookup the base repo and GitHub's head ref (matched against the run's# server-stamped branch); the config's team scopes it.diff --git a/products/stamphog/packages/pr-approval-agent/review_local.py b/products/stamphog/packages/pr-approval-agent/review_local.pyindex 1537eae12224..efc8f1dfd971 100644--- a/products/stamphog/packages/pr-approval-agent/review_local.py+++ b/products/stamphog/packages/pr-approval-agent/review_local.py@@ -395,7 +395,11 @@ def run(context: dict) -> dict:# head_checkout: the sandbox clones and checks out the PR head before this runs (see the server's# _clone_pr), so parent-PR symbols already resolve for stacked PRs and no worktree is needed.pipeline = Pipeline(- 0, context.get("repo") or "", self_driving=bool(context.get("self_driving_review")), head_checkout=True+ 0,+ context.get("repo") or "",+ self_driving=bool(context.get("self_driving_review")),+ review_trigger=str(context.get("review_trigger") or ""),+ head_checkout=True,)pipeline.pr = _build_pr_data(context)# Reads commit trailers with `git log base..head` against the checkout, so it needs no token,diff --git a/products/stamphog/packages/pr-approval-agent/review_pr.py b/products/stamphog/packages/pr-approval-agent/review_pr.pyindex 7cb0f263a667..59b8a6d37042 100644--- a/products/stamphog/packages/pr-approval-agent/review_pr.py+++ b/products/stamphog/packages/pr-approval-agent/review_pr.py@@ -209,6 +209,7 @@ class Pipeline:dry_run: bool = False,verbose: bool = False,self_driving: bool = False,+ review_trigger: str = "",head_checkout: bool = False,) -> None:self.pr_number = pr_number@@ -219,6 +220,10 @@ class Pipeline:# implementation run. It relaxes two gates (bot author, draft) and swaps author trust for# task provenance.self.self_driving = self_driving+ # Why the hosted runtime is reviewing this PR: "label", "all" or "self_driving". Descriptive+ # only. It reaches the prompt as one line and gates nothing, unlike self_driving above.+ # Empty for a local run, which has no trigger to report.+ self.review_trigger = review_trigger# True when REPO_ROOT already holds the PR head (the hosted sandbox clones and checks out# the head for every review). The Action reviews from a trunk checkout, so a stacked PR# needs a separate head worktree there — see _pr_head_worktree.@@ -491,6 +496,7 @@ class Pipeline:# False renders the provenance block empty, leaving every other prompt unchanged.# True swaps the author trust context for task provenance."self_driving": self.self_driving,+ "review_trigger": self.review_trigger,}def _summarize_assurance(self) -> dict:@@ -1063,6 +1069,8 @@ class Pipeline:"familiarity": familiarity_evidence(self.familiarity),# Audit trail: records that this review ran with the gates relaxed (see __init__)."self_driving": self.self_driving,+ # Audit trail: what the reviewer was told about why it was asked.+ "review_trigger": self.review_trigger,},"provenance": provenance_evidence(self.provenance),"gates": [diff --git a/products/stamphog/packages/pr-approval-agent/reviewer.py b/products/stamphog/packages/pr-approval-agent/reviewer.pyindex 4a489650ecb8..49c8ebfcb6aa 100644--- a/products/stamphog/packages/pr-approval-agent/reviewer.py+++ b/products/stamphog/packages/pr-approval-agent/reviewer.py@@ -302,6 +302,16 @@ def _apply_gateway_route(gateway: tuple[str, str] | None, attribution: dict[str,return query+# What the reviewer is told about why it was asked. One slot, one sentence per trigger, no guidance+# attached: the values differ because the facts differ, not because the reviewer should behave+# differently. Keys are ReviewTrigger values from the hosted context.+_INVOCATION_LINES = {+ "label": "Invocation: this repo reviews on request only, and this PR carries the request label.",+ "all": "Invocation: this repo reviews every pull request automatically.",+ "self_driving": "Invocation: dispatched from a self-driving Inbox implementation run.",+}++class Reviewer:"""LLM reviewer using Agent SDK."""@@ -571,6 +581,7 @@ class Reviewer:ownership = self._format_ownership(cl)assurance_block = self._format_assurance(cl)familiarity_block = self._format_familiarity(cl)+ invocation_block = self._format_invocation(cl)self_driving_block = self._format_self_driving(cl)gate_lines = []@@ -645,7 +656,7 @@ class Reviewer:Gate results:{chr(10).join(gate_lines)}Gate verdict: {gate_verdict}- {constraint}{familiarity_block}{self_driving_block}+ {constraint}{invocation_block}{familiarity_block}{self_driving_block}The full diff is at: {diff_path}Read this file to review the changes, then submit your verdict.@@ -760,6 +771,19 @@ class Reviewer:)return "\n" + line+ def _format_invocation(self, cl: dict) -> str:+ """The TRUSTED line naming why stamphog was asked to look at this PR, or "" when unknown.++ Data, not instruction. It states what happened and never what to conclude, because what a+ person asked for is not evidence about the diff. What it does carry is intent: in request+ mode somebody wanted a verdict on this PR, and in automatic mode the review reaches work+ nobody offered up, so an unfinished-looking PR means different things in the two.++ Empty for a local run, which keeps that prompt byte-identical to before this existed.+ """+ line = _INVOCATION_LINES.get(cl.get("review_trigger") or "")+ return f"\n{line}" if line else ""+def _format_self_driving(self, cl: dict) -> str:"""The TRUSTED provenance block for a self-driving inbox review, or "" for every other review.diff --git a/products/stamphog/packages/pr-approval-agent/test_reviewer.py b/products/stamphog/packages/pr-approval-agent/test_reviewer.pyindex 779029cb87e2..31edb14900b7 100644--- a/products/stamphog/packages/pr-approval-agent/test_reviewer.py+++ b/products/stamphog/packages/pr-approval-agent/test_reviewer.py@@ -297,6 +297,60 @@ def test_format_ownership_individual_only(ownership: dict, summary: str, expecteassert "NOT on the owning team" not in out+ "trigger, expected",+ [+ ("label", "this repo reviews on request only"),+ ("all", "this repo reviews every pull request automatically"),+ ("self_driving", "dispatched from a self-driving Inbox implementation run"),+ ],+)+def test_prompt_states_why_the_review_was_asked_for(trigger: str, expected: str) -> None:+ # A requested review and an automatic one used to reach the reviewer identically, so it could+ # not tell whether anyone wanted a verdict on this PR. The line is TRUSTED context, so it has to+ # sit above the untrusted PR content where an author cannot forge or contradict it.+ reviewer = Reviewer(Path("."))+ cl = {+ "tier": "T1-agent",+ "t1_subclass": "",+ "breadth": "narrow",+ "commit_type": "fix",+ "familiarity": None,+ "ownership": {},+ "assurance": None,+ "review_trigger": trigger,+ }+ prompt = reviewer._build_review_prompt(_pr(), cl, {"gate_verdict": "PENDING", "gates": []}, Path("/tmp/d.patch"))++ assert expected in prompt+ # rindex: the anti-injection notice at the top quotes the marker text, so the real delimiter is+ # the last occurrence.+ assert prompt.index("Invocation:") < prompt.rindex("--- BEGIN UNTRUSTED CONTENT ---")+++def test_prompt_omits_the_invocation_line_without_a_trigger() -> None:+ # A local review_pr.py run has no trigger to report, and its prompt must stay byte-identical to+ # what it was before the hosted runtime started sending one.+ reviewer = Reviewer(Path("."))+ base = {+ "tier": "T1-agent",+ "t1_subclass": "",+ "breadth": "narrow",+ "commit_type": "fix",+ "familiarity": None,+ "ownership": {},+ "assurance": None,+ }++ def prompt_with(cl_extra: dict) -> str:+ return reviewer._build_review_prompt(+ _pr(), {**base, **cl_extra}, {"gate_verdict": "PENDING", "gates": []}, Path("/tmp/d.patch")+ )++ assert prompt_with({}) == prompt_with({"review_trigger": ""})+ assert "Invocation:" not in prompt_with({})++def test_prompt_provenance_renders_only_for_self_driving_runs() -> None:# The Action never sets the flag, so its prompts must stay byte-identical (absent and False both# render nothing); a self-driving run gets the TRUSTED provenance block that replaces the