: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(stamphog): hard-gate bot-authored PRs (#63951)
Julian Bez66ef7bf4456c
diff --git a/.github/workflows/pr-approval-agent.yml b/.github/workflows/pr-approval-agent.ymlindex ede57a1dd582..d3c246c4cdc1 100644--- a/.github/workflows/pr-approval-agent.yml+++ b/.github/workflows/pr-approval-agent.yml@@ -15,7 +15,9 @@ concurrency:jobs:review:# Write access is required to apply the stamphog label, so no- # additional author_association check is needed.+ # additional author_association check is needed. Bot-authored PRs are+ # hard-excluded regardless of who applies the label — see the+ # bot-author-skip job, which strips the label and explains why.# Triggers: explicit `stamphog` label, ready_for_review with the# label already present, or `synchronize` where decide-delta# asked for re-review (or itself failed — fail closed for safety).@@ -23,6 +25,9 @@ jobs:if: >-always()&& !github.event.pull_request.draft+ && github.event.pull_request.user.type != 'Bot'+ && !contains(github.event.pull_request.user.login, '[bot]')+ && github.event.pull_request.user.login != 'posthog-bot'&& (github.event.label.name == 'stamphog'|| (github.event.action == 'ready_for_review' && contains(github.event.pull_request.labels.*.name, 'stamphog'))@@ -147,6 +152,9 @@ jobs:if: >-github.event.action == 'synchronize'&& !github.event.pull_request.draft+ && github.event.pull_request.user.type != 'Bot'+ && !contains(github.event.pull_request.user.login, '[bot]')+ && github.event.pull_request.user.login != 'posthog-bot'&& contains(github.event.pull_request.labels.*.name, 'stamphog')runs-on: ubuntu-latesttimeout-minutes: 5@@ -224,6 +232,12 @@ jobs:# Explicit synchronize + draft gates stop spurious dismissal on# labeled / ready_for_review events where decide-delta's result is# also 'skipped'.+ # Bot authors are deliberately NOT excluded here: a bot-authored PR may+ # still carry a stale github-actions[bot] approval from before the+ # bot-author gate landed, and it must get dismissed on push. decide-delta+ # is skipped for bots, which routes here via the 'skipped' fail-closed+ # path. This only ever touches github-actions[bot] approvals, so it's a+ # no-op when there's nothing to dismiss.if: >-always()&& github.event.action == 'synchronize'@@ -260,3 +274,52 @@ jobs:-f message="New commits pushed (delta classified \`$REASON\`) — stamphog approval dismissed; re-review running automatically." \-f event=DISMISSdone++ # stamphog never reviews bot-authored PRs (dependabot, mendral, other+ # agents). A human applying the label can't override this — bot output+ # isn't a trusted basis for an auto-approval. review / decide-delta are+ # gated to skip bot authors; this job runs instead to strip the label so+ # it never lingers. Same bot definition as those job gates, and as the+ # review script's defense-in-depth REFUSE.+ # Fires on labeled / ready_for_review (the apply paths — comment + strip)+ # and on synchronize when the label is still present (a leftover from before+ # this gate landed, or a failed earlier strip — clean it up, no comment).+ bot-author-skip:+ if: >-+ !github.event.pull_request.draft+ && (+ github.event.pull_request.user.type == 'Bot'+ || contains(github.event.pull_request.user.login, '[bot]')+ || github.event.pull_request.user.login == 'posthog-bot'+ )+ && (+ github.event.label.name == 'stamphog'+ || (github.event.action != 'labeled' && contains(github.event.pull_request.labels.*.name, 'stamphog'))+ )+ runs-on: ubuntu-latest+ timeout-minutes: 5++ steps:+ - name: Get app token+ id: app-token+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1+ with:+ client-id: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_APP_ID }}+ private-key: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_PRIVATE_KEY }}++ - name: Comment and strip label+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ PR: ${{ github.event.pull_request.number }}+ REPO: ${{ github.repository }}+ ACTION: ${{ github.event.action }}+ run: |+ set -euo pipefail+ # Explain only on the apply paths (a human just labeled it, or+ # marked the PR ready). On synchronize the note was already+ # posted — or the label predates this gate — so just clean up.+ if [ "$ACTION" != "synchronize" ]; then+ gh pr comment "$PR" --repo "$REPO" \+ --body "stamphog does not review bot-authored PRs — removing the \`stamphog\` label. This change needs a human reviewer."+ fi+ gh pr edit "$PR" --repo "$REPO" --remove-label stamphogdiff --git a/tools/pr-approval-agent/github.py b/tools/pr-approval-agent/github.pyindex 2a8adeb199f7..257d508be1b5 100644--- a/tools/pr-approval-agent/github.py+++ b/tools/pr-approval-agent/github.py@@ -29,6 +29,7 @@ class PRData:reviews: list[dict]review_comments: list[dict]check_runs: list[dict]+ author_is_bot: bool = False@propertydef file_paths(self) -> list[str]:@@ -53,6 +54,23 @@ class PRData:_TRUSTED_ASSOCIATIONS = {"MEMBER", "OWNER", "COLLABORATOR"}+# Machine users that are real org members (type "User") but should still be+# treated as bots. GitHub Apps already report type "Bot" and aren't listed here.+_BOT_MACHINE_USERS = {"posthog-bot"}+++def is_bot_author(user: dict) -> bool:+ """True when the PR author is a bot or machine account.++ GitHub Apps (dependabot, mendral, other agents) report user.type == "Bot";+ machine users like posthog-bot are type "User", so match them by login.+ Mirrors the bot definition gating the jobs in pr-approval-agent.yml.+ """+ if user.get("type") == "Bot":+ return True+ login = (user.get("login") or "").lower()+ return "[bot]" in login or login in _BOT_MACHINE_USERS+def _normalize_reviews_for_prompt(reviews_raw: list[dict], head_sha: str) -> list[dict]:"""Normalize top-level reviews for the reviewer prompt.@@ -280,6 +298,7 @@ def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRDatareviews=_normalize_reviews_for_prompt(reviews_raw, head_sha),review_comments=review_comments,check_runs=check_runs_resp.get("check_runs", []),+ author_is_bot=is_bot_author(pr.get("user", {})),)diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.pyindex 78b442ef3019..e03e52465848 100644--- a/tools/pr-approval-agent/review_pr.py+++ b/tools/pr-approval-agent/review_pr.py@@ -142,6 +142,10 @@ class Pipeline:def run(self) -> str:"""Run the full pipeline, return final verdict string."""self._fetch()++ if self.pr.author_is_bot:+ return self._refuse_bot_author()+self._classify()self._run_gates()@@ -171,6 +175,28 @@ class Pipeline:return Falsereturn migration_check_pending(self.pr.check_runs, self.pr.file_paths)+ def _refuse_bot_author(self) -> str:+ """Hard gate: stamphog never reviews bot-authored PRs.++ A human applying the stamphog label can't override this — bot output+ isn't a trusted basis for an auto-approval. The workflow already gates+ the review job on a non-bot author; this is the defense-in-depth layer+ for any manual or out-of-band invocation.+ """+ self.final_verdict = "REFUSED"+ self.reviewer_output = {+ "verdict": "REFUSE",+ "reasoning": (+ f"@{self.pr.author} is a bot — stamphog does not review "+ "bot-authored PRs. This change needs a human reviewer."+ ),+ "risk": "unknown",+ "issues": [],+ }+ print(f"\n{_fail('REFUSED')} — bot author (@{self.pr.author}); stamphog skips bot-authored PRs")+ self._capture_review_completed("DENIED", "BOT-AUTHOR")+ return self.final_verdict+def _refuse_pending_migration_check(self) -> str:self.final_verdict = "REFUSED"self.reviewer_output = {@@ -497,11 +523,14 @@ class Pipeline:"author": self.pr.author,"head_sha": self.pr.head_sha,"classification": {- "tier": self.classification["tier"],+ # .get() not [] — the bot-author REFUSE returns before _classify(),+ # so classification is empty {} on that path; --output-json must+ # still serialize cleanly rather than KeyError.+ "tier": self.classification.get("tier", ""),"t1_subclass": self.classification.get("t1_subclass", ""),"lines_total": self.pr.lines_total,"files_changed": len(self.pr.files),- "breadth": self.classification["breadth"],+ "breadth": self.classification.get("breadth", ""),"commit_type": self.classification.get("commit_type"),"deny_categories": self.classification.get("deny_categories", []),"safe_migration_files": self.classification.get("safe_migration_files", []),diff --git a/tools/pr-approval-agent/test_github.py b/tools/pr-approval-agent/test_github.pyindex 87aaa5a4617b..10dafbed805c 100644--- a/tools/pr-approval-agent/test_github.py+++ b/tools/pr-approval-agent/test_github.py@@ -2,7 +2,7 @@import pytest-from github import _normalize_reviews_for_prompt+from github import _normalize_reviews_for_prompt, is_bot_authordef test_normalize_reviews_marks_current_head_and_preserves_stale_reviews() -> None:@@ -75,3 +75,19 @@ def test_normalize_reviews_filters_by_trust_source()assert len(normalized) == expected_count+++ "user,expected",+ [+ pytest.param({"login": "mendral-app[bot]", "type": "Bot"}, True, id="github-app-type"),+ pytest.param({"login": "dependabot[bot]", "type": "Bot"}, True, id="dependabot"),+ pytest.param({"login": "some-tool[bot]", "type": "User"}, True, id="bot-suffix-misreported-type"),+ pytest.param({"login": "posthog-bot", "type": "User"}, True, id="machine-user"),+ pytest.param({"login": "POSTHOG-BOT", "type": "User"}, True, id="machine-user-case-insensitive"),+ pytest.param({"login": "alice", "type": "User"}, False, id="human"),+ pytest.param({}, False, id="missing-user"),+ ],+)+def test_is_bot_author(user: dict, expected: bool) -> None:+ assert is_bot_author(user) is expecteddiff --git a/tools/pr-approval-agent/test_review_pr.py b/tools/pr-approval-agent/test_review_pr.pyindex 5374b6de296f..97953a872716 100644--- a/tools/pr-approval-agent/test_review_pr.py+++ b/tools/pr-approval-agent/test_review_pr.py@@ -143,3 +143,36 @@ def test_turn_limit_error_not_retried(monkeypatch: pytest.MonkeyPatch, gate_verd# Should NOT mention infrastructure/credentialsassert "infrastructure" not in pipeline.reviewer_output["reasoning"]assert "credentials" not in pipeline.reviewer_output["reasoning"]+++def test_bot_author_refuses_before_classification(monkeypatch: pytest.MonkeyPatch) -> None:+ """A bot-authored PR is hard-refused before any classification, gate, or+ LLM call — a human applying the stamphog label can't make the agent review+ bot output."""+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)++ bot_pr = _fake_pr(head_sha="abc123")+ bot_pr.author = "mendral-app[bot]"+ bot_pr.author_is_bot = True++ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")+ monkeypatch.setattr(pipeline, "_fetch", lambda: setattr(pipeline, "pr", bot_pr))++ def _fail_classify() -> None:+ raise AssertionError("bot PR must be refused before classification")++ monkeypatch.setattr(pipeline, "_classify", _fail_classify)++ verdict = pipeline.run()++ assert verdict == "REFUSED"+ assert pipeline.reviewer_output is not None+ assert pipeline.reviewer_output["verdict"] == "REFUSE"+ assert "bot" in pipeline.reviewer_output["reasoning"].lower()++ # The workflow always runs with --output-json, so to_dict() must serialize+ # cleanly even though classification was never populated on this path.+ output = pipeline.to_dict()+ assert output["final_verdict"] == "REFUSED"+ assert output["classification"]["tier"] == ""+ assert output["classification"]["breadth"] == ""