: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
fix(devex): put every stamphog verdict in the reviews list (#91457)
Julian Bezf235a39ba0e7
diff --git a/.agents/skills/merging-prs/SKILL.md b/.agents/skills/merging-prs/SKILL.mdindex 675615a7dda0..10494e725dc9 100644--- a/.agents/skills/merging-prs/SKILL.md+++ b/.agents/skills/merging-prs/SKILL.md@@ -35,7 +35,7 @@ gh pr view <n> --json state,isDraft,mergeable,reviewDecision,statusCheckRollup,b- **Draft** → it can't be merged. Ask the developer to confirm, then `gh pr ready <n>` before continuing. Don't un-draft silently.- **Failing required checks** (`statusCheckRollup`) → the queue will just reject it. Report which checks are red and stop; fix them first. **Pending** checks are fine — the queue waits for them. To work out _why_ a check is red, use `/debugging-ci-failures`.- **Merge conflicts** (`mergeable == "CONFLICTING"`) → report and stop; merge `master` in first.-- **Missing approval** (`reviewDecision == "REVIEW_REQUIRED"`, or a stamphog approval was dismissed) → apply the `stamphog` label yourself: `gh pr edit <n> --add-label stamphog`. That triggers the automated review-and-approve flow ([tools/pr-approval-agent/README.md](../../../tools/pr-approval-agent/README.md)); on an `APPROVED` verdict the Stamphog app posts the approval that satisfies the required review. Re-applying the label is always safe and is the intended retry path — it gets stripped on a `REFUSED`/`ESCALATE` verdict, and after addressing that feedback you re-apply it to request a fresh review. It stays sticky across ordinary pushes (non-trivial deltas re-review automatically), and it never works on bot-authored PRs.+- **Missing approval** (`reviewDecision == "REVIEW_REQUIRED"`, or a stamphog approval was dismissed) → apply the `stamphog` label yourself: `gh pr edit <n> --add-label stamphog`. That triggers the automated review-and-approve flow ([tools/pr-approval-agent/README.md](../../../tools/pr-approval-agent/README.md)); on an `APPROVED` verdict the Stamphog app posts the approval that satisfies the required review. Re-applying the label is always safe and is the intended retry path — it gets stripped on a `REFUSED`/`ESCALATE` verdict, and after addressing that feedback you re-apply it to request a fresh review. Read the reason first: every verdict is its own review from the Stamphog app, opening with whether it approved. Re-applying the label without changing anything just repeats the same verdict. It stays sticky across ordinary pushes (non-trivial deltas re-review automatically), and it never works on bot-authored PRs.- **Part of a stack** (`baseRefName != "master"`, or the PR appears in `gh api repos/$REPO/stacks`) → the queue handles stacks natively: enqueueing a PR enqueues it **and every unmerged layer below it**, tests them together, and merges them atomically. After explicit user approval, comment `/trunk merge` on the **top** PR to merge the whole stack, or on the highest layer you want landed to merge just the bottom part. Run this preflight on every layer being merged, not only the one you comment on. `/stacking-prs` covers restack mechanics and the post-merge `gh stack sync --prune`.## 2. Enqueuediff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.pyindex 498856c8e614..c1267f3e6197 100644--- a/products/stamphog/backend/logic/github_client.py+++ b/products/stamphog/backend/logic/github_client.py@@ -1033,25 +1033,41 @@ class StamphogGitHubClient:# --- Write operations ---- def post_approve_review(self, repo: str, number: int, body: str, commit_id: str) -> dict:- """Submit an APPROVE review pinned to ``commit_id`` (``POST .../pulls/{number}/reviews``).+ def _submit_review(self, repo: str, number: int, body: str, commit_id: str, event: str) -> dict:+ """Submit one review pinned to ``commit_id`` (``POST .../pulls/{number}/reviews``).- Pinning to the reviewed head SHA means an approval never silently carries over to commits pushed- after the review. Raises on any non-success so a failed approval is never mistaken for a success.+ Pinning to the reviewed head SHA means a review never silently carries over to commits pushed+ after it. Raises on any non-success so a failed write is never mistaken for a success."""path = f"/repos/{repo}/pulls/{number}/reviews"response = self._request("POST",path,endpoint="/repos/{owner}/{repo}/pulls/{pull_number}/reviews",- json_body={"event": "APPROVE", "body": body, "commit_id": commit_id},+ json_body={"event": event, "body": body, "commit_id": commit_id},)if response.status_code not in (200, 201):raise StamphogGitHubError(- f"Failed to approve PR {repo}#{number}: {response.text[:300]}", status_code=response.status_code+ f"Failed to submit {event} review on {repo}#{number}: {response.text[:300]}",+ status_code=response.status_code,)return self._json(response, path)+ def post_approve_review(self, repo: str, number: int, body: str, commit_id: str) -> dict:+ """Submit an APPROVE review — the one that satisfies a required review."""+ return self._submit_review(repo, number, body, commit_id, "APPROVE")++ def post_comment_review(self, repo: str, number: int, body: str, commit_id: str) -> dict:+ """Submit a COMMENT review — stamphog declining to approve, without blocking the PR.++ Every verdict lands in the same place this way: the Reviews section, dated, notifying, and+ pinned to the head it judged. An issue comment would sit in a different list from the+ approvals it contradicts, which is how a stale refusal came to outlive the approval that+ replaced it. REQUEST_CHANGES would be the wrong event — stamphog declining to auto-approve+ must not block a human from merging.+ """+ return self._submit_review(repo, number, body, commit_id, "COMMENT")+def remove_pr_label(self, repo: str, number: int, label: str) -> None:"""Remove a label from a PR (``DELETE .../issues/{number}/labels/{label}``).diff --git a/products/stamphog/backend/models.py b/products/stamphog/backend/models.pyindex 4494482a6f08..229d0b33b5f7 100644--- a/products/stamphog/backend/models.py+++ b/products/stamphog/backend/models.py@@ -116,7 +116,9 @@ class PullRequest(ProductTeamModel):# when the engine predates the field; the digest falls back to the PR title.summary_line = models.CharField(max_length=200, blank=True, default="")digest_run = models.ForeignKey("DigestRun", on_delete=models.SET_NULL, null=True, related_name="pull_requests")- # The sticky comment is a PR-level artifact, upserted per PR across review runs.+ # Historical: the sticky comment a verdict used to be written into. Verdicts are reviews now, so+ # nothing writes this any more — it holds the last comment id from before that change. Kept+ # because it is on the facade contract; drop both together.posted_comment_id = models.BigIntegerField(null=True)# The PR's own pull_request.updated_at from the last payload we applied. GitHub can redeliver or# fan out an older snapshot after a newer one; this field is the monotonic clock that lets the taskdiff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.pyindex 34fe1b74ca6b..a70b7536148a 100644--- a/products/stamphog/backend/temporal/activities.py+++ b/products/stamphog/backend/temporal/activities.py@@ -765,12 +765,16 @@ def post_verdict(input: StamphogReviewInput) -> dict:activity.logger.info(f"Skipping verdict for run {run.id}: superseded during posting")return {"verdict": "skipped_superseded"}+ # Computed before the branch chain because two things must agree on it: the trigger label is only+ # stripped for a refusal, and only then may the review tell the author to re-add it.+ is_refusal = parsed.verdict in (ReviewVerdict.REFUSED, ReviewVerdict.ESCALATE)+ strips_label = repo_config.review_mode == ReviewMode.LABEL and is_refusal++ relabel_label = repo_config.trigger_label if strips_label else None+if parsed.gate_blocked:# The deterministic gates denied auto-review — a terminal, non-approval# outcome. The engine still rendered a plain-language explanation; post it.- _post_sticky(- client, repo, pull_request, _neutralize_active_markdown(parsed.review_body or _verdict_comment(parsed))- )run.status = ReviewRunStatus.GATEDrun.verdict = ReviewVerdict.WAITelif parsed.verdict == ReviewVerdict.APPROVED:@@ -794,7 +798,7 @@ def post_verdict(input: StamphogReviewInput) -> dict:if adopted_review_id is not None:run.posted_review_id = adopted_review_idelse:- body = _neutralize_active_markdown(_scrub_credentials(parsed.review_body or _approve_comment(parsed)))+ body = _scrub_credentials(_verdict_body(parsed, ReviewVerdict.APPROVED, relabel_label))review = client.post_approve_review(repo, pull_request.pr_number, body, run.head_sha)run.posted_review_id = _comment_id(review)# Persist the id immediately, outside the conditional terminal save below: if that save@@ -808,16 +812,19 @@ def post_verdict(input: StamphogReviewInput) -> dict:run.verdict = ReviewVerdict.APPROVEDupdate_fields.append("posted_review_id")else:- _post_sticky(- client, repo, pull_request, _neutralize_active_markdown(parsed.review_body or _verdict_comment(parsed))- )run.status = ReviewRunStatus.COMPLETEDrun.verdict = parsed.verdict+ # One post for every non-approval, keyed off the verdict the run just stored, so the review text+ # and the recorded verdict cannot disagree. The approve branch above posted its own APPROVE.+ if run.verdict != ReviewVerdict.APPROVED:+ _post_non_approval_review(+ client, repo, run, pull_request, input.team_id, _verdict_body(parsed, run.verdict, relabel_label)+ )+# Keyed off parsed.verdict, not run.verdict: the gate-blocked branch overrides run.verdict to WAIT,# but both the label-strip and the ReviewHog handoff below treat a gate-blocked refusal the same# as an engine-refused one.- is_refusal = parsed.verdict in (ReviewVerdict.REFUSED, ReviewVerdict.ESCALATE)# Same reading the reviewer got, from the same stamp, so the handoff can't disagree with what# the run was told it was.trigger = trigger_for_run(output=output, review_mode=repo_config.review_mode)@@ -825,7 +832,7 @@ def post_verdict(input: StamphogReviewInput) -> dict:# Action parity: in label-triggered mode a refused/escalated verdict strips the trigger label, so# the author re-requests the next review by re-adding it.# A failure here raises on purpose: the activity retries and the sticky upsert above is idempotent.- if repo_config.review_mode == ReviewMode.LABEL and is_refusal:+ if strips_label:client.remove_pr_label(repo, pull_request.pr_number, repo_config.trigger_label)run.completed_at = timezone.now()@@ -1264,15 +1271,27 @@ def _stamp_digest_audience_if_merged()-def _post_sticky(client: StamphogGitHubClient, repo: str, pull_request: PullRequest, body: str) -> None:- """Upsert the sticky comment and persist its id on the PR. Body is scrubbed before posting.+# The review this run posted when it did not approve. Kept out of ``posted_review_id``, which means+# "the APPROVE review this run posted" and drives the retraction sweep — a COMMENT review is not+# dismissable, so listing one there would break it. Nothing queries this, so it stays in ``output``.+NON_APPROVAL_REVIEW_ID_KEY = "non_approval_review_id"+- Idempotent on retry: ``upsert_sticky_comment`` edits the existing comment (tracked via- ``posted_comment_id``) rather than adding a new one, so a re-run does not double-post.+def _post_non_approval_review(+ client: StamphogGitHubClient, repo: str, run: ReviewRun, pull_request: PullRequest, team_id: int, body: str+) -> None:+ """Record a non-approval as its own COMMENT review, and remember it so a retry does not repeat it.++ Same surface as the approval, so the two cannot end up in separate lists disagreeing about the+ same head. Idempotency mirrors the approve path: the id is persisted the moment GitHub accepts+ the review, outside the caller's conditional terminal save, so a crash after this point cannot+ post twice."""- comment = client.upsert_sticky_comment(repo, pull_request.pr_number, _scrub_credentials(body))- pull_request.posted_comment_id = _comment_id(comment)- pull_request.save(update_fields=["posted_comment_id", "updated_at"])+ if (run.output or {}).get(NON_APPROVAL_REVIEW_ID_KEY) is not None:+ return+ review = client.post_comment_review(repo, pull_request.pr_number, _scrub_credentials(body), run.head_sha)+ run.output = {**(run.output or {}), NON_APPROVAL_REVIEW_ID_KEY: _comment_id(review)}+ ReviewRun.objects.for_team(team_id).filter(id=run.id).update(output=run.output, updated_at=timezone.now())def _comment_id(obj: dict) -> int | None:@@ -1281,12 +1300,36 @@ def _comment_id(obj: dict) -> int | None:return value if isinstance(value, int) else None-def _approve_comment(parsed: ReviewerVerdict) -> str:- return parsed.reasoning or "Looks good."+# What each verdict means for the author, in the words they need to act on. The engine renders its+# reasoning and a gate table, but never states the outcome, and every gate row reads "✓" even on a+# refusal — so without this line a reader cannot tell an approval from a denial.+_VERDICT_HEADLINES: dict[str, str] = {+ ReviewVerdict.APPROVED: "**Approved.**",+ ReviewVerdict.REFUSED: "**Not approved — this change needs a human reviewer.**",+ ReviewVerdict.ESCALATE: "**Not approved — escalated to a human reviewer.**",+ ReviewVerdict.WAIT: "**Not approved yet — waiting on the conditions below.**",+}+++def _verdict_body(parsed: ReviewerVerdict, verdict: str, relabel_label: str | None) -> str:+ """The review body: the outcome in words, what to do next, then whatever the engine rendered.++ ``relabel_label`` is the caller's own label-removal decision rather than a re-derivation of it, so+ the review cannot tell an author to re-add a label the run left in place.++ The engine's ``review_body`` is the rich version (reasoning plus the gate table) and the+ ``reasoning``/``showstoppers`` pair is the fallback when it rendered nothing. The headline is+ prepended to both, so the outcome is stated whichever one is available.+ """+ headline = _VERDICT_HEADLINES.get(verdict, f"**Stamphog review: {verdict}**")+ if relabel_label:+ headline += f"\n\nRe-add the `{relabel_label}` label to request another review once you have addressed this."+ detail = parsed.review_body or _reasoning_detail(parsed)+ return f"{headline}\n\n{_neutralize_active_markdown(detail)}".rstrip()-def _verdict_comment(parsed: ReviewerVerdict) -> str:- body = f"**Stamphog review: {parsed.verdict}**\n\n{parsed.reasoning}".rstrip()+def _reasoning_detail(parsed: ReviewerVerdict) -> str:+ body = parsed.reasoningif parsed.showstoppers:body += "\n\n**Showstoppers:**\n" + "\n".join(f"- {item}" for item in parsed.showstoppers)- return body+ return body.strip()diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.pyindex cf93d7a81cd5..af2f61a1cc34 100644--- a/products/stamphog/backend/tests/fakes.py+++ b/products/stamphog/backend/tests/fakes.py@@ -208,7 +208,10 @@ class GitHubRecorder:if method == "GET" and (m := _REVIEWS_RE.match(path)):return FakeResponse(200, json_data=self.pr_reviews.get((m.group("repo"), int(m.group("number"))), []))if method == "POST" and (m := _REVIEWS_RE.match(path)):- return self._record_write("approve_review", m.group("repo"), int(m.group("number")), json_body)+ # Split by event so a test asserting on approvals never matches a COMMENT review.+ event = (json_body or {}).get("event")+ kind = "approve_review" if event == "APPROVE" else "comment_review"+ return self._record_write(kind, m.group("repo"), int(m.group("number")), json_body)if method == "GET" and (m := _ISSUE_COMMENTS_RE.match(path)):page = int(params.get("page", 1))comments = self.issue_comments.get((m.group("repo"), int(m.group("number"))), []) if page == 1 else []diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.pyindex b04ba4ac0654..1a47647300b0 100644--- a/products/stamphog/backend/tests/test_integration.py+++ b/products/stamphog/backend/tests/test_integration.py@@ -30,7 +30,7 @@ from products.stamphog.backend.logic.channel_resolution import (build_routing_context,resolve_destination,)-from products.stamphog.backend.logic.github_client import STICKY_COMMENT_MARKER+from products.stamphog.backend.logic.github_client import STICKY_COMMENT_MARKER, StamphogGitHubClientfrom 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@@ -833,7 +833,7 @@ def test_reviewer_markdown_images_are_neutralized_before_posting(team, stamphog_assert body.count("[image removed]") == 2assert "![" not in body # reference-style images are demoted to plain links (never auto-fetched)assert "[x][leak]" in body- assert body.startswith("Looks fine.") and body.endswith("end.")+ assert "Looks fine. [image removed]" in body and body.endswith("end.")@pytest.mark.django_db(databases=PRODUCT_DATABASES)@@ -1258,17 +1258,17 @@ def test_superseded_refusal_does_not_hand_off_to_reviewhog(team, stamphog_chain:status=ReviewRunStatus.REVIEWING,output={"reviewer_raw": _refused_engine_output(), "inbox_review": {"trigger": "inbox"}},)- # A concurrent delivery flips the run to SUPERSEDED during the sticky-comment post (before the+ # A concurrent delivery flips the run to SUPERSEDED during the non-approval review post (before the# terminal save), so the conditional .exclude(status=SUPERSEDED).update(...) matches nothing and the# run returns skipped_superseded. This reaches the terminal-save early return, NOT the top guard —# the run is REVIEWING at load.- original_post_sticky = activities._post_sticky+ original_post_review = activities._post_non_approval_review- def _supersede_then_post(client, repo, pr, body) -> None:+ def _supersede_then_post(client, repo, posting_run, pr, team_id, body) -> None:ReviewRun.objects.for_team(team.id).filter(id=run.id).update(status=ReviewRunStatus.SUPERSEDED)- original_post_sticky(client, repo, pr, body)+ original_post_review(client, repo, posting_run, pr, team_id, body)- with patch.object(activities, "_post_sticky", side_effect=_supersede_then_post):+ with patch.object(activities, "_post_non_approval_review", side_effect=_supersede_then_post):result = _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))assert result == {"verdict": "skipped_superseded"}@@ -1649,6 +1649,47 @@ def test_post_verdict_stamps_digest_audience_only_at_approved_head(assert pull_request.summary_line == run.change_summary[email protected]_db(databases=PRODUCT_DATABASES)+def test_each_non_approval_posts_its_own_review(team, stamphog_chain: StamphogChain) -> None:+ # Every verdict has to land in the Reviews section, the same list the approvals land in. A refusal+ # written into an edited issue comment notified nobody and sat in a different list from the+ # approval that later replaced it, so a stale refusal outlived the approval it contradicted. Each+ # run posts its own review, pinned to the head it judged, saying the outcome in words — the+ # engine's own body never does, and renders every gate row as a tick even on a refusal.+ repo_config = _repo_config(team.id)+ repo_config.review_mode = ReviewMode.LABEL+ repo_config.save()+ head_sha = "sha-refused"+ stamphog_chain.recorder.register_pr(REPO, 101, _pr_object(101, "devex-dev", head_sha))+ pull_request = PullRequest.objects.for_team(team.id).create(+ team_id=team.id, repo_config=repo_config, pr_number=101, author_login="devex-dev"+ )++ for _ in range(2):+ 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": _refused_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))++ writes = stamphog_chain.recorder.github_writes+ assert [w for w in writes if w["kind"] in ("issue_comment", "issue_comment_edit")] == []+ reviews = [w for w in writes if w["kind"] == "comment_review"]+ assert len(reviews) == 2+ for review in reviews:+ # COMMENT, never REQUEST_CHANGES: declining to auto-approve must not block a human merging.+ assert review["body"]["event"] == "COMMENT"+ assert review["body"]["commit_id"] == head_sha+ assert review["body"]["body"].startswith("**Not approved")+ # LABEL mode strips the trigger label, so the review has to say how to ask again.+ assert "Re-add the `stamphog` label" in review["body"]["body"]++@pytest.mark.parametrize("comment_user_type,expect_patch",[("User", False), ("Bot", True)],@@ -1656,14 +1697,12 @@ def test_post_verdict_stamps_digest_audience_only_at_approved_head()@pytest.mark.django_db(databases=PRODUCT_DATABASES)def test_sticky_comment_only_edits_the_apps_own_comment(- team, stamphog_chain: StamphogChain, comment_user_type: str, expect_patch: bool+ stamphog_chain: StamphogChain, comment_user_type: str, expect_patch: bool) -> None:# The sticky marker is visible in the comment source, so a user could plant it to make the bot PATCH# (hijack) their comment. Only a Bot-authored comment carrying the marker may be edited; a user's is# ignored and a fresh comment is posted. (App slug is unset in tests, so any Bot author qualifies.)- repo_config = _repo_config(team.id)- head_sha = "sha-refused"- stamphog_chain.recorder.register_pr(REPO, 101, _pr_object(101, "devex-dev", head_sha))+ # Verdicts no longer upsert, so the remaining caller is the bot-author label cleanup.stamphog_chain.recorder.issue_comments[(REPO, 101)] = [{"id": 4242,@@ -1671,18 +1710,8 @@ def test_sticky_comment_only_edits_the_apps_own_comment("user": {"login": "someone", "type": comment_user_type},}]- pull_request = PullRequest.objects.for_team(team.id).create(- team_id=team.id, repo_config=repo_config, pr_number=101, 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,- output={"reviewer_raw": _refused_engine_output()},- )- _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))+ StamphogGitHubClient(INSTALLATION_ID).upsert_sticky_comment(REPO, 101, "status")writes = stamphog_chain.recorder.github_writespatched = [w for w in writes if w["kind"] == "issue_comment_edit"]