: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(devex): add reviewer requests toggle to stamphog settings (#128931)
Julian Bez6ae5cc31b115
diff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex 9898551a11c9..ab043ede386a 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -195,7 +195,9 @@ A comment names the cut owners and why.`routing_fork_labels` maps a team slug to a label name. On a fork PR, a kept team with an entry gets that label instead of a review request, so an outside author cannot ping it.-There is no API or admin page for these settings yet. Set them with a manual DB write, for example `StamphogRepoConfig.objects.for_team(team_id).filter(repository="acme/widgets").update(routing_mode="fallback", routing_fork_labels={"team-alpha": "team/alpha"})`.+`routing_mode` is set under "Reviewer requests" in the repository's row on the Stamphog page, or with `routing_mode` on the repo config API. Both directions take the `manager` level, like `review_mode`. A placeholder row resets it to `off` when it binds to an installation, like the other review policy fields.+The page offers the setting only when the default branch has a root `owners.yaml` (`GET repo_configs/{id}/owners_file/`, at most one GitHub call per repository every 10 minutes, at a priority the egress limiter can shed), and keeps it in view while it is on, so it can be turned off.+`routing_fork_labels` has no API yet. Set it with a manual DB write, for example `StamphogRepoConfig.objects.for_team(team_id).filter(repository="acme/widgets").update(routing_fork_labels={"team-alpha": "team/alpha"})`.The latest result is stored on `PullRequest.routing` with its mode, trigger (`opened`, `ready_for_review`, `verdict:<outcome>` or `safety_net`), scope (`full` or `pinned`) and status (`waiting`, `routing`, `requested` or `done`).`full_routed_head`, `pinned_routed_head` (with their `_at` times) and `requested_owners` carry over to every later record, so the PR-level rules hold across pushes.diff --git a/products/stamphog/backend/facade/api.py b/products/stamphog/backend/facade/api.pyindex b5a8f7d0511b..b3cb0b0ba4db 100644--- a/products/stamphog/backend/facade/api.py+++ b/products/stamphog/backend/facade/api.py@@ -22,6 +22,7 @@ import structlogfrom ..logic.installations import reset_unverified_review_policyfrom ..logic.review_trigger import derive_review_triggerfrom ..logic.reviewer import parse_reviewer_output+from ..logic.routing.owners_file import owners_file_statusfrom ..logic.scrubbing import neutralize_active_markdown, scrub_credentialsfrom ..models import DigestRun, PullRequest, ReviewRun, StamphogInstallation, StamphogRepoConfigfrom . import contracts@@ -29,6 +30,7 @@ from .enums import (TERMINAL_STATUSES,ChannelResolutionSource,DigestRunStatus,+ OwnersFileStatus,ReviewMode,ReviewRunStatus,ReviewTrigger,@@ -83,6 +85,7 @@ def _repo_config_to_dto(obj: StamphogRepoConfig) -> contracts.RepoConfigDTO:digest_enabled=obj.digest_enabled,review_mode=obj.review_mode,trigger_label=obj.trigger_label,+ routing_mode=obj.routing_mode,created_at=obj.created_at,updated_at=obj.updated_at,)@@ -254,6 +257,14 @@ def get_repo_config_by_id(team_id: int, config_id: str) -> contracts.RepoConfigDreturn _repo_config_to_dto(obj) if obj is not None else None+def check_owners_file(config: contracts.RepoConfigDTO) -> OwnersFileStatus:+ """Whether the repo's default branch has the root owners.yaml that reviewer requests need.++ Makes one GitHub call with the repo's installation token, so callers ask only on demand.+ """+ return owners_file_status(config.id, config.repository, config.installation_id)++def has_reviewable_repo_config(team_id: int) -> bool:"""Whether the team has at least one enabled repo config that hosted reviews can run on.@@ -353,6 +364,7 @@ def create_repo_config(digest_enabled: bool = False,review_mode: str | None = None,trigger_label: str | None = None,+ routing_mode: str | None = None,) -> contracts.RepoConfigDTO:"""Create a repo config, refusing a repository another team already owns.@@ -367,6 +379,8 @@ def create_repo_config(fields["review_mode"] = review_modeif trigger_label is not None:fields["trigger_label"] = trigger_label+ if routing_mode is not None:+ fields["routing_mode"] = routing_mode# unique_stamphog_installation_repo backs this at the DB level, so a race that slips past the# read still fails closed on the create below and surfaces as the same domain error.try:diff --git a/products/stamphog/backend/facade/contracts.py b/products/stamphog/backend/facade/contracts.pyindex c0c04ec62acd..0767d9a2d52c 100644--- a/products/stamphog/backend/facade/contracts.py+++ b/products/stamphog/backend/facade/contracts.py@@ -39,6 +39,7 @@ class RepoConfigDTO:digest_enabled: bool = Falsereview_mode: str = ""trigger_label: str = ""+ routing_mode: str = ""created_at: datetime | None = Noneupdated_at: datetime | None = Nonediff --git a/products/stamphog/backend/facade/enums.py b/products/stamphog/backend/facade/enums.pyindex 7d3562d932f7..114c14032d1d 100644--- a/products/stamphog/backend/facade/enums.py+++ b/products/stamphog/backend/facade/enums.py@@ -28,6 +28,15 @@ class RoutingMode(LabeledStrEnum):FALLBACK = "fallback", "When stamphog does not approve"+class OwnersFileStatus(LabeledStrEnum):+ """Whether a repository's default branch has the root owners.yaml that reviewer routing reads."""++ FOUND = "found", "Found"+ MISSING = "missing", "Missing"+ # The check could not ask GitHub: no installation to read with, or GitHub answered with an error.+ UNAVAILABLE = "unavailable", "Unavailable"++# The pull_request actions that start a reviewer routing run. The webhook consumer imports this at# module level, so it lives in this light module.ROUTING_ACTIONS = frozenset({"opened", "ready_for_review"})diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.pyindex 7efa66e8e405..bf23e09dc029 100644--- a/products/stamphog/backend/logic/github_client.py+++ b/products/stamphog/backend/logic/github_client.py@@ -1330,7 +1330,7 @@ class StamphogGitHubClient:except (binascii.Error, UnicodeDecodeError) as exc:raise StamphogGitHubError(f"Failed to decode base64 contents for {repo}:{path}") from exc- def get_default_branch_file(self, repo: str, path: str) -> str | None:+ def get_default_branch_file(self, repo: str, path: str, *, priority: Priority = Priority.CRITICAL) -> str | None:"""Fetch a file's text from the repo's DEFAULT branch, or ``None`` if it doesn't exist.Policy files are always read from the default branch (never PR head), so a PR can't rewrite the@@ -1342,6 +1342,7 @@ class StamphogGitHubClient:f"/repos/{repo}/contents/{path}",endpoint="/repos/{owner}/{repo}/contents/{path}",headers={"Accept": "application/vnd.github.raw+json"},+ priority=priority,)if response.status_code == 404:return Nonediff --git a/products/stamphog/backend/logic/installations.py b/products/stamphog/backend/logic/installations.pyindex 99403f1cff40..fe1a21dbbba8 100644--- a/products/stamphog/backend/logic/installations.py+++ b/products/stamphog/backend/logic/installations.py@@ -20,12 +20,14 @@ def reset_unverified_review_policy(config: StamphogRepoConfig) -> list[str]:A placeholder (blank installation) was configured by someone who never proved GitHub access.A mode or label they picked would otherwise go live the moment the row binds to a realinstallation and turns on: all mode reviews every pull request, and a label nobody uses- reviews nothing.+ reviews nothing. Reviewer routing does not wait for the row to turn on, so a routing mode+ picked there would request reviewers as soon as the row binds."""# 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()config.trigger_label = StamphogRepoConfig._meta.get_field("trigger_label").get_default()- return ["review_mode", "trigger_label"]+ config.routing_mode = StamphogRepoConfig._meta.get_field("routing_mode").get_default()+ return ["review_mode", "trigger_label", "routing_mode"]def _write_db() -> str:diff --git a/products/stamphog/backend/logic/routing/owners_file.py b/products/stamphog/backend/logic/routing/owners_file.pynew file mode 100644index 000000000000..71b308ff4d39--- /dev/null+++ b/products/stamphog/backend/logic/routing/owners_file.py@@ -0,0 +1,50 @@+"""Whether a repository carries the owners.yaml that reviewer routing reads its candidates from."""++from __future__ import annotations++from uuid import UUID++from django.core.cache import cache++import structlog+from owners_yaml.schema import OWNERS_FILENAME++from posthog.egress.limiter.policies import Priority++from products.stamphog.backend.facade.enums import OwnersFileStatus+from products.stamphog.backend.logic.github_client import StamphogGitHubClient++logger = structlog.get_logger(__name__)++# Bounds what a settings page left open, or a caller looping on the API, can spend of the installation's+# GitHub budget, which the reviews and the routing share. A newly added owners.yaml shows up within this.+OWNERS_FILE_CACHE_SECONDS = 600+++def _cache_key(config_id: UUID, installation_id: str) -> str:+ # A rebind to another installation can read a different answer, so the installation is part of the key.+ return f"stamphog:owners_file:{config_id}:{installation_id}"+++def owners_file_status(config_id: UUID, repository: str, installation_id: str) -> OwnersFileStatus:+ """Look for the root owners.yaml on the default branch, where routing reads ownership.++ At most one GitHub call per repository config in the cache window. The call can be shed, because+ nothing but the settings page waits on it.+ """+ if not installation_id:+ return OwnersFileStatus.UNAVAILABLE+ key = _cache_key(config_id, installation_id)+ cached = cache.get(key)+ if cached in (OwnersFileStatus.FOUND, OwnersFileStatus.MISSING):+ return OwnersFileStatus(cached)+ try:+ text = StamphogGitHubClient(installation_id).get_default_branch_file(+ repository, OWNERS_FILENAME, priority=Priority.NORMAL+ )+ except Exception: # noqa: BLE001 - a failed check only hides the setting, so any error reads as unknown+ logger.warning("stamphog_owners_file_check_failed", repository=repository, exc_info=True)+ return OwnersFileStatus.UNAVAILABLE+ status = OwnersFileStatus.MISSING if text is None else OwnersFileStatus.FOUND+ cache.set(key, status.value, timeout=OWNERS_FILE_CACHE_SECONDS)+ return statusdiff --git a/products/stamphog/backend/presentation/serializers.py b/products/stamphog/backend/presentation/serializers.pyindex bde8261ae16f..8da66ddd749f 100644--- a/products/stamphog/backend/presentation/serializers.py+++ b/products/stamphog/backend/presentation/serializers.py@@ -16,10 +16,12 @@ from ..facade import contractsfrom ..facade.enums import (ChannelResolutionSource,DigestRunStatus,+ OwnersFileStatus,ReviewMode,ReviewRunStatus,ReviewTrigger,ReviewVerdict,+ RoutingMode,)@@ -71,7 +73,7 @@ class StamphogRepoConfigSerializer(DataclassSerializer):help_text=("The caller's access level on the stamphog resource, resolved for the team that owns this ""row. 'editor' can turn reviews on. 'manager' is required to turn them off or to change "- "review_mode or trigger_label."+ "review_mode, trigger_label or routing_mode."),)@@ -105,6 +107,16 @@ class StamphogRepoConfigSerializer(DataclassSerializer):"default), mirroring the Action's opt-in flow; 'all' reviews every pull request."),)+ routing_mode = serializers.ChoiceField(+ choices=RoutingMode.choices,+ read_only=True,+ help_text=(+ "When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the "+ "default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' "+ "only when stamphog does not approve, where an approval requests only the owners of sensitive and "+ "new paths."+ ),+ )class Meta:dataclass = contracts.RepoConfigDTO@@ -117,6 +129,7 @@ class StamphogRepoConfigSerializer(DataclassSerializer):"digest_enabled","review_mode","trigger_label",+ "routing_mode","user_access_level","created_at","updated_at",@@ -750,6 +763,16 @@ class StamphogRepoConfigWriteSerializer(serializers.Serializer):required=False,help_text=("Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'."),)+ routing_mode = serializers.ChoiceField(+ choices=RoutingMode.choices,+ required=False,+ help_text=(+ "When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the "+ "default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' "+ "only when stamphog does not approve, where an approval requests only the owners of sensitive and "+ "new paths."+ ),+ )def __init__(self,@@ -791,3 +814,15 @@ class StamphogRepoConfigWriteSerializer(serializers.Serializer):# pairing the soft-delete tombstone applies, and the Enabled toggle sends only `enabled`.attrs["digest_enabled"] = Falsereturn attrs+++class StamphogOwnersFileSerializer(serializers.Serializer):+ """Whether a repository can use reviewer requests, which read ownership from its owners.yaml."""++ owners_file = serializers.ChoiceField(+ choices=OwnersFileStatus.choices,+ help_text=(+ "Whether the default branch has a root owners.yaml: 'found', 'missing', or 'unavailable' when "+ "the check could not ask GitHub (no installation, or GitHub answered with an error)."+ ),+ )diff --git a/products/stamphog/backend/presentation/views.py b/products/stamphog/backend/presentation/views.pyindex 8b909d35ab9e..5900cc86f26b 100644--- a/products/stamphog/backend/presentation/views.py+++ b/products/stamphog/backend/presentation/views.py@@ -61,6 +61,7 @@ from .serializers import (StamphogAvailableRepositoriesQuerySerializer,StamphogAvailableRepositoriesSerializer,StamphogInstallInfoSerializer,+ StamphogOwnersFileSerializer,StamphogRepoConfigSerializer,StamphogRepoConfigWriteSerializer,StamphogSyncInstallationRequestSerializer,@@ -79,6 +80,9 @@ _INSTALL_STATE_MAX_AGE_SECONDS = 60 * 60# These decide when a pull request gets reviewed, so writing either of them takes the manager level.# `enabled` is split by direction: turning reviews on takes editor, turning them off takes manager.REVIEW_POLICY_FIELDS = ("review_mode", "trigger_label")+# Reviewer requests decide which teams get asked on every pull request, and turning them off can leave+# pull requests with no reviewer at all, so both directions take manager.+MANAGER_FIELDS = (*REVIEW_POLICY_FIELDS, "routing_mode")ReviewLevel = Literal["editor", "manager"]@@ -90,7 +94,7 @@ def _required_review_level(validated_data: dict[str, Any]) -> ReviewLevel | Nonefacade refetches and saves it, so a value that looks unchanged can still overwrite a manager'sdecision made in between. That is why a supplied `enabled=False` always takes manager."""- if validated_data.get("enabled") is False or any(field in validated_data for field in REVIEW_POLICY_FIELDS):+ if validated_data.get("enabled") is False or any(field in validated_data for field in MANAGER_FIELDS):return "manager"if validated_data.get("enabled") is True:return "editor"@@ -234,7 +238,7 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewreturnif level == "manager":raise PermissionDenied(- "Only a Stamphog manager can turn reviews off or change when they run. "+ "Only a Stamphog manager can turn reviews off, change when they run, or change reviewer requests. ""Ask an organization admin for manager access.")raise PermissionDenied(@@ -307,6 +311,18 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewfacade_api.disable_repo_config(self.canonical_team_id, str(pk))return Response(status=204)+ @extend_schema(+ description=(+ "Check whether the repository's default branch has a root owners.yaml. Reviewer requests "+ "(routing_mode) read the code owners from it. Makes one GitHub call, so ask only when needed."+ ),+ responses={200: StamphogOwnersFileSerializer},+ )+ @action(detail=True, methods=["GET"], url_path="owners_file", required_scopes=["stamphog:read"])+ def owners_file(self, request: Request, pk: UUID, **kwargs) -> Response:+ config = self._get_or_404(pk)+ return Response(StamphogOwnersFileSerializer({"owners_file": facade_api.check_owners_file(config)}).data)+@extend_schema(description=("List repositories from the project's connected GitHub installations that are not added to "diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.pyindex b7e3f817f095..0690376eae0f 100644--- a/products/stamphog/backend/tests/test_api.py+++ b/products/stamphog/backend/tests/test_api.py@@ -13,6 +13,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.constants import AvailableFeature+from posthog.egress.limiter.policies import Priorityfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKey, hash_key_value@@ -22,7 +23,14 @@ from posthog.models.utils import generate_random_token_personal, uuid7from products.access_control.backend.models.access_control import AccessControlfrom products.stamphog.backend.facade import contracts-from products.stamphog.backend.facade.enums import ChannelResolutionSource, DigestRunStatus, ReviewMode, ReviewRunStatus+from products.stamphog.backend.facade.enums import (+ ChannelResolutionSource,+ DigestRunStatus,+ ReviewMode,+ ReviewRunStatus,+ RoutingMode,+)+from products.stamphog.backend.facade.github import StamphogGitHubErrorfrom products.stamphog.backend.models import DigestRun, PullRequest, ReviewRun, StamphogInstallation, StamphogRepoConfigfrom products.stamphog.backend.presentation.serializers import StamphogRepoConfigWriteSerializerfrom products.stamphog.backend.presentation.views import _INSTALL_STATE_SALT@@ -77,6 +85,7 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):("enabled", {"enabled": False}),("review_mode", {"review_mode": ReviewMode.ALL}),("trigger_label", {"trigger_label": "review-me"}),+ ("routing_mode", {"routing_mode": RoutingMode.FALLBACK}),])def test_member_cannot_change_a_review_gating_field(self, _name: str, payload: dict) -> None:@@ -111,19 +120,26 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):@parameterized.expand([- ("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),+ ("names_the_review_mode", None, {"review_mode": ReviewMode.ALL}, status.HTTP_403_FORBIDDEN),+ ("turns_reviews_off", None, {"enabled": False}, status.HTTP_403_FORBIDDEN),+ ("turns_reviews_on", None, {"enabled": True}, status.HTTP_201_CREATED),+ ("leaves_the_defaults", None, {}, status.HTTP_201_CREATED),+ ("names_the_routing_mode", None, {"routing_mode": RoutingMode.FALLBACK}, status.HTTP_403_FORBIDDEN),+ (+ "manager_names_the_routing_mode",+ "manager",+ {"routing_mode": RoutingMode.FALLBACK},+ status.HTTP_201_CREATED,+ ),])def test_member_create_is_gated_only_when_it_names_a_review_field(- self, _name: str, extra: dict, expected_status: int+ self, _name: str, stamphog_level: str | None, extra: dict, expected_status: int) -> None:# Spelling out a review policy is the same decision whichever verb carries it, so create# gates on the field being present, like update does. Turning reviews on, or leaving the# fields out, stays an editor's job: the row binds disabled at sync and routes no digest.- self._login_as_member()+ self._login_as_member(stamphog_level=stamphog_level)response = self.client.post(self.url, {"repository": "PostHog/new", **extra}, format="json")@@ -143,16 +159,22 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDEN, response.contentassert StamphogRepoConfig.objects.unscoped().get(id=config_id).enabled is True- def test_member_granted_manager_can_change_a_review_gating_field(self) -> None:+ @parameterized.expand(+ [+ ("turns_reviews_off", {"enabled": False}),+ ("turns_reviewer_requests_on", {"routing_mode": RoutingMode.FALLBACK}),+ ]+ )+ def test_member_granted_manager_can_change_a_review_gating_field(self, _name: str, payload: dict) -> None:# An admin must be able to hand the review switch to somebody through the normal access# control settings, or the manager gate would be an admin-only hardcode.config_id = self._create_config()self._login_as_member(stamphog_level="manager")- response = self.client.patch(f"{self.url}{config_id}/", {"enabled": False}, format="json")+ response = self.client.patch(f"{self.url}{config_id}/", payload, format="json")assert response.status_code == status.HTTP_200_OK, response.content- assert response.json()["enabled"] is False+ assert {field: response.json()[field] for field in payload} == payload@parameterized.expand([@@ -243,6 +265,36 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):assert response.status_code == status.HTTP_200_OK, response.contentassert response.json()["user_access_level"] == expected+ @parameterized.expand(+ [+ # An answer is cached, so the second open costs no GitHub call.+ ("found", "inst-1", "version: 1\n", None, "found", 1),+ ("missing", "inst-1", None, None, "missing", 1),+ # A failed check hides the setting rather than offering it for a repository it cannot route, and asks again.+ ("github_error", "inst-1", None, StamphogGitHubError("boom", status_code=502), "unavailable", 2),+ ("no_installation", "", None, None, "unavailable", 0),+ ]+ )+ def test_owners_file_reports_whether_the_default_branch_has_one(+ self,+ _name: str,+ installation_id: str,+ text: str | None,+ error: Exception | None,+ expected: str,+ expected_reads: int,+ ) -> None:+ config_id = self._create_config()+ StamphogRepoConfig.objects.unscoped().filter(id=config_id).update(installation_id=installation_id)++ with patch(f"{_CLIENT}.get_default_branch_file", return_value=text, side_effect=error) as read_file:+ responses = [self.client.get(f"{self.url}{config_id}/owners_file/") for _ in range(2)]++ assert [response.status_code for response in responses] == [status.HTTP_200_OK] * 2+ assert [response.json() for response in responses] == [{"owners_file": expected}] * 2+ read = call("PostHog/posthog", "owners.yaml", priority=Priority.NORMAL)+ assert read_file.call_args_list == [read] * expected_reads+def test_create_ignores_client_supplied_installation_id(self) -> None:# installation_id is read-only: a manual create must not let a caller claim an installation# they haven't proven ownership of. Only the verified sync_installation flow may set it.@@ -984,7 +1036,8 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):# flags were set by someone who never proved GitHub access, so a member could otherwise pre-arm# enabled=True for a private repo and have reviews start the moment a teammate installs. The# review policy resets for the same reason: label mode pointed at a label nobody uses would- # go live, reviewing nothing, the moment a manager turns the row on.+ # go live, reviewing nothing, the moment a manager turns the row on. Routing does not wait for+ # the row to turn on, so a preset routing mode would request reviewers as soon as it binds.manual = StamphogRepoConfig.objects.unscoped().create(team_id=self.team.id,repository="PostHog/posthog",@@ -993,6 +1046,7 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):digest_enabled=True,review_mode=ReviewMode.ALL,trigger_label="nobody-uses-this",+ routing_mode=RoutingMode.ALWAYS,)response = self.client.post(self.url, {"installation_id": "42", "code": "oauth-code", "state": self.state}, format="json"@@ -1008,6 +1062,7 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):assert manual.digest_enabled is Falseassert manual.review_mode == ReviewMode.LABELassert manual.trigger_label == StamphogRepoConfig._meta.get_field("trigger_label").get_default()+ assert manual.routing_mode == RoutingMode.OFF@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories", return_value=["PostHog/posthog"])@patch(f"{_VIEWS}.user_can_access_installation", return_value=True)diff --git a/products/stamphog/frontend/activityDescriber.tsx b/products/stamphog/frontend/activityDescriber.tsxindex 5b672dce3d67..b53d55a88c35 100644--- a/products/stamphog/frontend/activityDescriber.tsx+++ b/products/stamphog/frontend/activityDescriber.tsx@@ -9,8 +9,9 @@ import {} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'-import { ReviewModeEnumApi } from './generated/api.schemas'+import { ReviewModeEnumApi, RoutingModeEnumApi } from './generated/api.schemas'import { REVIEW_MODE_LABELS } from './reviewModeLabels'+import { ROUTING_MODE_LABELS } from './routingModeLabels'// A GitHub installation webhook writes a system row, so the actor reads "PostHog". Say which// GitHub event caused it, or the reader cannot tell why reviews stopped.@@ -34,6 +35,17 @@ function repoConfigFieldCopy(change: ActivityChange): Description | null {</>)}+ case 'routing_mode': {+ const mode = String(change.after)+ if (mode === RoutingModeEnumApi.Off) {+ return <>turned reviewer requests off</>+ }+ return (+ <>+ set reviewer requests to <strong>{ROUTING_MODE_LABELS[mode as RoutingModeEnumApi] ?? mode}</strong>+ </>+ )+ }case 'trigger_label':return (<>diff --git a/products/stamphog/frontend/generated/api.schemas.ts b/products/stamphog/frontend/generated/api.schemas.tsindex 375233a075ed..e4269a3b130f 100644--- a/products/stamphog/frontend/generated/api.schemas.ts+++ b/products/stamphog/frontend/generated/api.schemas.ts@@ -165,6 +165,19 @@ export const ReviewModeEnumApi = {Label: 'label',} as const+/**+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve+ */+export type RoutingModeEnumApi = (typeof RoutingModeEnumApi)[keyof typeof RoutingModeEnumApi]++export const RoutingModeEnumApi = {+ Off: 'off',+ Always: 'always',+ Fallback: 'fallback',+} as const+export interface StamphogRepoConfigApi {readonly id: string/** SCM provider this config talks to. Defaults to 'github'. */@@ -184,8 +197,14 @@ export interface StamphogRepoConfigApi {readonly review_mode: ReviewModeEnumApi/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */trigger_label?: string+ /** When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' only when stamphog does not approve, where an approval requests only the owners of sensitive and new paths.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ readonly routing_mode: RoutingModeEnumApi/**- * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'editor' can turn reviews on. 'manager' is required to turn them off or to change review_mode or trigger_label.+ * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'editor' can turn reviews on. 'manager' is required to turn them off or to change review_mode, trigger_label or routing_mode.* @nullable*/readonly user_access_level: string | null@@ -230,6 +249,12 @@ export interface StamphogRepoConfigWriteApi {review_mode?: ReviewModeEnumApi/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */trigger_label?: string+ /** When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' only when stamphog does not approve, where an approval requests only the owners of sensitive and new paths.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ routing_mode?: RoutingModeEnumApi}/**@@ -260,6 +285,37 @@ export interface PatchedStamphogRepoConfigWriteApi {review_mode?: ReviewModeEnumApi/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */trigger_label?: string+ /** When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' only when stamphog does not approve, where an approval requests only the owners of sensitive and new paths.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ routing_mode?: RoutingModeEnumApi+}++/**+ * * `found` - Found+ * * `missing` - Missing+ * * `unavailable` - Unavailable+ */+export type OwnersFileStatusEnumApi = (typeof OwnersFileStatusEnumApi)[keyof typeof OwnersFileStatusEnumApi]++export const OwnersFileStatusEnumApi = {+ Found: 'found',+ Missing: 'missing',+ Unavailable: 'unavailable',+} as const++/**+ * Whether a repository can use reviewer requests, which read ownership from its owners.yaml.+ */+export interface StamphogOwnersFileApi {+ /** Whether the default branch has a root owners.yaml: 'found', 'missing', or 'unavailable' when the check could not ask GitHub (no installation, or GitHub answered with an error).+ *+ * * `found` - Found+ * * `missing` - Missing+ * * `unavailable` - Unavailable */+ owners_file: OwnersFileStatusEnumApi}/**diff --git a/products/stamphog/frontend/generated/api.ts b/products/stamphog/frontend/generated/api.tsindex a41d26f340f0..381c48904e85 100644--- a/products/stamphog/frontend/generated/api.ts+++ b/products/stamphog/frontend/generated/api.ts@@ -22,6 +22,7 @@ import type {StamphogAvailableRepositoriesApi,StamphogDigestRunsListParams,StamphogInstallInfoApi,+ StamphogOwnersFileApi,StamphogPullRequestApi,StamphogPullRequestsListParams,StamphogRepoConfigApi,@@ -257,6 +258,24 @@ export const stamphogRepoConfigsDestroy = async (})}+export const getStamphogRepoConfigsOwnersFileRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/stamphog/repo_configs/${id}/owners_file/`+}++/**+ * Check whether the repository's default branch has a root owners.yaml. Reviewer requests (routing_mode) read the code owners from it. Makes one GitHub call, so ask only when needed.+ */+export const stamphogRepoConfigsOwnersFileRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<StamphogOwnersFileApi> => {+ return apiMutator<StamphogOwnersFileApi>(getStamphogRepoConfigsOwnersFileRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getStamphogRepoConfigsAddRepositoryCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/stamphog/repo_configs/add_repository/`}diff --git a/products/stamphog/frontend/generated/api.zod.ts b/products/stamphog/frontend/generated/api.zod.tsindex ebff79642e05..3d8a547295c2 100644--- a/products/stamphog/frontend/generated/api.zod.ts+++ b/products/stamphog/frontend/generated/api.zod.ts@@ -32,6 +32,13 @@ export const StamphogRepoConfigsCreateBody = /* @__PURE__ */ zod.string().optional().describe("Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'."),+ routing_mode: zod+ .enum(['off', 'always', 'fallback'])+ .describe('\* `off` - Off\n\* `always` - Always\n\* `fallback` - When stamphog does not approve')+ .optional()+ .describe(+ "When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' only when stamphog does not approve, where an approval requests only the owners of sensitive and new paths.\n\n\* `off` - Off\n\* `always` - Always\n\* `fallback` - When stamphog does not approve"+ ),}).describe("Input shape for creating\/updating a repo config.\n\nSeparate from the read serializer because the contract is an output shape: it carries a\nrequired id, which a create request has no way to supply. Same split as visual_review's\ninput serializers.\n\ninstallation_id is deliberately absent: it may only ever be set by the verified\nsync_installation flow, which proves the caller owns the installation before binding it. A\nclient-supplied value on this path is ignored, so a manually created config carries no\ninstallation and simply won't resolve webhooks until synced."@@ -60,6 +67,13 @@ export const StamphogRepoConfigsUpdateBody = /* @__PURE__ */ zod.string().optional().describe("Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'."),+ routing_mode: zod+ .enum(['off', 'always', 'fallback'])+ .describe('\* `off` - Off\n\* `always` - Always\n\* `fallback` - When stamphog does not approve')+ .optional()+ .describe(+ "When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' only when stamphog does not approve, where an approval requests only the owners of sensitive and new paths.\n\n\* `off` - Off\n\* `always` - Always\n\* `fallback` - When stamphog does not approve"+ ),}).describe("Input shape for creating\/updating a repo config.\n\nSeparate from the read serializer because the contract is an output shape: it carries a\nrequired id, which a create request has no way to supply. Same split as visual_review's\ninput serializers.\n\ninstallation_id is deliberately absent: it may only ever be set by the verified\nsync_installation flow, which proves the caller owns the installation before binding it. A\nclient-supplied value on this path is ignored, so a manually created config carries no\ninstallation and simply won't resolve webhooks until synced."@@ -88,6 +102,13 @@ export const StamphogRepoConfigsPartialUpdateBody = /* @__PURE__ */ zod.string().optional().describe("Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'."),+ routing_mode: zod+ .enum(['off', 'always', 'fallback'])+ .describe('\* `off` - Off\n\* `always` - Always\n\* `fallback` - When stamphog does not approve')+ .optional()+ .describe(+ "When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' only when stamphog does not approve, where an approval requests only the owners of sensitive and new paths.\n\n\* `off` - Off\n\* `always` - Always\n\* `fallback` - When stamphog does not approve"+ ),}).describe("Input shape for creating\/updating a repo config.\n\nSeparate from the read serializer because the contract is an output shape: it carries a\nrequired id, which a create request has no way to supply. Same split as visual_review's\ninput serializers.\n\ninstallation_id is deliberately absent: it may only ever be set by the verified\nsync_installation flow, which proves the caller owns the installation before binding it. A\nclient-supplied value on this path is ignored, so a manually created config carries no\ninstallation and simply won't resolve webhooks until synced."diff --git a/products/stamphog/frontend/routingModeLabels.ts b/products/stamphog/frontend/routingModeLabels.tsnew file mode 100644index 000000000000..6e890f1dd86b--- /dev/null+++ b/products/stamphog/frontend/routingModeLabels.ts@@ -0,0 +1,8 @@+import { RoutingModeEnumApi } from './generated/api.schemas'++// The repo settings and the activity log both name when reviewer requests run, so they read from one map.+export const ROUTING_MODE_LABELS: Record<RoutingModeEnumApi, string> = {+ [RoutingModeEnumApi.Off]: 'Off',+ [RoutingModeEnumApi.Fallback]: "When Stamphog doesn't approve",+ [RoutingModeEnumApi.Always]: 'On every pull request',+}diff --git a/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsx b/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsxindex a6d5e8e10886..edc1b2d45d68 100644--- a/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsx+++ b/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsx@@ -1,15 +1,29 @@import { useActions, useValues } from 'kea'-import { LemonSelect, LemonSwitch, Tooltip } from '@posthog/lemon-ui'+import { LemonDivider, LemonSelect, LemonSwitch, Tooltip } from '@posthog/lemon-ui'import { EditableField } from 'lib/components/EditableField/EditableField'import { toAccessControlLevel } from 'lib/utils/accessControlUtils'-import { ReviewModeEnumApi, type StamphogRepoConfigApi } from '../../generated/api.schemas'+import {+ OwnersFileStatusEnumApi,+ ReviewModeEnumApi,+ RoutingModeEnumApi,+ type StamphogRepoConfigApi,+} from '../../generated/api.schemas'import { REVIEW_MODE_LABELS } from '../../reviewModeLabels'import { editorDisabledReason, managerDisabledReason } from './repoAccess'+import { ReviewerRequestSettings } from './ReviewerRequestSettings'import { stamphogSceneLogic } from './stamphogSceneLogic'+const REVIEWER_REQUESTS_DESCRIPTION =+ 'Asks the code owners in owners.yaml to review. Owners with a trivial part of the change are left out, and a comment on the pull request says why.'++const REVIEWER_REQUESTS_MODE_DESCRIPTION: Partial<Record<RoutingModeEnumApi, string>> = {+ [RoutingModeEnumApi.Fallback]: 'After a Stamphog approval, only the owners of sensitive and new paths are asked.',+ [RoutingModeEnumApi.Always]: 'Owners are asked as soon as a pull request is ready for review.',+}+function Section({title,description,@@ -100,10 +114,15 @@ function TriggerSettings({}export function ExpandedRepoSettings({ repo }: { repo: StamphogRepoConfigApi }): JSX.Element {- const { updatingRepoIds } = useValues(stamphogSceneLogic)+ const { updatingRepoIds, ownersFileChecks } = useValues(stamphogSceneLogic)const { updateRepoConfig } = useActions(stamphogSceneLogic)const level = toAccessControlLevel(repo.user_access_level)const updatingReason = updatingRepoIds.includes(repo.id) ? 'Updating' : undefined+ const ownersFile = ownersFileChecks[repo.id]+ const routingMode = repo.routing_mode ?? RoutingModeEnumApi.Off+ // Requests read every owner from owners.yaml, so a repository without one is not offered them. A repository+ // that has them on keeps the setting in view, so it can be turned off.+ const showReviewerRequests = routingMode !== RoutingModeEnumApi.Off || ownersFile === OwnersFileStatusEnumApi.Foundreturn (<div className="@container pl-2 pr-4 py-4">@@ -151,6 +170,30 @@ export function ExpandedRepoSettings({ repo }: { repo: StamphogRepoConfigApi }):/></Section></div>+ {showReviewerRequests && (+ <>+ <LemonDivider className="my-4" />+ <div className="grid grid-cols-1 @2xl:grid-cols-3 gap-x-8">+ <div className="@2xl:col-span-2">+ <Section+ title="Reviewer requests"+ description={[+ REVIEWER_REQUESTS_DESCRIPTION,+ REVIEWER_REQUESTS_MODE_DESCRIPTION[routingMode],+ ]+ .filter(Boolean)+ .join(' ')}+ >+ <ReviewerRequestSettings+ repo={repo}+ ownersFile={ownersFile}+ updatingReason={updatingReason}+ />+ </Section>+ </div>+ </div>+ </>+ )}</div>)}diff --git a/products/stamphog/frontend/scenes/StamphogScene/ReviewerRequestSettings.tsx b/products/stamphog/frontend/scenes/StamphogScene/ReviewerRequestSettings.tsxnew file mode 100644index 000000000000..497d4e3ea646--- /dev/null+++ b/products/stamphog/frontend/scenes/StamphogScene/ReviewerRequestSettings.tsx@@ -0,0 +1,92 @@+import { useActions } from 'kea'++import { IconCheckCircle, IconWarning } from '@posthog/icons'+import { LemonSelect, LemonSwitch, Spinner } from '@posthog/lemon-ui'++import { toAccessControlLevel } from 'lib/utils/accessControlUtils'++import { OwnersFileStatusEnumApi, RoutingModeEnumApi, type StamphogRepoConfigApi } from '../../generated/api.schemas'+import { ROUTING_MODE_LABELS } from '../../routingModeLabels'+import { managerDisabledReason } from './repoAccess'+import { type OwnersFileCheck, stamphogSceneLogic } from './stamphogSceneLogic'++function OwnersFileState({ ownersFile }: { ownersFile: OwnersFileCheck | undefined }): JSX.Element {+ switch (ownersFile) {+ case OwnersFileStatusEnumApi.Found:+ return (+ <span className="flex items-center gap-1 text-success text-sm" data-attr="stamphog-owners-file-found">+ <IconCheckCircle />+ owners.yaml found+ </span>+ )+ case OwnersFileStatusEnumApi.Missing:+ return (+ <span className="flex items-center gap-1 text-warning text-sm">+ <IconWarning />+ No owners.yaml on the default branch, so nobody gets a review request.+ </span>+ )+ case OwnersFileStatusEnumApi.Unavailable:+ return (+ <span className="text-secondary text-sm">Couldn't check for owners.yaml. Reopen the row to retry.</span>+ )+ default:+ return (+ <span className="flex items-center gap-1 text-secondary text-sm">+ <Spinner />+ Checking for owners.yaml+ </span>+ )+ }+}++export function ReviewerRequestSettings({+ repo,+ ownersFile,+ updatingReason,+}: {+ repo: StamphogRepoConfigApi+ ownersFile: OwnersFileCheck | undefined+ updatingReason?: string+}): JSX.Element {+ const { updateRepoConfig } = useActions(stamphogSceneLogic)+ // Turning requests on asks teams on every pull request, and turning them off can leave pull requests+ // with no reviewer, so both directions take manager.+ const disabledReason = managerDisabledReason(toAccessControlLevel(repo.user_access_level)) ?? updatingReason+ const mode = repo.routing_mode ?? RoutingModeEnumApi.Off+ const on = mode !== RoutingModeEnumApi.Off++ return (+ <div className="flex flex-col gap-2">+ <OwnersFileState ownersFile={ownersFile} />+ <div className="flex flex-wrap items-center gap-2">+ <LemonSwitch+ label="Request reviewers"+ checked={on}+ disabledReason={disabledReason}+ // Waiting for the verdict is the default, because an approval then asks only the owners+ // of sensitive and new paths.+ onChange={(checked) =>+ updateRepoConfig(repo.id, {+ routing_mode: checked ? RoutingModeEnumApi.Fallback : RoutingModeEnumApi.Off,+ })+ }+ data-attr="stamphog-repo-reviewer-requests-toggle"+ />+ {on && (+ <LemonSelect+ size="small"+ value={mode}+ disabledReason={disabledReason}+ onChange={(routingMode) => updateRepoConfig(repo.id, { routing_mode: routingMode })}+ options={[RoutingModeEnumApi.Fallback, RoutingModeEnumApi.Always].map((value) => ({+ value,+ label: ROUTING_MODE_LABELS[value],+ }))}+ data-attr="stamphog-repo-reviewer-requests-mode"+ />+ )}+ </div>+ </div>+ )+}diff --git a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.stories.tsx b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.stories.tsxindex fd75970371eb..3ac5270198ff 100644--- a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.stories.tsx+++ b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.stories.tsx@@ -20,6 +20,7 @@ const repoConfig = (index: number, overrides: Partial<StamphogRepoConfigApi>): Sinstallation_id: '1',review_mode: 'all',trigger_label: 'stamphog',+ routing_mode: 'off',user_access_level: 'manager',created_at: '2026-07-01T00:00:00Z',updated_at: '2026-07-01T00:00:00Z',@@ -51,6 +52,8 @@ const repoConfigs = page([repoConfig(4, { repository: 'PostHog/hogland', enabled: false, created_at: '2026-08-12T00:00:00Z' }),])+const OWNERS_FILE_URL = '/api/projects/:team_id/stamphog/repo_configs/:id/owners_file/'+const availableRepositories: StamphogAvailableRepositoriesApi = {repositories: ['PostHog/charts', 'PostHog/plugin-server', 'PostHog/posthog-python', 'PostHog/wizard'],total_count: 4,@@ -89,6 +92,8 @@ const meta: Meta = {install_url: 'https://github.com/apps/stamphog/installations/new',authorize_url: 'https://github.com/login/oauth/authorize',},+ // Without owners.yaml the expanded row offers no reviewer requests.+ [OWNERS_FILE_URL]: { owners_file: 'missing' },},}),],@@ -97,22 +102,22 @@ export default metaexport const RepositoriesList: StoryObj = {}-async function expandLabelRow(canvasElement: HTMLElement): Promise<void> {- const labelRow = (await within(canvasElement).findByText('posthog-js', {}, { timeout: 15000 })).closest('tr')- await userEvent.click(within(labelRow!).getByTitle('Show more'))- await within(canvasElement).findByText('Daily digest')+async function expandRow(canvasElement: HTMLElement, name: string, shownText: string): Promise<void> {+ const row = (await within(canvasElement).findByText(name, {}, { timeout: 15000 })).closest('tr')+ await userEvent.click(within(row!).getByTitle('Show more'))+ await within(canvasElement).findByText(shownText)}// Expands the label-triggered row, the only one that shows the trigger label.export const RepositoryExpanded: StoryObj = {play: async ({ canvasElement }) => {- await expandLabelRow(canvasElement)+ await expandRow(canvasElement, 'posthog-js', 'Daily digest')},}export const TriggerLabelEditing: StoryObj = {play: async ({ canvasElement }) => {- await expandLabelRow(canvasElement)+ await expandRow(canvasElement, 'posthog-js', 'Daily digest')await userEvent.click(within(canvasElement).getByTitle('Edit'))await within(canvasElement).findByText('Save')},@@ -175,3 +180,46 @@ export const ConnectedAfterSync: StoryObj = {}),],}++// The default branch has owners.yaml, so the row offers reviewer requests, off until a manager turns them on.+export const ReviewerRequestsOffered: StoryObj = {+ parameters: { testOptions: { snapshotBrowsers: [] } },+ decorators: [mswDecorator({ get: { [OWNERS_FILE_URL]: { owners_file: 'found' } } })],+ play: async ({ canvasElement }) => {+ await expandRow(canvasElement, 'posthog', 'owners.yaml found')+ },+}++export const ReviewerRequestsOn: StoryObj = {+ parameters: { testOptions: { snapshotBrowsers: [] } },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/stamphog/repo_configs/': page([+ repoConfig(1, { repository: 'PostHog/posthog', digest_enabled: true, routing_mode: 'fallback' }),+ ]),+ [OWNERS_FILE_URL]: { owners_file: 'found' },+ },+ }),+ ],+ play: async ({ canvasElement }) => {+ await expandRow(canvasElement, 'posthog', 'owners.yaml found')+ },+}++// Requests stay in view after owners.yaml goes away, so a manager can see why nobody is asked and turn them off.+export const ReviewerRequestsWithoutOwnersFile: StoryObj = {+ parameters: { testOptions: { snapshotBrowsers: [] } },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/stamphog/repo_configs/': page([+ repoConfig(1, { repository: 'PostHog/posthog', routing_mode: 'always' }),+ ]),+ },+ }),+ ],+ play: async ({ canvasElement }) => {+ await expandRow(canvasElement, 'posthog', 'Reviewer requests')+ },+}diff --git a/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts b/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.tsindex a90f8c10b1dd..19f0193feee6 100644--- a/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts+++ b/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts@@ -16,17 +16,19 @@ import {stamphogRepoConfigsAvailableRepositoriesRetrieve,stamphogRepoConfigsInstallInfoRetrieve,stamphogRepoConfigsList,+ stamphogRepoConfigsOwnersFileRetrieve,stamphogRepoConfigsPartialUpdate,stamphogRepoConfigsSyncInstallationCreate,} from '../../generated/api'-import type {- PatchedStamphogRepoConfigWriteApi,- StamphogAvailableRepositoriesApi,- StamphogDiscoveredInstallationApi,- StamphogInstallInfoApi,- StamphogRepoConfigApi,- StamphogSyncInstallationRequestApi,- StamphogSyncInstallationResponseApi,+import {+ OwnersFileStatusEnumApi,+ type PatchedStamphogRepoConfigWriteApi,+ type StamphogAvailableRepositoriesApi,+ type StamphogDiscoveredInstallationApi,+ type StamphogInstallInfoApi,+ type StamphogRepoConfigApi,+ type StamphogSyncInstallationRequestApi,+ type StamphogSyncInstallationResponseApi,} from '../../generated/api.schemas'import { editorDisabledReason } from './repoAccess'@@ -41,6 +43,9 @@ const REPO_CONFIGS_PAGE_SIZE = 1000const AVAILABLE_REPOSITORIES_LIMIT = 50const AVAILABLE_SEARCH_DEBOUNCE_MS = 300+// 'checking' while the request is in flight. A repository nobody expanded yet has no entry at all.+export type OwnersFileCheck = OwnersFileStatusEnumApi | 'checking'+function sortByRepository(repos: StamphogRepoConfigApi[]): StamphogRepoConfigApi[] {return [...repos].sort((a, b) => a.repository.localeCompare(b.repository))}@@ -83,6 +88,7 @@ export interface stamphogSceneLogicValues {installInfoLoading: booleaninstallUrl: stringopeningInstallPage: boolean+ ownersFileChecks: Record<string, OwnersFileCheck>refreshingFromGitHub: booleanrepoConfigs: StamphogRepoConfigApi[]repoConfigsFailed: boolean@@ -109,6 +115,9 @@ export interface stamphogSceneLogicActions {addRepositorySuccess: (config: StamphogRepoConfigApi) => {config: StamphogRepoConfigApi}+ checkOwnersFile: (id: string) => {+ id: string+ }connectInstallation: (installationId: string) => {installationId: string}@@ -175,6 +184,13 @@ export interface stamphogSceneLogicActions {openInstallPageFailed: () => {value: true}+ ownersFileChecked: (+ id: string,+ status: OwnersFileStatusEnumApi+ ) => {+ id: string+ status: OwnersFileStatusEnumApi+ }refreshFromGitHub: () => {value: true}@@ -318,6 +334,8 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([addRepository: true,addRepositorySuccess: (config: StamphogRepoConfigApi) => ({ config }),addRepositoryFailure: true,+ checkOwnersFile: (id: string) => ({ id }),+ ownersFileChecked: (id: string, status: OwnersFileStatusEnumApi) => ({ id, status }),}),loaders(({ values }) => ({@@ -504,6 +522,14 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([refreshFromGitHubFailed: () => false,},],+ // The check costs a GitHub call, so each repository asks once per page load, when it first expands.+ ownersFileChecks: [+ {} as Record<string, OwnersFileCheck>,+ {+ checkOwnersFile: (state, { id }) => ({ ...state, [id]: 'checking' }),+ ownersFileChecked: (state, { id, status }) => ({ ...state, [id]: status }),+ },+ ],}),selectors({@@ -599,6 +625,7 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([review_mode: patch.review_mode,enabled: patch.enabled,digest_enabled: patch.digest_enabled,+ routing_mode: patch.routing_mode,})} catch {lemonToast.error('Failed to update repository')@@ -612,6 +639,21 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([}}},+ setRepoExpanded: ({ id, expanded }) => {+ const check = values.ownersFileChecks[id]+ // A failed check asks again on the next expand. Any other answer holds for the page load.+ if (expanded && (check === undefined || check === OwnersFileStatusEnumApi.Unavailable)) {+ actions.checkOwnersFile(id)+ }+ },+ checkOwnersFile: async ({ id }) => {+ try {+ const response = await stamphogRepoConfigsOwnersFileRetrieve(String(values.currentProjectId), id)+ actions.ownersFileChecked(id, response.owners_file)+ } catch {+ actions.ownersFileChecked(id, OwnersFileStatusEnumApi.Unavailable)+ }+ },triggerLabelEditStarted: ({ id }) => {posthog.capture('stamphog trigger label edit started', { repo_config_id: id })},@@ -636,9 +678,11 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([actions.addRepositoryFailure()}},- addRepositorySuccess: () => {+ addRepositorySuccess: ({ config }) => {actions.loadRepoConfigs()actions.loadAvailableRepositories({ search: '' })+ // An added repository opens by itself, without the expand that asks for the check.+ actions.checkOwnersFile(config.id)},connectInstallation: async ({ installationId }) => {sessionStorage.setItem(PENDING_INSTALLATION_STORAGE_KEY, installationId)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8ec4e05f695d..7fceaff1fd57 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -69635,6 +69635,20 @@ export namespace Schemas {NeedsAttention: 'needs_attention',} as const;+ /**+ * * `found` - Found+ * * `missing` - Missing+ * * `unavailable` - Unavailable+ */+ export type OwnersFileStatusEnum = typeof OwnersFileStatusEnum[keyof typeof OwnersFileStatusEnum];+++ export const OwnersFileStatusEnum = {+ Found: 'found',+ Missing: 'missing',+ Unavailable: 'unavailable',+ } as const;+export interface WorkflowCost {/** GitHub Actions workflow name this cost is for. */workflow_name: string;@@ -74503,6 +74517,20 @@ export namespace Schemas {Label: 'label',} as const;+ /**+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve+ */+ export type RoutingModeEnum = typeof RoutingModeEnum[keyof typeof RoutingModeEnum];+++ export const RoutingModeEnum = {+ Off: 'off',+ Always: 'always',+ Fallback: 'fallback',+ } as const;+export interface StamphogRepoConfig {readonly id: string;/** SCM provider this config talks to. Defaults to 'github'. */@@ -74522,8 +74550,14 @@ export namespace Schemas {readonly review_mode: ReviewModeEnum;/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */trigger_label?: string;+ /** When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' only when stamphog does not approve, where an approval requests only the owners of sensitive and new paths.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ readonly routing_mode: RoutingModeEnum;/**- * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'editor' can turn reviews on. 'manager' is required to turn them off or to change review_mode or trigger_label.+ * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'editor' can turn reviews on. 'manager' is required to turn them off or to change review_mode, trigger_label or routing_mode.* @nullable*/readonly user_access_level: string | null;@@ -86350,6 +86384,12 @@ export namespace Schemas {review_mode?: ReviewModeEnum;/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */trigger_label?: string;+ /** When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' only when stamphog does not approve, where an approval requests only the owners of sensitive and new paths.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ routing_mode?: RoutingModeEnum;}export type PatchedSubscriptionWriteContextsItem = {@@ -107386,6 +107426,18 @@ export namespace Schemas {readonly authorize_url: string;}+ /**+ * Whether a repository can use reviewer requests, which read ownership from its owners.yaml.+ */+ export interface StamphogOwnersFile {+ /** Whether the default branch has a root owners.yaml: 'found', 'missing', or 'unavailable' when the check could not ask GitHub (no installation, or GitHub answered with an error).+ *+ * * `found` - Found+ * * `missing` - Missing+ * * `unavailable` - Unavailable */+ owners_file: OwnersFileStatusEnum;+ }+/*** Input shape for creating/updating a repo config.*@@ -107414,6 +107466,12 @@ export namespace Schemas {review_mode?: ReviewModeEnum;/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */trigger_label?: string;+ /** When stamphog requests reviews from the code owners in the repository's owners.yaml: 'off' (the default) never; 'always' when a pull request opens ready for review or is marked ready; 'fallback' only when stamphog does not approve, where an approval requests only the owners of sensitive and new paths.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ routing_mode?: RoutingModeEnum;}/**