: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): default new repos to label mode and create the trigger label (#115270)
Julian Bez3cfba26b5237
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.mdindex c8add9f4b69a..2425898952ec 100644--- a/products/stamphog/AGENTS.md+++ b/products/stamphog/AGENTS.md@@ -204,6 +204,8 @@ A refusal writes nothing to GitHub and creates no run, so it cannot leave or rema manager paused; that is the requested self-serve direction. A supplied value counts even when itmatches the stored one, because the view's snapshot of the row is stale by the time the facadesaves. The digest toggle stays at `editor`. Service credentials are refused at both levels.+ The model default for `review_mode` is `label`, the narrow mode, so an editor turning reviews on+ never widens them past opt-in. Do not change the default to `all` without moving that level too.- A sync records what the member's own GitHub token lists in the team's `StamphogInstallation`snapshot and creates no repo config. `add_repository` binds only a repository in that snapshot,taking the installation id and the connecting user from the record, never from the request.@@ -218,8 +220,8 @@ A refusal writes nothing to GitHub and creates no run, so it cannot leave or remroot `owners.yaml` team registry the digest routes through.- A manually-created repo config (blank `installation_id`) binds **disabled** when a sync adopts it,and its review policy (`review_mode`, `trigger_label`) resets to the model defaults: all of those- fields were set by someone who never proved GitHub access, so a pre-selected label mode would- otherwise go live the moment someone enables the row. `add_repository` resets a placeholder's+ fields were set by someone who never proved GitHub access, so a pre-selected review mode or label+ would otherwise go live the moment someone enables the row. `add_repository` resets a placeholder'spolicy the same way when it binds one. Reinstall rebinds keep settings — thosewere configured under a verified binding. Such a row is also kept out of the digest candidates:a blank installation can fetch no routing file, and every candidate is read, so leaving it in letdiff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex 5ff98d8c17ac..aa5b1cec0c7d 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -49,8 +49,8 @@ Every other rule still applies: drafts, closed PRs, bot-authored PRs, PRs from o1. Install the Stamphog GitHub App on your GitHub organization.2. Open Stamphog in the PostHog app and connect GitHub. The callback records the repositories you can reach with your own GitHub account. It adds none of them yet.-3. Add each repository you want reviewed from the **Add a repository** search (`POST repo_configs/add_repository`). Adding a repository turns its reviews on. The search lists the repositories you can add, from `GET repo_configs/available_repositories`.-4. Expand the repository's row and pick a **review mode**: "All PRs" reviews every pull request, "Label-triggered" reviews only PRs carrying the trigger label. Set the trigger label name next to the mode.+3. Add each repository you want reviewed from the **Add a repository** search (`POST repo_configs/add_repository`). Adding a repository turns its reviews on in label-triggered mode. The search lists the repositories you can add, from `GET repo_configs/available_repositories`.+4. Expand the repository's row to change the **review mode**: "Label-triggered" (the default) reviews only PRs carrying the trigger label, "All PRs" reviews every pull request. Set the trigger label name next to the mode.5. Turn on **Include in the digest** if you want the daily Slack digest of merged PRs. The project needs a connected Slack integration first, or the digest run stops silently before posting.The repositories you can add are the ones a project member reached with their own GitHub account, not every repository the installation can reach.@@ -61,6 +61,10 @@ A repository added to the installation later shows up after a member connects agAdding a repository, turning reviews back on, and the digest toggle need the `editor` level on the `stamphog` resource.Turning reviews off, removing a repository, and changing the review mode or trigger label need `manager`.So an editor can turn reviews back on for a repository a manager paused.+New repositories start in label-triggered mode, so an editor can turn reviews on without a manager, and widening them to every PR stays a manager decision.++When a repository is turned on in label-triggered mode, or its trigger label changes, Stamphog creates the label in the GitHub repository, because GitHub only offers existing labels on a PR.+This is best-effort: if the app may not write labels there, or the label already exists, nothing changes and nothing is reported.## Customize the review for your repositorydiff --git a/products/stamphog/backend/facade/enums.py b/products/stamphog/backend/facade/enums.pyindex 6bf17a4bd0f1..3842ab95f0a6 100644--- a/products/stamphog/backend/facade/enums.py+++ b/products/stamphog/backend/facade/enums.py@@ -12,9 +12,9 @@ from posthog.enums import LabeledStrEnumclass ReviewMode(LabeledStrEnum):- # Every relevant PR event triggers a review (the default).+ # Every relevant PR event triggers a review.ALL = "all", "All pull requests"- # Reviews run only for PRs carrying the repo's trigger label (Action-style opt-in).+ # Reviews run only for PRs carrying the repo's trigger label (Action-style opt-in, the default).LABEL = "label", "Labeled pull requests"diff --git a/products/stamphog/backend/facade/tasks.py b/products/stamphog/backend/facade/tasks.pyindex aa16c52ba592..640120e2b032 100644--- a/products/stamphog/backend/facade/tasks.py+++ b/products/stamphog/backend/facade/tasks.py@@ -15,9 +15,11 @@ from products.stamphog.backend.tasks.tasks import (process_pull_request_event,request_rereview_after_external_review,)+from products.stamphog.backend.tasks.trigger_label import create_trigger_label__all__ = ["DAILY_DIGEST_CRONTAB",+ "create_trigger_label","process_installation_event","process_pull_request_event","queue_inbox_pr_review",diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.pyindex 4e366bceacc5..f27f729740c1 100644--- a/products/stamphog/backend/logic/github_client.py+++ b/products/stamphog/backend/logic/github_client.py@@ -1379,6 +1379,30 @@ class StamphogGitHubClient:status_code=response.status_code,)+ def create_label(self, repo: str, name: str, *, color: str, description: str) -> bool:+ """Create a repository label (``POST /repos/{repo}/labels``). Returns whether GitHub created it.++ Best-effort and never raises over the response: a 422 means the label already exists, and a+ 403 or 404 means the installation may not write labels on this repository. Both leave the+ repository as it is.+ """+ response = self._request(+ "POST",+ f"/repos/{repo}/labels",+ endpoint="/repos/{owner}/{repo}/labels",+ json_body={"name": name, "color": color, "description": description},+ priority=Priority.BATCH,+ )+ if response.status_code == 201:+ return True+ logger.info(+ "stamphog github: label not created",+ repo=repo,+ label=name,+ status_code=response.status_code,+ )+ return False+def dismiss_pr_review(self, repo: str, pr_number: int, review_id: int, message: str) -> None:"""Dismiss a previously submitted review (``PUT .../reviews/{review_id}/dismissals``).diff --git a/products/stamphog/backend/logic/installations.py b/products/stamphog/backend/logic/installations.pyindex f002e06f1cf5..99403f1cff40 100644--- a/products/stamphog/backend/logic/installations.py+++ b/products/stamphog/backend/logic/installations.py@@ -18,8 +18,9 @@ def reset_unverified_review_policy(config: StamphogRepoConfig) -> list[str]:"""Put a placeholder's review policy back at the model defaults. Returns the fields it changed.A placeholder (blank installation) was configured by someone who never proved GitHub access.- A label mode with a label nobody uses would otherwise go live, reviewing nothing, the moment- the row binds to a real installation and turns on.+ A mode or label they picked would otherwise go live the moment the row binds to a real+ installation and turns on: all mode reviews every pull request, and a label nobody uses+ reviews nothing."""# Read the defaults off the model so the reset cannot drift from what a fresh row gets.config.review_mode = StamphogRepoConfig._meta.get_field("review_mode").get_default()diff --git a/products/stamphog/backend/migrations/0010_review_mode_default_label.py b/products/stamphog/backend/migrations/0010_review_mode_default_label.pynew file mode 100644index 000000000000..63fd1f3029b5--- /dev/null+++ b/products/stamphog/backend/migrations/0010_review_mode_default_label.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.18 on 2026-10-12 09:23++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("stamphog", "0009_delete_unused_repo_configs"),+ ]++ operations = [+ migrations.AlterField(+ model_name="stamphogrepoconfig",+ name="review_mode",+ field=models.CharField(+ choices=[+ ("all", "All pull requests"),+ ("label", "Labeled pull requests"),+ ],+ default="label",+ max_length=16,+ ),+ ),+ ]diff --git a/products/stamphog/backend/migrations/max_migration.txt b/products/stamphog/backend/migrations/max_migration.txtindex 2b35efdcb4e9..6f172202cb7a 100644--- a/products/stamphog/backend/migrations/max_migration.txt+++ b/products/stamphog/backend/migrations/max_migration.txt@@ -1 +1 @@-0009_delete_unused_repo_configs+0010_review_mode_default_labeldiff --git a/products/stamphog/backend/models.py b/products/stamphog/backend/models.pyindex 8bdbfdda91dd..a99e18bea0f0 100644--- a/products/stamphog/backend/models.py+++ b/products/stamphog/backend/models.py@@ -42,12 +42,12 @@ class StamphogRepoConfig(ModelActivityMixin, ProductTeamModel):# Opt-in: capture merged PRs and fold them into the daily Slack digest. Independent of# `enabled` (review) so a repo can be reviewed without digests, or vice versa.digest_enabled = models.BooleanField(default=False)- # ALL reviews every relevant PR event (the default); LABEL reviews only PRs carrying trigger_label,- # mirroring the Action's label-gated opt-in flow.+ # LABEL (the default) reviews only PRs carrying trigger_label, mirroring the Action's label-gated+ # opt-in flow; ALL reviews every relevant PR event.review_mode = models.CharField(max_length=16,- choices=[(m.value, m.value) for m in ReviewMode],- default=ReviewMode.ALL.value,+ choices=ReviewMode.choices,+ default=ReviewMode.LABEL.value,)trigger_label = models.CharField(max_length=100, default="stamphog")# The PostHog user who connected this repo's installation (plain id, no FK — multi-DB product).diff --git a/products/stamphog/backend/presentation/serializers.py b/products/stamphog/backend/presentation/serializers.pyindex 31c68ede0854..bde8261ae16f 100644--- a/products/stamphog/backend/presentation/serializers.py+++ b/products/stamphog/backend/presentation/serializers.py@@ -101,8 +101,8 @@ class StamphogRepoConfigSerializer(DataclassSerializer):choices=ReviewMode.choices,read_only=True,help_text=(- "When reviews run: 'all' reviews every pull request (the default); 'label' reviews "- "only pull requests carrying the trigger label, mirroring the Action's opt-in flow."+ "When reviews run: 'label' reviews only pull requests carrying the trigger label (the "+ "default), mirroring the Action's opt-in flow; 'all' reviews every pull request."),)@@ -742,8 +742,8 @@ class StamphogRepoConfigWriteSerializer(serializers.Serializer):choices=ReviewMode.choices,required=False,help_text=(- "When reviews run: 'all' reviews every pull request (the default); 'label' reviews "- "only pull requests carrying the trigger label, mirroring the Action's opt-in flow."+ "When reviews run: 'label' reviews only pull requests carrying the trigger label (the "+ "default), mirroring the Action's opt-in flow; 'all' reviews every pull request."),)trigger_label = serializers.CharField(diff --git a/products/stamphog/backend/presentation/views.py b/products/stamphog/backend/presentation/views.pyindex 447e490c7be0..5e1aef72f29a 100644--- a/products/stamphog/backend/presentation/views.py+++ b/products/stamphog/backend/presentation/views.py@@ -37,7 +37,7 @@ from products.stamphog.backend.facade import (api as facade_api,contracts,)-from products.stamphog.backend.facade.enums import ReviewRequestRefusal, ReviewTrigger+from products.stamphog.backend.facade.enums import ReviewMode, ReviewRequestRefusal, ReviewTriggerfrom ..facade import review_requestsfrom ..facade.github import (@@ -47,6 +47,7 @@ from ..facade.github import (sync_installation_repositories,user_can_access_installation,)+from ..facade.tasks import create_trigger_labelfrom .serializers import (DigestRunSerializer,PullRequestSerializer,@@ -236,6 +237,15 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView"Only a Stamphog editor can turn reviews on. Ask an organization admin for editor access.")+ def _queue_trigger_label_creation(self, config: contracts.RepoConfigDTO) -> None:+ if not (config.enabled and config.review_mode == ReviewMode.LABEL):+ return+ # The write already committed, so an unreachable broker must not turn it into a 500.+ try:+ create_trigger_label.delay(team_id=self.canonical_team_id, config_id=str(config.id))+ except Exception:+ logger.warning("stamphog_trigger_label_queue_failed", repository=config.repository, exc_info=True)+def _available_count(self) -> int:return facade_api.list_available_repositories(self.canonical_team_id, limit=0).total_count@@ -278,6 +288,8 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewserializer.is_valid(raise_exception=True)self._require_review_level(request, _required_review_level(serializer.validated_data))config = facade_api.update_repo_config(self.canonical_team_id, str(pk), **serializer.validated_data)+ if any(field in serializer.validated_data for field in ("enabled", *REVIEW_POLICY_FIELDS)):+ self._queue_trigger_label_creation(config)return Response(self.get_serializer(config).data)@extend_schema(request=StamphogRepoConfigWriteSerializer, responses={200: StamphogRepoConfigSerializer})@@ -338,6 +350,7 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewraise ValidationError({"repository": "This repository is already configured under this GitHub installation by another team."})+ self._queue_trigger_label_creation(result.config)return Response(self.get_serializer(result.config).data, status=201 if result.created else 200)@extend_schema(responses={200: StamphogInstallInfoSerializer})diff --git a/products/stamphog/backend/tasks/__init__.py b/products/stamphog/backend/tasks/__init__.pyindex 1bd477ba1e76..02b6293af6da 100644--- a/products/stamphog/backend/tasks/__init__.py+++ b/products/stamphog/backend/tasks/__init__.py@@ -4,4 +4,4 @@ Import the task-defining submodules here so Celery's ``autodiscover_tasks`` (whiapp's ``tasks`` package) registers every ``@shared_task`` on workers and beat."""-from products.stamphog.backend.tasks import digest, tasks # noqa: F401+from products.stamphog.backend.tasks import digest, tasks, trigger_label # noqa: F401diff --git a/products/stamphog/backend/tasks/trigger_label.py b/products/stamphog/backend/tasks/trigger_label.pynew file mode 100644index 000000000000..42c8cb72c881--- /dev/null+++ b/products/stamphog/backend/tasks/trigger_label.py@@ -0,0 +1,52 @@+"""Create a repository's trigger label on GitHub, so people can pick it on a pull request.++GitHub's label picker only offers labels that exist in the repository. In label mode, a repository+without the trigger label gets no reviews until somebody creates it by hand.+"""++from __future__ import annotations++from django.db import router++import structlog+from celery import shared_task++from products.stamphog.backend.facade.enums import ReviewMode+from products.stamphog.backend.logic.github_client import StamphogGitHubClient+from products.stamphog.backend.models import StamphogRepoConfig++logger = structlog.get_logger(__name__)++TRIGGER_LABEL_COLOR = "f54e00"+TRIGGER_LABEL_DESCRIPTION = "Ask Stamphog to review this pull request"+++@shared_task(ignore_result=True)+def create_trigger_label(team_id: int, config_id: str) -> None:+ """Create the trigger label of an enabled label-mode repository, if GitHub lets the app do it."""+ # Writer pin: the task runs right after the commit that enabled the row, and a lagged replica+ # can still show it disabled or missing.+ config = (+ StamphogRepoConfig.objects.for_team(team_id)+ .using(router.db_for_write(StamphogRepoConfig))+ .filter(id=config_id, enabled=True, review_mode=ReviewMode.LABEL)+ .exclude(installation_id="")+ .first()+ )+ if config is None:+ return+ # Best-effort: without the label, somebody creates it by hand, so no failure here may surface.+ try:+ StamphogGitHubClient(config.installation_id).create_label(+ config.repository,+ config.trigger_label,+ color=TRIGGER_LABEL_COLOR,+ description=TRIGGER_LABEL_DESCRIPTION,+ )+ except Exception:+ logger.warning(+ "stamphog_trigger_label_create_failed",+ repository=config.repository,+ label=config.trigger_label,+ exc_info=True,+ )diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.pyindex 9a0ab175c1eb..afad7416c766 100644--- a/products/stamphog/backend/tests/test_api.py+++ b/products/stamphog/backend/tests/test_api.py@@ -3,7 +3,7 @@ from typing import Anyimport pytestfrom posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import call, patchfrom django.core import signingfrom django.db import transaction@@ -75,7 +75,7 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):@parameterized.expand([("enabled", {"enabled": False}),- ("review_mode", {"review_mode": ReviewMode.LABEL}),+ ("review_mode", {"review_mode": ReviewMode.ALL}),("trigger_label", {"trigger_label": "review-me"}),])@@ -111,7 +111,7 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):@parameterized.expand([- ("names_the_review_mode", {"review_mode": ReviewMode.LABEL}, status.HTTP_403_FORBIDDEN),+ ("names_the_review_mode", {"review_mode": ReviewMode.ALL}, status.HTTP_403_FORBIDDEN),("turns_reviews_off", {"enabled": False}, status.HTTP_403_FORBIDDEN),("turns_reviews_on", {"enabled": True}, status.HTTP_201_CREATED),("leaves_the_defaults", {}, status.HTTP_201_CREATED),@@ -481,7 +481,7 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):[("new_row", None, status.HTTP_201_CREATED),("paused_row", "42", status.HTTP_200_OK),- # A placeholder's label mode was set without proving GitHub access, so it resets on binding.+ # A placeholder's all mode was set without proving GitHub access, so it resets on binding.("placeholder_row", "", status.HTTP_200_OK),])@@ -497,17 +497,22 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):repository="acme/alpha",installation_id=existing_installation,enabled=False,- review_mode=ReviewMode.LABEL,+ review_mode=ReviewMode.ALL,)self._login_as_member()- response = self.client.post(f"{self.url}add_repository/", {"repository": "acme/alpha"}, format="json")+ with patch(f"{_VIEWS}.create_trigger_label.delay") as queue_label:+ response = self.client.post(f"{self.url}add_repository/", {"repository": "acme/alpha"}, format="json")assert response.status_code == expected_status, response.contentconfig = StamphogRepoConfig.objects.unscoped().get(team_id=self.team.id, repository="acme/alpha")assert (config.enabled, config.installation_id, config.connected_by_user_id) == (True, "42", self.user.id)- expected_mode = ReviewMode.ALL if existing_installation in (None, "") else ReviewMode.LABEL+ expected_mode = ReviewMode.LABEL if existing_installation in (None, "") else ReviewMode.ALLassert config.review_mode == expected_mode+ expected_calls = (+ [call(team_id=self.team.id, config_id=str(config.id))] if expected_mode == ReviewMode.LABEL else []+ )+ assert queue_label.call_args_list == expected_calls@parameterized.expand([@@ -985,7 +990,7 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):installation_id="",enabled=True,digest_enabled=True,- review_mode=ReviewMode.LABEL,+ review_mode=ReviewMode.ALL,trigger_label="nobody-uses-this",)response = self.client.post(@@ -1000,7 +1005,7 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):assert manual.connected_by_user_id == self.user.idassert manual.enabled is Falseassert manual.digest_enabled is False- assert manual.review_mode == ReviewMode.ALL+ assert manual.review_mode == ReviewMode.LABELassert manual.trigger_label == StamphogRepoConfig._meta.get_field("trigger_label").get_default()@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories", return_value=["PostHog/posthog"])@@ -1016,7 +1021,7 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):repository="PostHog/posthog",installation_id="41",enabled=True,- review_mode=ReviewMode.LABEL,+ review_mode=ReviewMode.ALL,connected_by_user_id=previous_connector_id,)response = self.client.post(@@ -1028,7 +1033,7 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):stale.refresh_from_db()assert stale.installation_id == "42"assert stale.enabled is True # settings survive the rebind- assert stale.review_mode == ReviewMode.LABEL # including the review policy+ assert stale.review_mode == ReviewMode.ALL # including the review policyassert stale.connected_by_user_id == self.user.id# The restamp reads its before-value from the locked row, so the log names who held the# connection before this sync took it over.diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.pyindex c32ab5483993..e59c1b17f4c6 100644--- a/products/stamphog/backend/tests/test_integration.py+++ b/products/stamphog/backend/tests/test_integration.py@@ -90,6 +90,7 @@ def _repo_config(team_id: int, *, digest_enabled: bool = True, repository: str =installation_id=INSTALLATION_ID,enabled=True,digest_enabled=digest_enabled,+ review_mode=ReviewMode.ALL,connected_by_user_id=connected_by,)diff --git a/products/stamphog/backend/tests/test_models.py b/products/stamphog/backend/tests/test_models.pyindex 51b1d4c89c7c..caac660923a6 100644--- a/products/stamphog/backend/tests/test_models.py+++ b/products/stamphog/backend/tests/test_models.py@@ -144,10 +144,11 @@ class TestInstallationMigrations(StamphogTeamScopedTestMixin, APIBaseTest):("acme/unused", "1", False, 7),("acme/with-history", "1", False, None),("acme/placeholder", "", False, None),- ("acme/label-mode", "1", False, None),+ ("acme/changed-mode", "1", False, None),]}- StamphogRepoConfig.objects.unscoped().filter(id=rows["acme/label-mode"].id).update(review_mode="label")+ # The cleanup reads the model default as untouched, so the kept row holds the other mode.+ StamphogRepoConfig.objects.unscoped().filter(id=rows["acme/changed-mode"].id).update(review_mode="all")for day, name in enumerate(rows, start=1):StamphogRepoConfig.objects.unscoped().filter(id=rows[name].id).update(updated_at=datetime(2026, 1, day, tzinfo=UTC)@@ -161,12 +162,12 @@ class TestInstallationMigrations(StamphogTeamScopedTestMixin, APIBaseTest):installation = StamphogInstallation.objects.unscoped().get(team_id=self.team.id)assert installation.installation_id == "1"- assert installation.repositories == ["acme/label-mode", "acme/reviewed", "acme/unused", "acme/with-history"]+ assert installation.repositories == ["acme/changed-mode", "acme/reviewed", "acme/unused", "acme/with-history"]# The newest non-null connector, which the newer row with no connector does not overwrite.assert installation.connected_by_user_id == 7remaining = StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id)assert sorted(remaining.values_list("repository", flat=True)) == [- "acme/label-mode",+ "acme/changed-mode","acme/placeholder","acme/reviewed","acme/with-history",diff --git a/products/stamphog/backend/tests/test_tasks.py b/products/stamphog/backend/tests/test_tasks.pyindex 4754c580bed8..a6732f87e523 100644--- a/products/stamphog/backend/tests/test_tasks.py+++ b/products/stamphog/backend/tests/test_tasks.py@@ -6,8 +6,11 @@ import pytestfrom unittest.mock import patchfrom django.core.cache import cache+from django.test import override_settingsfrom django.utils.dateparse import parse_datetime+import requests+from posthog.models import Project, Teamfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.instance_setting import override_instance_config@@ -30,7 +33,13 @@ from products.stamphog.backend.tasks.tasks import (process_installation_event,process_pull_request_event,)-from products.stamphog.backend.tests.conftest import PRODUCT_DATABASES+from products.stamphog.backend.tasks.trigger_label import (+ TRIGGER_LABEL_COLOR,+ TRIGGER_LABEL_DESCRIPTION,+ create_trigger_label,+)+from products.stamphog.backend.tests.conftest import PRODUCT_DATABASES, _generate_app_private_key+from products.stamphog.backend.tests.fakes import FakeResponsefrom products.tasks.backend.facade.contracts import SignalImplementationRunDTOREPO = "acme/widgets"@@ -145,7 +154,9 @@ def _run_task(@pytest.fixturedef repo_config(team):with team_scope(team.id):- return StamphogRepoConfig.objects.create(team_id=team.id, repository=REPO, installation_id=INSTALLATION_ID)+ return StamphogRepoConfig.objects.create(+ team_id=team.id, repository=REPO, installation_id=INSTALLATION_ID, review_mode=ReviewMode.ALL+ )@pytest.mark.django_db(databases=PRODUCT_DATABASES)@@ -1475,3 +1486,42 @@ def test_trigger_label_is_taken_back_off_a_bot_pr(team, repo_config, action, expassert client.upsert_sticky_comment.called is expect_commentwith team_scope(team.id):assert ReviewRun.objects.count() == 0+++ "review_mode,enabled,github_answer,expect_post",+ [+ pytest.param(ReviewMode.LABEL, True, FakeResponse(201), True, id="created"),+ pytest.param(ReviewMode.LABEL, True, FakeResponse(422), True, id="already_exists"),+ pytest.param(ReviewMode.LABEL, True, FakeResponse(403), True, id="not_permitted"),+ pytest.param(ReviewMode.LABEL, True, requests.ConnectionError("down"), True, id="network_error"),+ pytest.param(ReviewMode.ALL, True, FakeResponse(201), False, id="all_mode"),+ pytest.param(ReviewMode.LABEL, False, FakeResponse(201), False, id="paused"),+ ],+)[email protected]_db(databases=PRODUCT_DATABASES)+def test_create_trigger_label_never_raises(team, repo_config, review_mode, enabled, github_answer, expect_post):+ StamphogRepoConfig.objects.unscoped().filter(id=repo_config.id).update(+ review_mode=review_mode, enabled=enabled, trigger_label="review-me"+ )+ calls: list[tuple[str, str, Any]] = []++ def fake_request(method: str, url: str, **kwargs: Any) -> FakeResponse:+ if url.endswith("/access_tokens"):+ return FakeResponse(201, json_data={"token": "t", "expires_at": "2999-01-01T00:00:00Z"})+ calls.append((method, url, kwargs.get("json")))+ if isinstance(github_answer, Exception):+ raise github_answer+ return github_answer++ _GH = "products.stamphog.backend.logic.github_client"+ with (+ override_settings(STAMPHOG_GITHUB_APP_ID="1", STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key()),+ patch(f"{_GH}.github_request", fake_request),+ patch(f"{_GH}.remember_observed_core_limit", lambda *a, **k: None),+ patch(f"{_GH}.raise_if_github_rate_limited", lambda *a, **k: None),+ ):+ create_trigger_label(team.id, str(repo_config.id))++ expected_body = {"name": "review-me", "color": TRIGGER_LABEL_COLOR, "description": TRIGGER_LABEL_DESCRIPTION}+ assert calls == ([("POST", f"https://api.github.com/repos/{REPO}/labels", expected_body)] if expect_post else [])diff --git a/products/stamphog/frontend/generated/api.schemas.ts b/products/stamphog/frontend/generated/api.schemas.tsindex 4580d9ca129c..375233a075ed 100644--- a/products/stamphog/frontend/generated/api.schemas.ts+++ b/products/stamphog/frontend/generated/api.schemas.ts@@ -177,7 +177,7 @@ export interface StamphogRepoConfigApi {readonly installation_id: string/** Whether merged PRs on this repo are captured for the daily Slack digest. Requires 'enabled', since the digest reports what stamphog approved. */digest_enabled?: boolean- /** When reviews run: 'all' reviews every pull request (the default); 'label' reviews only pull requests carrying the trigger label, mirroring the Action's opt-in flow.+ /** When reviews run: 'label' reviews only pull requests carrying the trigger label (the default), mirroring the Action's opt-in flow; 'all' reviews every pull request.** * `all` - All pull requests* * `label` - Labeled pull requests */@@ -223,7 +223,7 @@ export interface StamphogRepoConfigWriteApi {enabled?: boolean/** Whether merged PRs on this repo are captured for the daily Slack digest. */digest_enabled?: boolean- /** When reviews run: 'all' reviews every pull request (the default); 'label' reviews only pull requests carrying the trigger label, mirroring the Action's opt-in flow.+ /** When reviews run: 'label' reviews only pull requests carrying the trigger label (the default), mirroring the Action's opt-in flow; 'all' reviews every pull request.** * `all` - All pull requests* * `label` - Labeled pull requests */@@ -253,7 +253,7 @@ export interface PatchedStamphogRepoConfigWriteApi {enabled?: boolean/** Whether merged PRs on this repo are captured for the daily Slack digest. */digest_enabled?: boolean- /** When reviews run: 'all' reviews every pull request (the default); 'label' reviews only pull requests carrying the trigger label, mirroring the Action's opt-in flow.+ /** When reviews run: 'label' reviews only pull requests carrying the trigger label (the default), mirroring the Action's opt-in flow; 'all' reviews every pull request.** * `all` - All pull requests* * `label` - Labeled pull requests */diff --git a/products/stamphog/frontend/generated/api.zod.ts b/products/stamphog/frontend/generated/api.zod.tsindex bc9d2bd56b6f..ebff79642e05 100644--- a/products/stamphog/frontend/generated/api.zod.ts+++ b/products/stamphog/frontend/generated/api.zod.ts@@ -26,7 +26,7 @@ export const StamphogRepoConfigsCreateBody = /* @__PURE__ */ zod.describe('\* `all` - All pull requests\n\* `label` - Labeled pull requests').optional().describe(- "When reviews run: 'all' reviews every pull request (the default); 'label' reviews only pull requests carrying the trigger label, mirroring the Action's opt-in flow.\n\n\* `all` - All pull requests\n\* `label` - Labeled pull requests"+ "When reviews run: 'label' reviews only pull requests carrying the trigger label (the default), mirroring the Action's opt-in flow; 'all' reviews every pull request.\n\n\* `all` - All pull requests\n\* `label` - Labeled pull requests"),trigger_label: zod.string()@@ -54,7 +54,7 @@ export const StamphogRepoConfigsUpdateBody = /* @__PURE__ */ zod.describe('\* `all` - All pull requests\n\* `label` - Labeled pull requests').optional().describe(- "When reviews run: 'all' reviews every pull request (the default); 'label' reviews only pull requests carrying the trigger label, mirroring the Action's opt-in flow.\n\n\* `all` - All pull requests\n\* `label` - Labeled pull requests"+ "When reviews run: 'label' reviews only pull requests carrying the trigger label (the default), mirroring the Action's opt-in flow; 'all' reviews every pull request.\n\n\* `all` - All pull requests\n\* `label` - Labeled pull requests"),trigger_label: zod.string()@@ -82,7 +82,7 @@ export const StamphogRepoConfigsPartialUpdateBody = /* @__PURE__ */ zod.describe('\* `all` - All pull requests\n\* `label` - Labeled pull requests').optional().describe(- "When reviews run: 'all' reviews every pull request (the default); 'label' reviews only pull requests carrying the trigger label, mirroring the Action's opt-in flow.\n\n\* `all` - All pull requests\n\* `label` - Labeled pull requests"+ "When reviews run: 'label' reviews only pull requests carrying the trigger label (the default), mirroring the Action's opt-in flow; 'all' reviews every pull request.\n\n\* `all` - All pull requests\n\* `label` - Labeled pull requests"),trigger_label: zod.string()diff --git a/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsx b/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsxindex cb1eec3aa8ed..a6d5e8e10886 100644--- a/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsx+++ b/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsx@@ -58,7 +58,7 @@ function TriggerSettings({<div className="flex flex-wrap items-center gap-2"><LemonSelectsize="small"- value={repo.review_mode ?? ReviewModeEnumApi.All}+ value={repo.review_mode ?? ReviewModeEnumApi.Label}disabledReason={disabledReason}onChange={(mode) => updateRepoConfig(repo.id, { review_mode: mode })}options={[diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c4755874963e..ce00a46e3665 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -73938,7 +73938,7 @@ export namespace Schemas {readonly installation_id: string;/** Whether merged PRs on this repo are captured for the daily Slack digest. Requires 'enabled', since the digest reports what stamphog approved. */digest_enabled?: boolean;- /** When reviews run: 'all' reviews every pull request (the default); 'label' reviews only pull requests carrying the trigger label, mirroring the Action's opt-in flow.+ /** When reviews run: 'label' reviews only pull requests carrying the trigger label (the default), mirroring the Action's opt-in flow; 'all' reviews every pull request.** * `all` - All pull requests* * `label` - Labeled pull requests */@@ -84771,7 +84771,7 @@ export namespace Schemas {enabled?: boolean;/** Whether merged PRs on this repo are captured for the daily Slack digest. */digest_enabled?: boolean;- /** When reviews run: 'all' reviews every pull request (the default); 'label' reviews only pull requests carrying the trigger label, mirroring the Action's opt-in flow.+ /** When reviews run: 'label' reviews only pull requests carrying the trigger label (the default), mirroring the Action's opt-in flow; 'all' reviews every pull request.** * `all` - All pull requests* * `label` - Labeled pull requests */@@ -107185,7 +107185,7 @@ export namespace Schemas {enabled?: boolean;/** Whether merged PRs on this repo are captured for the daily Slack digest. */digest_enabled?: boolean;- /** When reviews run: 'all' reviews every pull request (the default); 'label' reviews only pull requests carrying the trigger label, mirroring the Action's opt-in flow.+ /** When reviews run: 'label' reviews only pull requests carrying the trigger label (the default), mirroring the Action's opt-in flow; 'all' reviews every pull request.** * `all` - All pull requests* * `label` - Labeled pull requests */