: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): show stamphog routing state per pr and the deciding owners file (#130732)
Julian Bez34629debc5f1
diff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex 0980ab77bd95..b49f415712f3 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -206,9 +206,11 @@ Turn routing on first, then set the variable. To roll back, delete the variableThe 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.Routing never writes `payload_updated_at` or the descriptive fields of the row, so it cannot make the review path drop a delivery as stale.+`GET pull_requests/` and `stamphog-pull-requests-list` return an allowlist of that record as `routing` (status, head, mode, trigger, scope, timestamps, the routed heads, and `claim_expired`), next to the repository's `routing_mode` now. The plan, the pins and the pending comment stay internal.Each run that makes its requests is also recorded, append-only, in `RoutingRun` with one `RoutingRunOwner` row per owner: what the run did with the owner (`outcome`), why (`reason`), the model's one-line reason when it proposed a cut, also when a guard kept the owner, and every changed file the owner owns, without patches.owners.yaml and the pull request both change after the run, so the run keeps its own copy of the file list, and `owners_sha` names the default-branch commit whose owners.yaml files decided the owners.+Each file also keeps `owners_source`, the ownership file whose `owners` list named the owner for it. An owner that only an additions declaration made a candidate has none, because additions collect from every file on the walk.The plan decides each owner's outcome and reason. The rows are written after the `requested` record is saved, so a failed log write only logs and never makes the task request again.Read them with `GET routing_runs/` (filters `repository`, `pr_number`, `owner`, `outcome`, `reason`, `head_sha`, `created_after`, `created_before`) or the `stamphog-routing-runs-list` MCP tool.`outcome` and `reason` match the same owner as `owner`, so `owner=team-devex&outcome=cut` lists the runs that cut team-devex.diff --git a/products/stamphog/backend/facade/api.py b/products/stamphog/backend/facade/api.pyindex bc324c2a980c..c0d76183725f 100644--- a/products/stamphog/backend/facade/api.py+++ b/products/stamphog/backend/facade/api.py@@ -23,6 +23,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.claims import is_stale_claimfrom ..logic.routing.owners_file import owners_file_statusfrom ..logic.scrubbing import neutralize_active_markdown, scrub_credentialsfrom ..models import (@@ -51,6 +52,7 @@ from .enums import (RoutingOwnerOutcome,RoutingOwnerReason,RoutingScope,+ RoutingStatus,)logger = structlog.get_logger(__name__)@@ -107,6 +109,41 @@ def _repo_config_to_dto(obj: StamphogRepoConfig) -> contracts.RepoConfigDTO:)+def _record_time(value: object) -> datetime | None:+ if not isinstance(value, str):+ return None+ try:+ return datetime.fromisoformat(value)+ except ValueError:+ return None+++def _routing_to_dto(record: object) -> contracts.PullRequestRoutingDTO | None:+ """An allowlist of the routing record's scalars. The plan, the pins and the comment stay internal."""+ if not isinstance(record, dict):+ return None+ try:+ status = RoutingStatus(str(record.get("status")))+ mode = RoutingMode(str(record.get("mode")))+ scope = RoutingScope(record["scope"]) if record.get("scope") else None+ except ValueError:+ return None+ claimed = status in (RoutingStatus.ROUTING, RoutingStatus.REQUESTED)+ return contracts.PullRequestRoutingDTO(+ status=status,+ head_sha=str(record.get("head_sha") or ""),+ mode=mode,+ trigger=str(record.get("trigger") or ""),+ scope=scope,+ claim_expired=claimed and is_stale_claim(record),+ waiting_since=_record_time(record.get("waiting_since")),+ claimed_at=_record_time(record.get("claimed_at")),+ routed_at=_record_time(record.get("routed_at")),+ full_routed_head=str(record.get("full_routed_head") or ""),+ pinned_routed_head=str(record.get("pinned_routed_head") or ""),+ )++def _pull_request_to_dto(obj: PullRequest) -> contracts.PullRequestDTO:return contracts.PullRequestDTO(id=obj.id,@@ -125,6 +162,8 @@ def _pull_request_to_dto(obj: PullRequest) -> contracts.PullRequestDTO:merge_commit_sha=obj.merge_commit_sha,merged_at=obj.merged_at,posted_comment_id=obj.posted_comment_id,+ routing_mode=RoutingMode(obj.repo_config.routing_mode),+ routing=_routing_to_dto(obj.routing),created_at=obj.created_at,updated_at=obj.updated_at,)@@ -646,6 +685,8 @@ def _routing_owner_to_dto(row: RoutingRunOwner, *, with_files: bool) -> contractstatus=file["status"],additions=file["additions"],deletions=file["deletions"],+ # Runs recorded before the field have no entry.+ owners_source=file.get("owners_source"),)for file in (row.files if with_files else [])],diff --git a/products/stamphog/backend/facade/contracts.py b/products/stamphog/backend/facade/contracts.pyindex fa9a8bcc4056..54caccafb584 100644--- a/products/stamphog/backend/facade/contracts.py+++ b/products/stamphog/backend/facade/contracts.py@@ -30,6 +30,7 @@ from .enums import (RoutingOwnerOutcome,RoutingOwnerReason,RoutingScope,+ RoutingStatus,)@@ -71,6 +72,24 @@ class AddRepositoryResultDTO:created: bool+@dataclass(frozen=True)+class PullRequestRoutingDTO:+ """The latest reviewer routing record of a pull request: its phase, never its plan."""++ status: RoutingStatus+ head_sha: str+ mode: RoutingMode+ trigger: str+ scope: RoutingScope | None = None+ # A claim this old may be taken over, which does not prove that its task died.+ claim_expired: bool = False+ waiting_since: datetime | None = None+ claimed_at: datetime | None = None+ routed_at: datetime | None = None+ full_routed_head: str = ""+ pinned_routed_head: str = ""++@dataclass(frozen=True)class PullRequestDTO:"""A pull request stamphog knows about, including merge state once it merges."""@@ -91,6 +110,8 @@ class PullRequestDTO:merge_commit_sha: str = ""merged_at: datetime | None = Noneposted_comment_id: int | None = None+ routing_mode: RoutingMode = RoutingMode.OFF+ routing: PullRequestRoutingDTO | None = Nonecreated_at: datetime | None = Noneupdated_at: datetime | None = None@@ -168,6 +189,7 @@ class RoutingFileDTO:status: str = ""additions: int = 0deletions: int = 0+ owners_source: str | None = None@dataclass(frozen=True)diff --git a/products/stamphog/backend/facade/enums.py b/products/stamphog/backend/facade/enums.pyindex a22b5dd95100..5ec1c5c7e145 100644--- a/products/stamphog/backend/facade/enums.py+++ b/products/stamphog/backend/facade/enums.py@@ -28,6 +28,18 @@ class RoutingMode(LabeledStrEnum):FALLBACK = "fallback", "When stamphog does not approve"+class RoutingStatus(LabeledStrEnum):+ """The phase of a pull request's latest reviewer routing record."""++ # FALLBACK only: the head waits for stamphog's verdict or for the safety net.+ WAITING = "waiting", "Waiting for stamphog's verdict"+ # A task holds the claim and has not requested anybody yet.+ ROUTING = "routing", "Routing"+ # The review requests went out and the routing comment is not finished yet.+ REQUESTED = "requested", "Requested"+ DONE = "done", "Done"++class OwnersFileStatus(LabeledStrEnum):"""Whether a repository's default branch has the root owners.yaml that reviewer routing reads."""diff --git a/products/stamphog/backend/logic/routing/candidates.py b/products/stamphog/backend/logic/routing/candidates.pyindex 1ddf0886c7a0..2ed9819ac467 100644--- a/products/stamphog/backend/logic/routing/candidates.py+++ b/products/stamphog/backend/logic/routing/candidates.py@@ -7,6 +7,7 @@ path and owners of additions are pinned: the cut step never removes them (SPEC sfrom __future__ import annotationsfrom collections.abc import Iterable, Mapping, Sequence+from dataclasses import fieldfrom pathlib import PurePosixPathfrom owners_yaml import Resolution, path_matches_pattern@@ -101,6 +102,10 @@ class OwnerCandidate:kind: OwnerKindfiles: tuple[ChangedFile, ...]pins: frozenset[Pin]+ # Changed path -> the ownership file whose `owners` list names this owner for it. A path the owner+ # reached only through an additions declaration has no entry, because additions collect from every+ # file on the walk and no single file decides them.+ owners_sources: Mapping[str, str] = field(default_factory=dict)@propertydef lines(self) -> int:@@ -148,14 +153,19 @@ class _CandidateCollector:def __init__(self) -> None:self._files: dict[str, dict[str, ChangedFile]] = {}self._pins: dict[str, set[Pin]] = {}+ self._sources: dict[str, dict[str, str]] = {}- def add(self, owner: str, file: ChangedFile, pin: Pin | None = None) -> None:+ def add(self, owner: str, file: ChangedFile, *, pin: Pin | None = None, source: str | None = None) -> None:if not owner:returnself._files.setdefault(owner, {})[file.path] = filepins = self._pins.setdefault(owner, set())if pin is not None:pins.add(pin)+ sources = self._sources.setdefault(owner, {})+ # The first file that names the owner wins. The plain ownership of the path is collected first.+ if source and file.path not in sources:+ sources[file.path] = sourcedef candidates(self) -> list[OwnerCandidate]:return [@@ -164,6 +174,7 @@ class _CandidateCollector:kind=_owner_kind(owner),files=tuple(files.values()),pins=frozenset(self._pins[owner]),+ owners_sources=self._sources[owner],)for owner, files in self._files.items()]@@ -173,7 +184,7 @@ def _collect_owned(collector: _CandidateCollector, file: ChangedFile, resolutionif resolution is None or is_excluded(file.path) or _is_generated_or_vendored(file.path, resolution):returnfor owner in resolution.owners or []:- collector.add(owner, file)+ collector.add(owner, file, source=resolution.source)def _collect_additions(collector: _CandidateCollector, file: ChangedFile, resolution: Resolution | None) -> None:@@ -186,7 +197,7 @@ def _collect_additions(collector: _CandidateCollector, file: ChangedFile, resolureturnpin = Pin(reason=PinReason.NEW_PATH, path=resolution.added.path)for owner in resolution.added.additions:- collector.add(owner, file, pin)+ collector.add(owner, file, pin=pin)def _collect_sensitive(@@ -200,7 +211,7 @@ def _collect_sensitive(continuepin = Pin(reason=PinReason.SENSITIVE, path=path)for owner in resolution.owners or []:- collector.add(owner, file, pin)+ collector.add(owner, file, pin=pin, source=resolution.source)def find_candidates(files: Sequence[ChangedFile], resolutions: Mapping[str, Resolution]) -> tuple[OwnerCandidate, ...]:diff --git a/products/stamphog/backend/logic/routing/claims.py b/products/stamphog/backend/logic/routing/claims.pynew file mode 100644index 000000000000..3a2028feab6e--- /dev/null+++ b/products/stamphog/backend/logic/routing/claims.py@@ -0,0 +1,23 @@+"""When a reviewer routing claim on `PullRequest.routing` counts as abandoned.++Kept apart from the routing service, so the facade can report a claim's age without importing the+GitHub, model and ownership clients that a routing run needs.+"""++from __future__ import annotations++from collections.abc import Mapping+from datetime import UTC, datetime, timedelta+from typing import Any++# A claim older than this counts as abandoned, so a task that died does not block the pull request+# for good. It sits far above the time a task needs to finish, retries included.+CLAIM_STALE_AFTER = timedelta(hours=2)+++def is_stale_claim(record: Mapping[str, Any]) -> bool:+ try:+ claimed_at = datetime.fromisoformat(str(record.get("claimed_at") or ""))+ except ValueError:+ return True+ return datetime.now(UTC) - claimed_at > CLAIM_STALE_AFTERdiff --git a/products/stamphog/backend/logic/routing/service.py b/products/stamphog/backend/logic/routing/service.pyindex 1d56101d5223..309631c51ae7 100644--- a/products/stamphog/backend/logic/routing/service.py+++ b/products/stamphog/backend/logic/routing/service.py@@ -15,7 +15,7 @@ from __future__ import annotationsimport timefrom collections.abc import Mapping, Sequence-from datetime import UTC, datetime, timedelta+from datetime import UTC, datetimefrom typing import Anyfrom django.db import router@@ -36,6 +36,7 @@ from products.stamphog.backend.facade.enums import (RoutingOwnerOutcome,RoutingOwnerReason,RoutingScope,+ RoutingStatus,)from products.stamphog.backend.logic.github_client import StamphogGitHubClientfrom products.stamphog.backend.logic.routing.candidates import (@@ -44,6 +45,7 @@ from products.stamphog.backend.logic.routing.candidates import (find_candidates,paths_to_resolve,)+from products.stamphog.backend.logic.routing.claims import is_stale_claimfrom products.stamphog.backend.logic.routing.comment import (ROUTING_COMMENT_MARKER,render_approved_routing_comment,@@ -58,19 +60,15 @@ from products.stamphog.backend.models import PullRequest, StamphogRepoConfiglogger = structlog.get_logger(__name__)ROUTING_EVENT = "stamphog_reviewer_routing_completed"-# FALLBACK only: the head waits for stamphog's verdict or for the safety net, whichever comes first.-STATUS_WAITING = "waiting"+STATUS_WAITING = RoutingStatus.WAITING.value# A task claimed the pull request and its routing is running. The record holds the plan once# `planned_at` is set, and the plan is saved before any GitHub write.-STATUS_ROUTING = "routing"+STATUS_ROUTING = RoutingStatus.ROUTING.value# A record stays REQUESTED between the review requests and the comment, so a retry finishes the# comment without requesting anybody a second time.-STATUS_REQUESTED = "requested"-STATUS_DONE = "done"+STATUS_REQUESTED = RoutingStatus.REQUESTED.value+STATUS_DONE = RoutingStatus.DONE.value_CLAIMED_STATUSES = frozenset({STATUS_ROUTING, STATUS_REQUESTED})-# A claim older than this counts as abandoned, so a task that died does not block the pull request-# for good. It sits far above the time a task needs to finish, retries included.-CLAIM_STALE_AFTER = timedelta(hours=2)TRIGGER_SAFETY_NET = "safety_net"SCOPE_FULL = RoutingScope.FULL.value@@ -172,19 +170,9 @@ def is_own_claim(record: Mapping[str, Any] | None, task_id: str) -> bool:return _is_claim(record) and bool(task_id) and record is not None and record.get("claimed_by") == task_id-def _is_stale_claim(record: Mapping[str, Any]) -> bool:- try:- claimed_at = datetime.fromisoformat(str(record.get("claimed_at") or ""))- except ValueError:- return True- return datetime.now(UTC) - claimed_at > CLAIM_STALE_AFTER--def is_foreign_claim(record: Mapping[str, Any] | None, task_id: str) -> bool:"""Whether another task holds a live claim on the pull request."""- return (- _is_claim(record) and not is_own_claim(record, task_id) and record is not None and not _is_stale_claim(record)- )+ return _is_claim(record) and not is_own_claim(record, task_id) and record is not None and not is_stale_claim(record)def effective_record(record: dict[str, Any] | None, task_id: str) -> dict[str, Any] | None:@@ -195,7 +183,7 @@ def effective_record(record: dict[str, Any] | None, task_id: str) -> dict[str, A"""if record is None or record.get("status") != STATUS_ROUTING:return record- if is_own_claim(record, task_id) or _is_stale_claim(record):+ if is_own_claim(record, task_id) or is_stale_claim(record):previous = record.get("previous")return previous if isinstance(previous, dict) else Nonereturn record@@ -391,6 +379,7 @@ def _candidate_record("status": file.status,"additions": file.additions,"deletions": file.deletions,+ "owners_source": candidate.owners_sources.get(file.path),}for file in candidate.files],diff --git a/products/stamphog/backend/presentation/serializers.py b/products/stamphog/backend/presentation/serializers.pyindex 0321f277ff43..fc84a8199a3a 100644--- a/products/stamphog/backend/presentation/serializers.py+++ b/products/stamphog/backend/presentation/serializers.py@@ -28,6 +28,7 @@ from ..facade.enums import (RoutingOwnerOutcome,RoutingOwnerReason,RoutingScope,+ RoutingStatus,)@@ -345,6 +346,77 @@ class StamphogAddRepositorySerializer(serializers.Serializer):)+@extend_schema_serializer(component_name="StamphogPullRequestRouting")+class PullRequestRoutingSerializer(DataclassSerializer):+ status = serializers.ChoiceField(+ choices=RoutingStatus.choices,+ read_only=True,+ help_text=(+ "The phase of the latest routing record: 'waiting' (fallback mode, the head waits for stamphog's "+ "verdict or the safety net), 'routing' (a task holds the claim and requested nobody yet), "+ "'requested' (the review requests went out, the routing comment is not finished) or 'done'."+ ),+ )+ mode = serializers.ChoiceField(+ choices=RoutingMode.choices,+ read_only=True,+ help_text="The repository's routing_mode when the record was written. Compare with the pull request's routing_mode.",+ )+ scope = serializers.ChoiceField(+ choices=RoutingScope.choices,+ read_only=True,+ allow_null=True,+ help_text=(+ "'full', or 'pinned' when a stamphog approval asks only the owners of sensitive and new paths. "+ "Null while the record waits."+ ),+ )++ class Meta:+ dataclass = contracts.PullRequestRoutingDTO+ # Only the fields NOT declared above (see ReviewRunSerializer).+ read_only_fields = [+ "head_sha",+ "trigger",+ "claim_expired",+ "waiting_since",+ "claimed_at",+ "routed_at",+ "full_routed_head",+ "pinned_routed_head",+ ]+ extra_kwargs = {+ "head_sha": {"help_text": "The head commit the record is for. It can be older than the pull request head."},+ "trigger": {+ "help_text": "What started the record: 'opened', 'ready_for_review', 'verdict:<outcome>' or 'safety_net'."+ },+ "claim_expired": {+ "help_text": (+ "True when a 'routing' or 'requested' claim is older than the takeover limit. The task can "+ "still be alive, and a later delivery does not always finish an expired 'requested' claim."+ )+ },+ "waiting_since": {+ "allow_null": True,+ "help_text": "When the head started to wait for stamphog's verdict. Null unless waiting.",+ },+ "claimed_at": {"allow_null": True, "help_text": "When a task claimed the pull request for this record."},+ "routed_at": {+ "allow_null": True,+ "help_text": "When the claim planned its requests. Null until the plan is saved.",+ },+ "full_routed_head": {+ "help_text": (+ "The head that a full routing of this pull request requested owners for, blank if none. "+ "Fallback mode routes in full at most once per pull request."+ )+ },+ "pinned_routed_head": {+ "help_text": "The latest approved head whose pinned owners were requested, blank if none."+ },+ }++@extend_schema_serializer(component_name="StamphogPullRequest")class PullRequestSerializer(DataclassSerializer):repository = serializers.CharField(@@ -359,6 +431,20 @@ class PullRequestSerializer(DataclassSerializer):allow_null=True,help_text="When the pull request merged, null if it hasn't.",)+ routing_mode = serializers.ChoiceField(+ choices=RoutingMode.choices,+ read_only=True,+ help_text="The repository's routing_mode now. 'off' means reviewer routing does not run for new events.",+ )+ routing = PullRequestRoutingSerializer(+ read_only=True,+ allow_null=True,+ help_text=(+ "The latest reviewer routing record of the pull request, or null when routing never wrote one: "+ "routing is off, the pull request is still a draft, or no routing event arrived yet. Use the "+ "routing runs list for the owners each run requested or cut."+ ),+ )class Meta:dataclass = contracts.PullRequestDTO@@ -378,6 +464,8 @@ class PullRequestSerializer(DataclassSerializer):"additions","deletions","changed_files",+ "routing_mode",+ "routing","created_at","updated_at",]@@ -897,6 +985,13 @@ class RoutingFileSerializer(DataclassSerializer):"status": {"help_text": "GitHub's file status, such as 'added', 'modified', 'removed' or 'renamed'."},"additions": {"help_text": "Added lines."},"deletions": {"help_text": "Deleted lines."},+ "owners_source": {+ "help_text": (+ "Repo-relative path of the ownership file, read at the run's owners_sha, whose `owners` list names "+ "this owner for the file. Null when only an additions declaration made the owner a candidate (see "+ "the owner's `new_path` pins), or when the run is older than this field."+ )+ },}diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.pyindex a5e1d742f15f..329db957f0c4 100644--- a/products/stamphog/backend/tests/test_api.py+++ b/products/stamphog/backend/tests/test_api.py@@ -1,5 +1,5 @@import json-from datetime import timedelta+from datetime import datetime, timedeltafrom typing import Anyimport pytest@@ -1255,6 +1255,15 @@ class TestRoutingRunAPI(StamphogTeamScopedTestMixin, APIBaseTest):"status": "added","additions": 20,"deletions": 0,+ "owners_source": "products/alpha/owners.yaml",+ }+ # Runs recorded before `owners_source` existed have no such key.+ _OLD_FILE = {+ "path": "products/beta/c.py",+ "previous_path": None,+ "status": "modified",+ "additions": 1,+ "deletions": 1,}def setUp(self) -> None:@@ -1282,6 +1291,7 @@ class TestRoutingRunAPI(StamphogTeamScopedTestMixin, APIBaseTest):"outcome": "cut","reason": "model_cut","model_reason": "Only renames an import.",+ "files": [self._OLD_FILE],},],)@@ -1382,7 +1392,88 @@ class TestRoutingRunAPI(StamphogTeamScopedTestMixin, APIBaseTest):assert run["owners_sha"] == "owners-1"assert {owner["owner"]: owner["files"] for owner in run["owners"]} == {"team-alpha": [self._FILE],- "team-beta": [],+ "team-beta": [{**self._OLD_FILE, "owners_source": None}],+ }++ @parameterized.expand(+ [+ ("no_record", None, None),+ (+ "waiting",+ {"status": "waiting", "mode": "fallback", "trigger": "opened", "waiting_since": -5},+ {"status": "waiting", "mode": "fallback", "trigger": "opened", "waiting_since": -5},+ ),+ (+ "fresh_claim",+ {"status": "routing", "mode": "always", "trigger": "opened", "scope": "full", "claimed_at": -5},+ {"status": "routing", "mode": "always", "trigger": "opened", "scope": "full", "claimed_at": -5},+ ),+ (+ "expired_requested_claim",+ {+ "status": "requested",+ "mode": "fallback",+ "trigger": "verdict:approved",+ "scope": "pinned",+ "claimed_at": -180,+ "routed_at": -179,+ "pinned_routed_head": "head-1",+ },+ {+ "status": "requested",+ "mode": "fallback",+ "trigger": "verdict:approved",+ "scope": "pinned",+ "claim_expired": True,+ "claimed_at": -180,+ "routed_at": -179,+ "pinned_routed_head": "head-1",+ },+ ),+ ]+ )+ def test_a_pull_request_shows_its_latest_routing_record(+ self, _name: str, record: dict[str, Any] | None, expected: dict[str, Any] | None+ ) -> None:+ now = timezone.now().replace(microsecond=0)+ times = ("waiting_since", "claimed_at", "routed_at")++ def at(values: dict[str, Any]) -> dict[str, Any]:+ return {key: (now + timedelta(minutes=value) if key in times else value) for key, value in values.items()}++ stored = None+ if record is not None:+ # The plan, the comment and the claim's previous record must never leave the API.+ stored = {+ **{key: (value.isoformat() if key in times else value) for key, value in at(record).items()},+ "head_sha": "head-1",+ "claimed_by": "task-1",+ "candidates": [{"owner": "team-alpha", "model_reason": "author text"}],+ "pending_comment": "author text",+ "previous": {"status": "done"},+ }+ PullRequest.objects.unscoped().filter(team_id=self.team.id, pr_number=1).update(routing=stored)+ StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id).update(routing_mode=RoutingMode.FALLBACK)++ response = self.client.get(f"/api/projects/{self.team.id}/stamphog/pull_requests/", {"pr_number": 1})++ assert response.status_code == status.HTTP_200_OK, response.content+ pull_request = response.json()["results"][0]+ assert pull_request["routing_mode"] == "fallback"+ routing = pull_request["routing"]+ if expected is None:+ assert routing is None+ return+ for key in times:+ routing[key] = datetime.fromisoformat(routing[key]) if routing[key] else None+ assert routing == {+ "head_sha": "head-1",+ "scope": None,+ "claim_expired": False,+ **dict.fromkeys(times),+ "full_routed_head": "",+ "pinned_routed_head": "",+ **at(expected),}def test_another_teams_run_is_not_found(self) -> None:diff --git a/products/stamphog/backend/tests/test_routing.py b/products/stamphog/backend/tests/test_routing.pyindex ae5013e32c35..3f9933e0726e 100644--- a/products/stamphog/backend/tests/test_routing.py+++ b/products/stamphog/backend/tests/test_routing.py@@ -52,13 +52,14 @@ def _resolution(status: str = "active",sensitive: bool = False,added: Addition | None = None,+ source: str = "owners.yaml",) -> Resolution:return Resolution(path=path,owners=owners,status=status,slack=None,- source="owners.yaml",+ source=source,unowned_by_design=False,added=added,sensitive=sensitive,@@ -106,7 +107,9 @@ class TestFindCandidates:) -> None:file = _file(path, status=status, previous_path=previous_path)resolutions = {- "ci/baseline.txt": _resolution("ci/baseline.txt", ["team-guard"], status=path_status, sensitive=True),+ "ci/baseline.txt": _resolution(+ "ci/baseline.txt", ["team-guard"], status=path_status, sensitive=True, source="ci/owners.yaml"+ ),"ci/moved.txt": _resolution("ci/moved.txt", ["team-other"]),}@@ -114,6 +117,8 @@ class TestFindCandidates:assert candidates["team-guard"].pins == _SENSITIVE_PINassert candidates["team-guard"].files == (file,)+ # A rename reaches the guard through its old path, so the old path's file decided the owner.+ assert candidates["team-guard"].owners_sources == {path: "ci/owners.yaml"}if "team-other" in candidates:assert not candidates["team-other"].is_pinned@@ -121,15 +126,17 @@ class TestFindCandidates:def test_addition_pins_owners_of_additions(self, status: str, expect_pin: bool) -> None:path = "products/new_thing/backend/api.py"added = Addition(path="products/new_thing", additions=["team-architecture"])- resolutions = {path: _resolution(path, ["team-products"], added=added)}+ resolutions = {path: _resolution(path, ["team-products"], added=added, source="products/owners.yaml")}candidates = {candidate.owner: candidate for candidate in find_candidates([_file(path, status=status)], resolutions)}assert not candidates["team-products"].is_pinned+ assert candidates["team-products"].owners_sources == {path: "products/owners.yaml"}if expect_pin:assert candidates["team-architecture"].pins == {Pin(reason=PinReason.NEW_PATH, path="products/new_thing")}+ assert candidates["team-architecture"].owners_sources == {}else:assert "team-architecture" not in candidatesdiff --git a/products/stamphog/backend/tests/test_routing_task.py b/products/stamphog/backend/tests/test_routing_task.pyindex a2d617fb1c11..6d17aca8dcff 100644--- a/products/stamphog/backend/tests/test_routing_task.py+++ b/products/stamphog/backend/tests/test_routing_task.py@@ -15,9 +15,10 @@ from posthog.ownership.github_files import OwnershipUnavailablefrom products.stamphog.backend.facade.enums import ReviewMode, ReviewRunStatus, ReviewVerdictfrom products.stamphog.backend.facade.tasks import route_pull_request_reviewers+from products.stamphog.backend.logic.routing.claims import CLAIM_STALE_AFTERfrom products.stamphog.backend.logic.routing.comment import ROUTING_COMMENT_MARKERfrom products.stamphog.backend.logic.routing.cut import CUT_MODEL-from products.stamphog.backend.logic.routing.service import CLAIM_STALE_AFTER, RoutingBusy+from products.stamphog.backend.logic.routing.service import RoutingBusyfrom products.stamphog.backend.models import PullRequest, ReviewRun, RoutingRun, RoutingRunOwner, StamphogRepoConfigfrom products.stamphog.backend.tasks.tasks import (ROUTING_BUSY_RETRY_SECONDS,@@ -162,10 +163,10 @@ def _run_log(team_id: int) -> dict[str, tuple[str, str, str]]:return {row.owner: (row.outcome, row.reason, row.model_reason) for row in rows}-def _run_log_paths(team_id: int) -> dict[str, list[str]]:+def _run_log_sources(team_id: int) -> dict[str, dict[str, str | None]]:with team_scope(team_id):rows = RoutingRunOwner.objects.for_team(team_id).all()- return {row.owner: [file["path"] for file in row.files] for row in rows}+ return {row.owner: {file["path"]: file["owners_source"] for file in row.files} for row in rows}def _seed_routing_comment(chain: RoutingChain, repo_config: StamphogRepoConfig) -> None:@@ -276,10 +277,13 @@ def test_routing_requests_the_owners_the_cut_step_keeps(assert record["additions_resolved"] is Trueassert {candidate["owner"] for candidate in record["candidates"]} == {"team-alpha", "team-beta", "@carol"}assert _run_log(team.id) == (_LOG_ONE_CUT if expected_cut else _LOG_CUT_SKIPPED)- assert _run_log_paths(team.id) == {- "team-alpha": ["products/alpha/a.py", "products/alpha/new/b.py"],- "team-beta": ["products/beta/b.py"],- "@carol": ["products/gamma/c.py"],+ assert _run_log_sources(team.id) == {+ "team-alpha": {+ "products/alpha/a.py": "products/alpha/owners.yaml",+ "products/alpha/new/b.py": "products/alpha/owners.yaml",+ },+ "team-beta": {"products/beta/b.py": "products/beta/owners.yaml"},+ "@carol": {"products/gamma/c.py": "products/gamma/owners.yaml"},}assert all("files" not in candidate for candidate in record["candidates"])assert record["owners_sha"]diff --git a/products/stamphog/frontend/generated/api.schemas.ts b/products/stamphog/frontend/generated/api.schemas.tsindex de0dcd195f72..9e59bc912c0e 100644--- a/products/stamphog/frontend/generated/api.schemas.ts+++ b/products/stamphog/frontend/generated/api.schemas.ts@@ -110,6 +110,91 @@ export interface PaginatedDigestRunListApi {results: DigestRunApi[]}+/**+ * * `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++/**+ * * `waiting` - Waiting for stamphog's verdict+ * * `routing` - Routing+ * * `requested` - Requested+ * * `done` - Done+ */+export type RoutingStatusEnumApi = (typeof RoutingStatusEnumApi)[keyof typeof RoutingStatusEnumApi]++export const RoutingStatusEnumApi = {+ Waiting: 'waiting',+ Routing: 'routing',+ Requested: 'requested',+ Done: 'done',+} as const++/**+ * * `full` - Every owner+ * * `pinned` - Pinned owners only+ */+export type RoutingScopeEnumApi = (typeof RoutingScopeEnumApi)[keyof typeof RoutingScopeEnumApi]++export const RoutingScopeEnumApi = {+ Full: 'full',+ Pinned: 'pinned',+} as const++export interface StamphogPullRequestRoutingApi {+ /** The phase of the latest routing record: 'waiting' (fallback mode, the head waits for stamphog's verdict or the safety net), 'routing' (a task holds the claim and requested nobody yet), 'requested' (the review requests went out, the routing comment is not finished) or 'done'.+ *+ * * `waiting` - Waiting for stamphog's verdict+ * * `routing` - Routing+ * * `requested` - Requested+ * * `done` - Done */+ readonly status: RoutingStatusEnumApi+ /** The repository's routing_mode when the record was written. Compare with the pull request's routing_mode.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ readonly mode: RoutingModeEnumApi+ /** 'full', or 'pinned' when a stamphog approval asks only the owners of sensitive and new paths. Null while the record waits.+ *+ * * `full` - Every owner+ * * `pinned` - Pinned owners only */+ readonly scope: RoutingScopeEnumApi | null+ /** The head commit the record is for. It can be older than the pull request head. */+ readonly head_sha: string+ /** What started the record: 'opened', 'ready_for_review', 'verdict:<outcome>' or 'safety_net'. */+ readonly trigger: string+ /** True when a 'routing' or 'requested' claim is older than the takeover limit. The task can still be alive, and a later delivery does not always finish an expired 'requested' claim. */+ readonly claim_expired: boolean+ /**+ * When the head started to wait for stamphog's verdict. Null unless waiting.+ * @nullable+ */+ readonly waiting_since: string | null+ /**+ * When a task claimed the pull request for this record.+ * @nullable+ */+ readonly claimed_at: string | null+ /**+ * When the claim planned its requests. Null until the plan is saved.+ * @nullable+ */+ readonly routed_at: string | null+ /** The head that a full routing of this pull request requested owners for, blank if none. Fallback mode routes in full at most once per pull request. */+ readonly full_routed_head: string+ /** The latest approved head whose pinned owners were requested, blank if none. */+ readonly pinned_routed_head: string+}+export interface StamphogPullRequestApi {readonly id: string/** Full name of the repository this pull request belongs to. */@@ -139,6 +224,14 @@ export interface StamphogPullRequestApi {readonly deletions: number/** Files changed, recorded when the pull request merges. */readonly changed_files: number+ /** The repository's routing_mode now. 'off' means reviewer routing does not run for new events.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ readonly routing_mode: RoutingModeEnumApi+ /** The latest reviewer routing record of the pull request, or null when routing never wrote one: routing is off, the pull request is still a draft, or no routing event arrived yet. Use the routing runs list for the owners each run requested or cut. */+ readonly routing: StamphogPullRequestRoutingApi | null/** When this pull request was first captured. */readonly created_at: string/** When this pull request was last updated. */@@ -165,19 +258,6 @@ 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'. */@@ -616,17 +696,6 @@ export interface ReviewRequestResponseApi {readonly created: boolean}-/**- * * `full` - Every owner- * * `pinned` - Pinned owners only- */-export type RoutingScopeEnumApi = (typeof RoutingScopeEnumApi)[keyof typeof RoutingScopeEnumApi]--export const RoutingScopeEnumApi = {- Full: 'full',- Pinned: 'pinned',-} as const-/*** * `single_candidate` - Single candidate* * `fork` - Fork@@ -831,6 +900,11 @@ export interface StamphogRoutingFileApi {additions?: number/** Deleted lines. */deletions?: number+ /**+ * Repo-relative path of the ownership file, read at the run's owners_sha, whose `owners` list names this owner for the file. Null when only an additions declaration made the owner a candidate (see the owner's `new_path` pins), or when the run is older than this field.+ * @nullable+ */+ owners_source?: string | null}export interface StamphogRoutingRunOwnerDetailApi {diff --git a/products/stamphog/mcp/tools.yaml b/products/stamphog/mcp/tools.yamlindex ac922304a813..2c7922f7d9a6 100644--- a/products/stamphog/mcp/tools.yaml+++ b/products/stamphog/mcp/tools.yaml@@ -44,8 +44,10 @@ tools:Get one pull request record from stamphog (PostHog's automated PR review and merged-PR digest) by itsinternal UUID — the `id` returned by `stamphog-pull-requests-list`, not the GitHub PR number. Returns therepository, title, author, head branch, and merge details. To look a PR up by its GitHub number, use- `stamphog-pull-requests-list` with `pr_number`. For CI status or merge-timing analytics on a PR, use the- engineering analytics `pull-requests` or `pr-lifecycle` tools instead.+ `stamphog-pull-requests-list` with `pr_number`. `routing_mode` is the repository's reviewer routing mode+ now, and `routing` is the latest routing record (phase, head, trigger, timestamps), null when routing never+ wrote one. For CI status or merge-timing analytics on a PR, use the engineering analytics `pull-requests` or+ `pr-lifecycle` tools instead.feature_flag: stamphogstamphog-pull-requests-list:operation: stamphog_pull_requests_list@@ -61,7 +63,8 @@ tools:description: >List pull requests stamphog has seen in this project, newest first. Filter by `pr_number` for a specific PR,or by `merged` (true/false) to separate open work from merged history. Each entry includes the repository,- author, head branch, merge state, and diff size (additions/deletions/changed_files) once merged.+ author, head branch, merge state, diff size (additions/deletions/changed_files) once merged, and the+ reviewer routing state: `routing_mode` now and the latest `routing` record.feature_flag: stamphogstamphog-repo-configs-delete:operation: stamphog_repo_configs_destroy@@ -181,8 +184,9 @@ tools:description: >Get one reviewer routing run by id, with the same owner decisions as the list plus `files` for every owner:each changed file the owner owns (path, previous path, status, additions, deletions), which is what made- them a candidate. `owners_sha` names the default-branch commit whose owners.yaml files decided the owners.- Patches are not kept.+ them a candidate, and `owners_source`, the ownership file at `owners_sha` whose `owners` list names the+ owner for that file (null when only an additions declaration made the owner a candidate, or the run is older+ than the field). Patches are not kept.feature_flag: stamphogresponse:informational_wrapper:@@ -210,9 +214,13 @@ tools:keep only the runs where that owner got it, and `created_after` or `created_before` to set a time window.`head_sha` finds the run for one commit. An owner missing from a run was not a candidate: it owns none ofthe changed files that routing reads (generated, vendored and lock files are skipped), or GitHub listed- fewer files than the pull request changes (`files_truncated`). No runs for a pull request means no run was- recorded: routing is off for the repository, it still waits for stamphog's verdict, or the log write failed.- Use `stamphog-routing-runs-get` for the files each owner owns.+ fewer files than the pull request changes (`files_truncated`). An empty result with `owner`, `outcome`,+ `reason` or a time window can mean only that the owner was not a candidate, so drop those filters first. No+ runs at all for a pull request means no run was recorded: read `routing` and `routing_mode` on+ `stamphog-pull-requests-list` with `pr_number` to see whether routing is off, waiting for stamphog's+ verdict, or still running. A `done` record whose head has no run means the log has no entry for it, most+ often because the log write failed. Use `stamphog-routing-runs-get` for the files each owner owns and the+ ownership file that decided each one.feature_flag: stamphogresponse:informational_wrapper:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 7b55dbf3d4dc..08e099abe471 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -14068,7 +14068,7 @@"feature_flag": "stamphog"},"stamphog-pull-requests-get": {- "description": "Get one pull request record from stamphog (PostHog's automated PR review and merged-PR digest) by its internal UUID — the `id` returned by `stamphog-pull-requests-list`, not the GitHub PR number. Returns the repository, title, author, head branch, and merge details. To look a PR up by its GitHub number, use `stamphog-pull-requests-list` with `pr_number`. For CI status or merge-timing analytics on a PR, use the engineering analytics `pull-requests` or `pr-lifecycle` tools instead.",+ "description": "Get one pull request record from stamphog (PostHog's automated PR review and merged-PR digest) by its internal UUID — the `id` returned by `stamphog-pull-requests-list`, not the GitHub PR number. Returns the repository, title, author, head branch, and merge details. To look a PR up by its GitHub number, use `stamphog-pull-requests-list` with `pr_number`. `routing_mode` is the repository's reviewer routing mode now, and `routing` is the latest routing record (phase, head, trigger, timestamps), null when routing never wrote one. For CI status or merge-timing analytics on a PR, use the engineering analytics `pull-requests` or `pr-lifecycle` tools instead.","category": "Stamphog","feature": "stamphog","summary": "Get stamphog pull request",@@ -14084,7 +14084,7 @@"feature_flag": "stamphog"},"stamphog-pull-requests-list": {- "description": "List pull requests stamphog has seen in this project, newest first. Filter by `pr_number` for a specific PR, or by `merged` (true/false) to separate open work from merged history. Each entry includes the repository, author, head branch, merge state, and diff size (additions/deletions/changed_files) once merged.",+ "description": "List pull requests stamphog has seen in this project, newest first. Filter by `pr_number` for a specific PR, or by `merged` (true/false) to separate open work from merged history. Each entry includes the repository, author, head branch, merge state, diff size (additions/deletions/changed_files) once merged, and the reviewer routing state: `routing_mode` now and the latest `routing` record.","category": "Stamphog","feature": "stamphog","summary": "List stamphog pull requests",@@ -14196,7 +14196,7 @@"feature_flag": "stamphog"},"stamphog-routing-runs-get": {- "description": "Get one reviewer routing run by id, with the same owner decisions as the list plus `files` for every owner: each changed file the owner owns (path, previous path, status, additions, deletions), which is what made them a candidate. `owners_sha` names the default-branch commit whose owners.yaml files decided the owners. Patches are not kept.",+ "description": "Get one reviewer routing run by id, with the same owner decisions as the list plus `files` for every owner: each changed file the owner owns (path, previous path, status, additions, deletions), which is what made them a candidate, and `owners_source`, the ownership file at `owners_sha` whose `owners` list names the owner for that file (null when only an additions declaration made the owner a candidate, or the run is older than the field). Patches are not kept.","category": "Stamphog","feature": "stamphog","summary": "Get stamphog reviewer routing run",@@ -14212,7 +14212,7 @@"feature_flag": "stamphog"},"stamphog-routing-runs-list": {- "description": "List stamphog's reviewer routing runs, newest first. Each run is one round of review requests on a pull request, with the run's decision for every owner of the changed code from owners.yaml: an `outcome` and the `reason` behind it, and the model's one-line `model_reason` when it proposed a cut. To answer \"why was my team not asked to review\", filter by `owner` (a team slug such as `team-devex`, or a GitHub login such as `@octocat`), optionally with `repository` and `pr_number`. Add `outcome` (for example `cut`) or `reason` to keep only the runs where that owner got it, and `created_after` or `created_before` to set a time window. `head_sha` finds the run for one commit. An owner missing from a run was not a candidate: it owns none of the changed files that routing reads (generated, vendored and lock files are skipped), or GitHub listed fewer files than the pull request changes (`files_truncated`). No runs for a pull request means no run was recorded: routing is off for the repository, it still waits for stamphog's verdict, or the log write failed. Use `stamphog-routing-runs-get` for the files each owner owns.",+ "description": "List stamphog's reviewer routing runs, newest first. Each run is one round of review requests on a pull request, with the run's decision for every owner of the changed code from owners.yaml: an `outcome` and the `reason` behind it, and the model's one-line `model_reason` when it proposed a cut. To answer \"why was my team not asked to review\", filter by `owner` (a team slug such as `team-devex`, or a GitHub login such as `@octocat`), optionally with `repository` and `pr_number`. Add `outcome` (for example `cut`) or `reason` to keep only the runs where that owner got it, and `created_after` or `created_before` to set a time window. `head_sha` finds the run for one commit. An owner missing from a run was not a candidate: it owns none of the changed files that routing reads (generated, vendored and lock files are skipped), or GitHub listed fewer files than the pull request changes (`files_truncated`). An empty result with `owner`, `outcome`, `reason` or a time window can mean only that the owner was not a candidate, so drop those filters first. No runs at all for a pull request means no run was recorded: read `routing` and `routing_mode` on `stamphog-pull-requests-list` with `pr_number` to see whether routing is off, waiting for stamphog's verdict, or still running. A `done` record whose head has no run means the log has no entry for it, most often because the log write failed. Use `stamphog-routing-runs-get` for the files each owner owns and the ownership file that decided each one.","category": "Stamphog","feature": "stamphog","summary": "List stamphog reviewer routing runs",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 42df933ad70e..2710209281c6 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -14790,7 +14790,7 @@"feature_flag": "stamphog"},"stamphog-pull-requests-get": {- "description": "Get one pull request record from stamphog (PostHog's automated PR review and merged-PR digest) by its internal UUID — the `id` returned by `stamphog-pull-requests-list`, not the GitHub PR number. Returns the repository, title, author, head branch, and merge details. To look a PR up by its GitHub number, use `stamphog-pull-requests-list` with `pr_number`. For CI status or merge-timing analytics on a PR, use the engineering analytics `pull-requests` or `pr-lifecycle` tools instead.",+ "description": "Get one pull request record from stamphog (PostHog's automated PR review and merged-PR digest) by its internal UUID — the `id` returned by `stamphog-pull-requests-list`, not the GitHub PR number. Returns the repository, title, author, head branch, and merge details. To look a PR up by its GitHub number, use `stamphog-pull-requests-list` with `pr_number`. `routing_mode` is the repository's reviewer routing mode now, and `routing` is the latest routing record (phase, head, trigger, timestamps), null when routing never wrote one. For CI status or merge-timing analytics on a PR, use the engineering analytics `pull-requests` or `pr-lifecycle` tools instead.","category": "Stamphog","feature": "stamphog","summary": "Get stamphog pull request",@@ -14806,7 +14806,7 @@"feature_flag": "stamphog"},"stamphog-pull-requests-list": {- "description": "List pull requests stamphog has seen in this project, newest first. Filter by `pr_number` for a specific PR, or by `merged` (true/false) to separate open work from merged history. Each entry includes the repository, author, head branch, merge state, and diff size (additions/deletions/changed_files) once merged.",+ "description": "List pull requests stamphog has seen in this project, newest first. Filter by `pr_number` for a specific PR, or by `merged` (true/false) to separate open work from merged history. Each entry includes the repository, author, head branch, merge state, diff size (additions/deletions/changed_files) once merged, and the reviewer routing state: `routing_mode` now and the latest `routing` record.","category": "Stamphog","feature": "stamphog","summary": "List stamphog pull requests",@@ -14918,7 +14918,7 @@"feature_flag": "stamphog"},"stamphog-routing-runs-get": {- "description": "Get one reviewer routing run by id, with the same owner decisions as the list plus `files` for every owner: each changed file the owner owns (path, previous path, status, additions, deletions), which is what made them a candidate. `owners_sha` names the default-branch commit whose owners.yaml files decided the owners. Patches are not kept.",+ "description": "Get one reviewer routing run by id, with the same owner decisions as the list plus `files` for every owner: each changed file the owner owns (path, previous path, status, additions, deletions), which is what made them a candidate, and `owners_source`, the ownership file at `owners_sha` whose `owners` list names the owner for that file (null when only an additions declaration made the owner a candidate, or the run is older than the field). Patches are not kept.","category": "Stamphog","feature": "stamphog","summary": "Get stamphog reviewer routing run",@@ -14934,7 +14934,7 @@"feature_flag": "stamphog"},"stamphog-routing-runs-list": {- "description": "List stamphog's reviewer routing runs, newest first. Each run is one round of review requests on a pull request, with the run's decision for every owner of the changed code from owners.yaml: an `outcome` and the `reason` behind it, and the model's one-line `model_reason` when it proposed a cut. To answer \"why was my team not asked to review\", filter by `owner` (a team slug such as `team-devex`, or a GitHub login such as `@octocat`), optionally with `repository` and `pr_number`. Add `outcome` (for example `cut`) or `reason` to keep only the runs where that owner got it, and `created_after` or `created_before` to set a time window. `head_sha` finds the run for one commit. An owner missing from a run was not a candidate: it owns none of the changed files that routing reads (generated, vendored and lock files are skipped), or GitHub listed fewer files than the pull request changes (`files_truncated`). No runs for a pull request means no run was recorded: routing is off for the repository, it still waits for stamphog's verdict, or the log write failed. Use `stamphog-routing-runs-get` for the files each owner owns.",+ "description": "List stamphog's reviewer routing runs, newest first. Each run is one round of review requests on a pull request, with the run's decision for every owner of the changed code from owners.yaml: an `outcome` and the `reason` behind it, and the model's one-line `model_reason` when it proposed a cut. To answer \"why was my team not asked to review\", filter by `owner` (a team slug such as `team-devex`, or a GitHub login such as `@octocat`), optionally with `repository` and `pr_number`. Add `outcome` (for example `cut`) or `reason` to keep only the runs where that owner got it, and `created_after` or `created_before` to set a time window. `head_sha` finds the run for one commit. An owner missing from a run was not a candidate: it owns none of the changed files that routing reads (generated, vendored and lock files are skipped), or GitHub listed fewer files than the pull request changes (`files_truncated`). An empty result with `owner`, `outcome`, `reason` or a time window can mean only that the owner was not a candidate, so drop those filters first. No runs at all for a pull request means no run was recorded: read `routing` and `routing_mode` on `stamphog-pull-requests-list` with `pr_number` to see whether routing is off, waiting for stamphog's verdict, or still running. A `done` record whose head has no run means the log has no entry for it, most often because the log write failed. Use `stamphog-routing-runs-get` for the files each owner owns and the ownership file that decided each one.","category": "Stamphog","feature": "stamphog","summary": "List stamphog reviewer routing runs",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e4e0f9f248fc..cf66278c1d66 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -75779,6 +75779,94 @@ export namespace Schemas {quarantined_count?: number;}+ /**+ * * `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;++ /**+ * * `waiting` - Waiting for stamphog's verdict+ * * `routing` - Routing+ * * `requested` - Requested+ * * `done` - Done+ */+ export type RoutingStatusEnum = typeof RoutingStatusEnum[keyof typeof RoutingStatusEnum];+++ export const RoutingStatusEnum = {+ Waiting: 'waiting',+ Routing: 'routing',+ Requested: 'requested',+ Done: 'done',+ } as const;++ /**+ * * `full` - Every owner+ * * `pinned` - Pinned owners only+ */+ export type RoutingScopeEnum = typeof RoutingScopeEnum[keyof typeof RoutingScopeEnum];+++ export const RoutingScopeEnum = {+ Full: 'full',+ Pinned: 'pinned',+ } as const;++ export interface StamphogPullRequestRouting {+ /** The phase of the latest routing record: 'waiting' (fallback mode, the head waits for stamphog's verdict or the safety net), 'routing' (a task holds the claim and requested nobody yet), 'requested' (the review requests went out, the routing comment is not finished) or 'done'.+ *+ * * `waiting` - Waiting for stamphog's verdict+ * * `routing` - Routing+ * * `requested` - Requested+ * * `done` - Done */+ readonly status: RoutingStatusEnum;+ /** The repository's routing_mode when the record was written. Compare with the pull request's routing_mode.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ readonly mode: RoutingModeEnum;+ /** 'full', or 'pinned' when a stamphog approval asks only the owners of sensitive and new paths. Null while the record waits.+ *+ * * `full` - Every owner+ * * `pinned` - Pinned owners only */+ readonly scope: RoutingScopeEnum | null;+ /** The head commit the record is for. It can be older than the pull request head. */+ readonly head_sha: string;+ /** What started the record: 'opened', 'ready_for_review', 'verdict:<outcome>' or 'safety_net'. */+ readonly trigger: string;+ /** True when a 'routing' or 'requested' claim is older than the takeover limit. The task can still be alive, and a later delivery does not always finish an expired 'requested' claim. */+ readonly claim_expired: boolean;+ /**+ * When the head started to wait for stamphog's verdict. Null unless waiting.+ * @nullable+ */+ readonly waiting_since: string | null;+ /**+ * When a task claimed the pull request for this record.+ * @nullable+ */+ readonly claimed_at: string | null;+ /**+ * When the claim planned its requests. Null until the plan is saved.+ * @nullable+ */+ readonly routed_at: string | null;+ /** The head that a full routing of this pull request requested owners for, blank if none. Fallback mode routes in full at most once per pull request. */+ readonly full_routed_head: string;+ /** The latest approved head whose pinned owners were requested, blank if none. */+ readonly pinned_routed_head: string;+ }+export interface StamphogPullRequest {readonly id: string;/** Full name of the repository this pull request belongs to. */@@ -75808,6 +75896,14 @@ export namespace Schemas {readonly deletions: number;/** Files changed, recorded when the pull request merges. */readonly changed_files: number;+ /** The repository's routing_mode now. 'off' means reviewer routing does not run for new events.+ *+ * * `off` - Off+ * * `always` - Always+ * * `fallback` - When stamphog does not approve */+ readonly routing_mode: RoutingModeEnum;+ /** The latest reviewer routing record of the pull request, or null when routing never wrote one: routing is off, the pull request is still a draft, or no routing event arrived yet. Use the routing runs list for the owners each run requested or cut. */+ readonly routing: StamphogPullRequestRouting | null;/** When this pull request was first captured. */readonly created_at: string;/** When this pull request was last updated. */@@ -75835,20 +75931,6 @@ 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'. */@@ -75892,18 +75974,6 @@ export namespace Schemas {results: StamphogRepoConfig[];}- /**- * * `full` - Every owner- * * `pinned` - Pinned owners only- */- export type RoutingScopeEnum = typeof RoutingScopeEnum[keyof typeof RoutingScopeEnum];--- export const RoutingScopeEnum = {- Full: 'full',- Pinned: 'pinned',- } as const;-/*** * `requested` - Requested* * `labeled` - Labeled@@ -109540,6 +109610,11 @@ export namespace Schemas {additions?: number;/** Deleted lines. */deletions?: number;+ /**+ * Repo-relative path of the ownership file, read at the run's owners_sha, whose `owners` list names this owner for the file. Null when only an additions declaration made the owner a candidate (see the owner's `new_path` pins), or when the run is older than this field.+ * @nullable+ */+ owners_source?: string | null;}export interface StamphogRoutingRunOwnerDetail {