: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
chore(stamphog): let devex self-approve CI workflows (#113532)
Raúl Negrón-Oterocf837e7b34eb
diff --git a/.stamphog/README.md b/.stamphog/README.mdindex f8e1aebeaa19..2feab7f9b1de 100644--- a/.stamphog/README.md+++ b/.stamphog/README.md@@ -11,7 +11,8 @@ What each file contains and how per-folder overrides resolve: [the engine's "PolIt overrides `deny` and `allow`, and the differences are:- `auth` and `billing` exempt `products/warehouse_sources/backend/temporal/data_imports/sources/`, because connector code does OAuth and talks to the Stripe API without touching PostHog's auth system or its billing.-- `infra_cicd` also matches `.github/pr-deploy`.+- `infra_cicd` also matches `.github/pr-deploy`. Of the workflows, it keeps only the ones that CODEOWNERS assigns to `team-security`, so those stay denied for every author.+- `ci_workflows` is an extra, owner-only category. It matches every file under `.github/workflows/` and `.depot/workflows/`, and its `exempt_author_teams` lets stamphog approve there only for authors on `team-devex`.- `stamphog_policy` also matches `products/stamphog/backend/logic/policy_defaults/`, `packages/owners-yaml/`, `owners.yaml` and `product.yaml`, because those are gate inputs here.- `devex_guardrails` is an extra category. It matches the semgrep rules, ratchet baselines, invariant tests and lint code that guard the house patterns, so an edit to a guard always gets a human review.- `workflows_delivery` is an extra, owner-only category. It matches the CDP, Workflows and Messaging API, models and plugin-server worker code, and its `exempt_author_teams` lets stamphog approve there only for authors on `team-workflows`.diff --git a/.stamphog/policy.yml b/.stamphog/policy.ymlindex 1da4a55efb13..0e4108dd0492 100644--- a/.stamphog/policy.yml+++ b/.stamphog/policy.yml@@ -72,8 +72,7 @@ deny:- 'k8s'- 'dockerfile'- 'docker-compose'- - '\.github/workflows'- - '\.depot/workflows'+ - '\.(github|depot)/workflows/(ci-security|codeql|auto-assign-reviewers)'- '\.github/pr-deploy'- 'iam'- 'cloudflare'@@ -81,6 +80,15 @@ deny:- 'waf'- '(?:^|/)bin/deploy'- 'deploy\.sh'+ ci_workflows:+ description: 'GitHub Actions and Depot CI workflows.'+ rationale: 'Owner-only: stamphog approves team-devex changes here and refuses everyone else. team-devex owns the workflows in .github/owners.yaml and edits them daily, so a hard deny sent every routine CI fix to a second devex engineer. infra_cicd also matches the workflows that CODEOWNERS assigns to team-security, and it exempts nobody, so those stay denied for every author.'+ match:+ paths:+ - '\.github/workflows'+ - '\.depot/workflows'+ exempt_author_teams:+ - 'team-devex'billing:description: 'Payments and billing.'rationale: 'subscription is excluded on purpose: in this repo it means scheduled insight/report deliveries, not payments. Real billing surfaces still match via the other words.'diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.pyindex 522700471511..a1480df79061 100644--- a/products/stamphog/backend/temporal/activities.py+++ b/products/stamphog/backend/temporal/activities.py@@ -2282,6 +2282,20 @@ _VERDICT_HEADLINES: dict[str, str] = {}+_PATH_DENY_GATES = frozenset({"deny-list", "tier"})+++def _only_a_human_can_approve(parsed: ReviewerVerdict) -> bool:+ """True when the changed paths alone refused the PR, so a re-review of the same files refuses again.++ A deny on migrations alone is excluded: it lifts once the `Migration risk` check passes.+ """+ gates = [g for g in parsed.gate_result.get("gates") or [] if isinstance(g, dict)]+ failed = {g.get("gate") for g in gates if not g.get("passed", True)}+ deny_categories = (parsed.gate_result.get("classification") or {}).get("deny_categories") or []+ return bool(failed) and failed <= _PATH_DENY_GATES and deny_categories != ["migrations"]++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.@@ -2293,7 +2307,13 @@ def _verdict_body(parsed: ReviewerVerdict, verdict: str, relabel_label: str | Noprepended to both, so the outcome is stated whichever one is available."""headline = _VERDICT_HEADLINES.get(verdict, f"**Stamphog review: {verdict}**")- if relabel_label:+ if _only_a_human_can_approve(parsed):+ headline = _VERDICT_HEADLINES[ReviewVerdict.REFUSED]+ if relabel_label:+ headline += (+ f"\n\nRe-adding the `{relabel_label}` label gives the same result unless the changed files change."+ )+ elif 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()diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.pyindex a06b0f24109a..b8ff63e4df86 100644--- a/products/stamphog/backend/tests/test_integration.py+++ b/products/stamphog/backend/tests/test_integration.py@@ -2306,8 +2306,34 @@ def test_post_verdict_stamps_digest_audience_only_at_approved_head(assert pull_request.summary_line == run.change_summary+def _path_denied_engine_output(deny_categories: list[str]) -> str:+ payload = {+ "final_verdict": "REFUSED",+ "gates": [+ {"gate": "size", "passed": True, "message": "within ceiling"},+ {"gate": "deny-list", "passed": False, "message": "matches: infra_cicd"},+ {"gate": "tier", "passed": False, "message": "classified as T2-never"},+ ],+ "classification": {"deny_categories": deny_categories},+ "review_body": "Refused by stamphog.",+ }+ return json.dumps(payload)+++ "engine_output, expect_hint",+ [+ pytest.param(_refused_engine_output(), "Re-add the `stamphog` label", id="reviewer-refusal"),+ # A re-review of the same files refuses again, so the review must not invite one.+ pytest.param(_path_denied_engine_output(["infra_cicd", "migrations"]), "gives the same result", id="path-deny"),+ # The Migration risk check lifts this deny with the files unchanged.+ pytest.param(_path_denied_engine_output(["migrations"]), "Re-add the `stamphog` label", id="migrations-only"),+ ],+)@pytest.mark.django_db(databases=PRODUCT_DATABASES)-def test_each_non_approval_posts_its_own_review(team, stamphog_chain: StamphogChain) -> None:+def test_each_non_approval_posts_its_own_review(+ team, stamphog_chain: StamphogChain, engine_output: str, expect_hint: str+) -> 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@@ -2328,7 +2354,7 @@ def test_each_non_approval_posts_its_own_review(team, stamphog_chain: StamphogChpull_request=pull_request,head_sha=head_sha,status=ReviewRunStatus.REVIEWING,- output={"reviewer_raw": _refused_engine_output()},+ 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))@@ -2344,7 +2370,7 @@ def test_each_non_approval_posts_its_own_review(team, stamphog_chain: StamphogChassert review["body"]["commit_id"] == head_shaassert 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"]+ assert expect_hint in review["body"]["body"]@pytest.mark.parametrize(diff --git a/products/stamphog/packages/pr-approval-agent/review_pr.py b/products/stamphog/packages/pr-approval-agent/review_pr.pyindex 1b32c0520641..1af670723dab 100644--- a/products/stamphog/packages/pr-approval-agent/review_pr.py+++ b/products/stamphog/packages/pr-approval-agent/review_pr.py@@ -447,11 +447,13 @@ class Pipeline:)if risky_manifests and "deps_toolchain" not in deny:deny = sorted([*deny, "deps_toolchain"])+ denied_before_exemptions = len(deny)deny = [categoryfor category in denyif not any(self._author_on_team(team) for team in DENY_EXEMPT_AUTHOR_TEAMS.get(category, ()))]+ owner_exempted = len(deny) < denied_before_exemptionstitle_flags = [cfor c in detect_title_scrutiny_flags(pr.title)@@ -463,8 +465,15 @@ class Pipeline:# Both checks matter: has_dependency_changes catches lockfile-paired# manifests, dependency_manifests_without_lockfile catches the rest# (tsconfig, setup.py/.cfg) that the reviewer's scripts guard covers.- allow_only = is_allow_listed_only(file_paths) and not has_dependency_changes(file_paths) and not dep_manifests- is_test = test_only(categories)+ # An owner-only exemption lifts the deny, not the review: a workflow is .yml,+ # so without this it rides the allow-list to a T0 approval with no reviewer.+ allow_only = (+ is_allow_listed_only(file_paths)+ and not has_dependency_changes(file_paths)+ and not dep_manifests+ and not owner_exempted+ )+ is_test = test_only(categories) and not owner_exemptedownership_resolvers = build_ownership(REPO_ROOT, POLICY.ownership)ownership = detect_ownership(file_paths, ownership_resolvers)diff --git a/products/stamphog/packages/pr-approval-agent/test_gates.py b/products/stamphog/packages/pr-approval-agent/test_gates.pyindex e12c62b8c2b8..3e2e850535ac 100644--- a/products/stamphog/packages/pr-approval-agent/test_gates.py+++ b/products/stamphog/packages/pr-approval-agent/test_gates.py@@ -201,9 +201,24 @@ def test_no_false_positive(files: list[str]) -> None:),pytest.param([".github/workflows/ci.yml"],- "infra_cicd",+ "ci_workflows",id="github-workflow",),+ pytest.param(+ [".depot/workflows/ci-backend.yml"],+ "ci_workflows",+ id="depot-workflow",+ ),+ pytest.param(+ [".github/workflows/ci-security.yaml"],+ "infra_cicd",+ id="security-owned-workflow",+ ),+ pytest.param(+ [".depot/workflows/ci-security.yaml"],+ "infra_cicd",+ id="security-owned-depot-workflow",+ ),pytest.param(["bin/deploy-hobby"],"infra_cicd",diff --git a/products/stamphog/packages/pr-approval-agent/test_policy.py b/products/stamphog/packages/pr-approval-agent/test_policy.pyindex 4d81ca64b383..91ed568aa055 100644--- a/products/stamphog/packages/pr-approval-agent/test_policy.py+++ b/products/stamphog/packages/pr-approval-agent/test_policy.py@@ -83,8 +83,7 @@ OLD_DENY_PATTERN_DEFS = {"k8s","dockerfile","docker-compose",- "\\.github/workflows",- "\\.depot/workflows",+ "\\.(github|depot)/workflows/(ci-security|codeql|auto-assign-reviewers)","\\.github/pr-deploy","iam","cloudflare",@@ -94,6 +93,12 @@ OLD_DENY_PATTERN_DEFS = {"deploy\\.sh",],},+ "ci_workflows": {+ "paths": [+ "\\.github/workflows",+ "\\.depot/workflows",+ ]+ },"billing": {"any": ["billing", "payment", "stripe", "invoice", "pricing"]},"public_api": {"any": ["openapi", "api_schema", "swagger", "public_api"]},"deps_toolchain": {diff --git a/products/stamphog/packages/pr-approval-agent/test_review_pr.py b/products/stamphog/packages/pr-approval-agent/test_review_pr.pyindex 51bd9716d37b..3af7c9ac592d 100644--- a/products/stamphog/packages/pr-approval-agent/test_review_pr.py+++ b/products/stamphog/packages/pr-approval-agent/test_review_pr.py@@ -334,6 +334,35 @@ def test_dep_manifest_pr_gets_t1_scrutiny_not_t0(monkeypatch: pytest.MonkeyPatchassert pipeline.classification["dep_manifests_without_lockfile"] == [manifest]+ "filename, touched_paths",+ [+ pytest.param(".github/workflows/ci-backend.yml", [], id="github-workflow"),+ pytest.param(".depot/workflows/ci-backend.yml", [], id="depot-workflow"),+ pytest.param("docs/ci-backend.yml", [".github/workflows/ci-backend.yml"], id="workflow-renamed-out"),+ pytest.param(".github/workflows/tests/test_ci.py", [], id="test-named-file-under-workflows"),+ ],+)+def test_exempt_author_workflow_pr_gets_t1_scrutiny_not_t0(+ monkeypatch: pytest.MonkeyPatch, filename: str, touched_paths: list[str]+) -> None:+ # A workflow is .yml, so once the owner-only exemption lifts the deny, the allow-list+ # would classify it T0 and approve it with no reviewer.+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)++ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")+ pipeline.author_team_slugs = {"team-devex"}+ pr = _fake_pr(head_sha="abc123")+ pr.files = [{"filename": filename, "additions": 2, "deletions": 1, "status": "M"}]+ pr.touched_paths = touched_paths+ pipeline.pr = pr++ pipeline._classify()++ assert pipeline.classification["deny_categories"] == []+ assert pipeline.classification["tier"] == "T1-agent"++def test_manifest_scripts_edit_hard_denies(monkeypatch: pytest.MonkeyPatch) -> None:# The deterministic scan is the first line against scripts/hook edits —# when it fires, the PR must land T2-never rather than the LLM-only path.@@ -450,7 +479,7 @@ def test_wait_refetch_reclassifies_before_review(monkeypatch: pytest.MonkeyPatchverdict = pipeline.run()assert verdict == "REFUSED"- assert pipeline.classification["deny_categories"] == ["infra_cicd"]+ assert pipeline.classification["deny_categories"] == ["ci_workflows"]class _FakeCompleted:diff --git a/products/stamphog/packages/pr-approval-agent/version.py b/products/stamphog/packages/pr-approval-agent/version.pyindex cfec570000b8..00e9578e1d65 100644--- a/products/stamphog/packages/pr-approval-agent/version.py+++ b/products/stamphog/packages/pr-approval-agent/version.py@@ -9,4 +9,4 @@ changes don't need a bump - they are tracked by the policy sha shown next tothe version in the verdict table."""-STAMPHOG_VERSION = "2.4.0"+STAMPHOG_VERSION = "2.4.1"