Skip to content

: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.

feat(signals): resolve a team slug to reviewers in scout-members-list (#105042)

posthog[bot]094bfe7b88b9
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index d69507065302..c9fab99efde9 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -37,6 +37,7 @@ from products.engineering_analytics.backend.facade.contracts import (
DoraOverview,
FlakyTestList,
GitHubSource,
+ GitHubTeamRoster,
MasterFailureGroup,
MergedPullRequest,
PathOwnership,
@@ -694,6 +695,16 @@ def list_job_aggregates(
)
+def get_github_team_roster(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> GitHubTeamRoster:
+ """Who is on which GitHub org team, from the team's synced membership snapshot.
+
+ Narrower than every read above: it resolves the membership table alone, so a caller routing work
+ at a team slug does not need the ``pull_requests`` / ``workflow_runs`` pair the curated handle
+ insists on. An unsynced snapshot comes back as ``synced=False``, never an error.
+ """
+ return logic.build_github_team_roster(team=team, user_access_control=user_access_control)
+
+
def resolve_path_owners(repository: str, paths: Sequence[str]) -> PathOwnership:
"""Name the team that owns each repository path, from the ownership files on the repository's
default branch. It takes no team, because nothing PostHog stores feeds the answer."""
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 052fcb957114..1671095621d5 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -247,6 +247,32 @@ class GitHubSource:
synced: bool = False
+@dataclass(frozen=True)
+class GitHubTeamMembership:
+ """One person's membership of one GitHub org team, read from the synced roster snapshot."""
+
+ # The member's GitHub login, lowercased so a reader can match it against a stored identity.
+ member_handle: str
+ team_slug: str
+ team_name: str
+ # False whenever the snapshot cannot say otherwise: GitHub omits the role column on some syncs.
+ is_maintainer: bool
+
+
+@dataclass(frozen=True)
+class GitHubTeamRoster:
+ """Every synced org team membership, and whether there was a snapshot to read at all.
+
+ ``synced`` is false when no connected source carries the membership endpoint. It is off by
+ default and needs the org Members grant, so a caller must be able to say "the roster isn't
+ synced here" rather than read an empty result as "that team has nobody on it". The snapshot is
+ also only as fresh as the source's last sync, so it can lag the live team.
+ """
+
+ memberships: tuple[GitHubTeamMembership, ...]
+ synced: bool
+
+
@dataclass(frozen=True)
class ExpectedWarehouseView:
"""A code-generated warehouse view this product exposes as a team-scoped DataWarehouse saved
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index 2dd5ff658db8..d3c5826ce586 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -28,6 +28,9 @@ from products.engineering_analytics.backend.logic.delivery_scope import (
SummaryScope as SummaryScope,
)
from products.engineering_analytics.backend.logic.dora import build_dora_overview as build_dora_overview
+from products.engineering_analytics.backend.logic.github_teams import (
+ build_github_team_roster as build_github_team_roster,
+)
from products.engineering_analytics.backend.logic.ownership import resolve_path_owners as resolve_path_owners
from products.engineering_analytics.backend.logic.pull_requests import (
build_author_workflow_costs as build_author_workflow_costs,
diff --git a/products/engineering_analytics/backend/logic/github_teams.py b/products/engineering_analytics/backend/logic/github_teams.py
new file mode 100644
index 000000000000..3f5e70d828c0
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/github_teams.py
@@ -0,0 +1,58 @@
+"""The org team roster read: who is on which GitHub team, from the synced membership snapshot.
+
+A caller that only wants to turn a team slug into people asks this one question, so the read stands
+on its own rather than going through ``CuratedGitHubSource``: that handle resolves ``pull_requests``
+and ``workflow_runs`` first, which a roster read never touches and a roster-only source may not even
+sync.
+"""
+
+from typing import TYPE_CHECKING
+
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.team import Team
+
+from products.engineering_analytics.backend.facade.contracts import GitHubTeamMembership, GitHubTeamRoster
+from products.engineering_analytics.backend.logic.sources import resolve_team_membership_table
+from products.engineering_analytics.backend.logic.views import team_members
+
+if TYPE_CHECKING:
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+# A whole org's memberships in one pass, with a ceiling that keeps a runaway snapshot out of memory.
+_ROSTER_ROW_LIMIT = 100_000
+
+
+def build_github_team_roster(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> GitHubTeamRoster:
+ """Every synced org team membership, or an unsynced roster when no source carries the snapshot."""
+ snapshot = resolve_team_membership_table(team=team, user_access_control=user_access_control)
+ if snapshot is None:
+ return GitHubTeamRoster(memberships=(), synced=False)
+
+ roster_sql = team_members.build_roster_query(snapshot.table, has_role=snapshot.has_role)
+ sql = f"SELECT * FROM ({roster_sql}) AS roster ORDER BY team_slug, member_handle LIMIT {_ROSTER_ROW_LIMIT}"
+ with tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=team.pk):
+ response = execute_hogql_query(
+ query=parse_select(sql),
+ team=team,
+ query_type="engineering_analytics.github_team_roster",
+ # Same two paths as ``CuratedGitHubSource.run``: the real user lets HogQL honor the per-table
+ # warehouse ACL, and the userless caller must bypass it or fail closed on every such table.
+ user=user_access_control.user if user_access_control is not None else None,
+ user_access_control=user_access_control,
+ bypass_warehouse_access_control=user_access_control is None,
+ )
+ return GitHubTeamRoster(
+ memberships=tuple(
+ GitHubTeamMembership(
+ member_handle=str(member_handle),
+ team_slug=str(team_slug),
+ team_name=str(team_name),
+ is_maintainer=bool(is_maintainer),
+ )
+ for member_handle, team_slug, team_name, is_maintainer in (response.results or [])
+ ),
+ synced=True,
+ )
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index bab419976cde..45ea52230f40 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -66,6 +66,11 @@ REVIEWS_SCHEMA = "reviews"
# pull request in the repo requested a team, and a read of it fails before that.
REQUESTED_TEAM_COLUMN = "requested_team"
+# GitHub puts the membership role (``maintainer`` / ``member``) on a team member row, but it is not in
+# the endpoint's documented user object, so a snapshot can land without it. Probed per table like
+# REQUESTED_TEAM_COLUMN, and a read without it reports every member as a plain member.
+MEMBER_ROLE_COLUMN = "role"
+
# The curated endpoints we resolve per repo. A source's other synced endpoints (issues, commits,
# teams, …) are irrelevant to the CI/PR read layer and dropped during grouping.
_CURATED_ENDPOINTS = frozenset(
@@ -227,6 +232,39 @@ def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:
return resolved
+@dataclass(frozen=True)
+class TeamMembershipTable:
+ """The synced org team-membership snapshot: its warehouse table and whether it carries roles."""
+
+ table: str
+ has_role: bool
+
+
+def resolve_team_membership_table(
+ *, team: Team, user_access_control: "UserAccessControl | None" = None
+) -> TeamMembershipTable | None:
+ """The team's synced ``team_members`` table, or None when no connected source syncs it.
+
+ Deliberately narrower than ``resolve_github_tables``: turning a team slug into logins needs
+ neither ``pull_requests`` nor ``workflow_runs``, so requiring them would make routing fail on a
+ source that syncs the roster alone, or while the PR endpoints are still backfilling. Membership is
+ org-scoped, so every repo of every source answers with the same roster and the first match wins.
+ The endpoint is off by default (it needs the org Members grant), so None is the normal state and
+ callers degrade to "membership isn't synced" rather than "that team has nobody on it".
+ """
+ for source in _github_sources(team, user_access_control):
+ legacy_repo = _source_repository(source) or None
+ for schema in _synced_schemas(team=team, source=source):
+ _, endpoint = github_schema_repo_endpoint(schema.schema_metadata, schema.name, legacy_repo)
+ if endpoint != TEAM_MEMBERS_SCHEMA:
+ continue
+ table = schema.table
+ if table is None or table.deleted or not _IDENTIFIER.match(table.name):
+ continue
+ return TeamMembershipTable(table=table.name, has_role=MEMBER_ROLE_COLUMN in (table.columns or {}))
+ return None
+
+
TRUNK_MERGE_QUEUE_SCHEMA = "MergeQueuePullRequests"
diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.py
index bd01b19bd384..ed88d908be7f 100644
--- a/products/engineering_analytics/backend/logic/views/source_schema.py
+++ b/products/engineering_analytics/backend/logic/views/source_schema.py
@@ -116,10 +116,14 @@ REVIEWS_COLUMNS: dict[str, dict[str, str]] = {
# Contract for the ``github_team_members`` warehouse source (org team membership). Member rows
# are GitHub user objects with the parent team's identity injected by the source fan-out
# (``team_id`` / ``team_slug`` / ``team_name``); ``login`` + ``team_slug`` are the join keys the
-# membership-based merge timing reads. Same Nullable discipline as above.
+# membership-based merge timing reads, and ``role`` (``maintainer`` / ``member``) is what the
+# roster read orders reviewers by. Same Nullable discipline as above. GitHub omits ``role`` from
+# the documented member object, so a real table can land without it and the source resolver
+# probes for it rather than assuming it (see MEMBER_ROLE_COLUMN).
TEAM_MEMBERS_COLUMNS: dict[str, dict[str, str]] = {
"id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},
"login": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+ "role": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
"team_id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},
"team_slug": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
"team_name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
diff --git a/products/engineering_analytics/backend/logic/views/team_members.py b/products/engineering_analytics/backend/logic/views/team_members.py
index 4f6f5e172758..ed1ac7c55fb5 100644
--- a/products/engineering_analytics/backend/logic/views/team_members.py
+++ b/products/engineering_analytics/backend/logic/views/team_members.py
@@ -20,3 +20,27 @@ def build_query(table_name: str) -> str:
FROM {table_name}
WHERE ifNull(login, '') != ''
"""
+
+
+def build_roster_query(table_name: str, *, has_role: bool) -> str:
+ """One row per (member, team), for reading the roster itself rather than joining PR authors to it.
+
+ Logins are lowercased here because a reader matches them against identities stored lowercase.
+ A snapshot without the optional ``role`` column reports every member as a plain member, which is
+ the honest answer: the column's absence says nothing about who maintains the team.
+
+ Membership is org-scoped but the source offers it per repo, so one membership can land more than
+ once. The grouping collapses those to one row, and ``max`` keeps a maintainer row winning over a
+ plain-member duplicate of the same membership.
+ """
+ is_maintainer = "lower(ifNull(role, '')) = 'maintainer'" if has_role else "0"
+ return f"""
+ SELECT
+ lower(ifNull(login, '')) AS member_handle,
+ ifNull(team_slug, '') AS team_slug,
+ max(ifNull(team_name, '')) AS team_name,
+ max({is_maintainer}) AS is_maintainer
+ FROM {table_name}
+ WHERE ifNull(login, '') != '' AND ifNull(team_slug, '') != ''
+ GROUP BY member_handle, team_slug
+ """
diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
index 1a8a32fddab3..1258e39d9cca 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -932,6 +932,9 @@ def _team_membership_rows(prs: list[dict[str, Any]]) -> list[dict[str, Any]]:
{
"id": 900_000 + member_index,
"login": login,
+ # One maintainer per team, so the roster read's maintainers-first order is
+ # visible locally instead of every member looking the same.
+ "role": "maintainer" if slot == 0 and member_index < team_count else "member",
"team_id": team_index + 1,
"team_slug": slug,
"team_name": slug.removeprefix("team-").replace("-", " ").title(),
diff --git a/products/engineering_analytics/backend/tests/test_github_team_roster.py b/products/engineering_analytics/backend/tests/test_github_team_roster.py
new file mode 100644
index 000000000000..a2888ec3a517
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_github_team_roster.py
@@ -0,0 +1,67 @@
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+from products.engineering_analytics.backend.facade import api
+from products.engineering_analytics.backend.facade.contracts import GitHubTeamMembership, GitHubTeamRoster
+from products.engineering_analytics.backend.logic.views.source_schema import TEAM_MEMBERS_COLUMNS
+from products.engineering_analytics.backend.tests._logic_helpers import _WarehouseMixin
+
+_WITHOUT_ROLE = {name: spec for name, spec in TEAM_MEMBERS_COLUMNS.items() if name != "role"}
+
+
+def _member_row(member_id: int, login: str, team_slug: str, role: str) -> dict:
+ return {
+ "id": member_id,
+ "login": login,
+ "role": role,
+ "team_id": 1,
+ "team_slug": team_slug,
+ "team_name": team_slug.removeprefix("team-").title(),
+ }
+
+
+class TestGitHubTeamRoster(_WarehouseMixin, ClickhouseTestMixin, BaseTest):
+ """The roster read end to end over a real warehouse table, with no PR/CI endpoints seeded."""
+
+ def test_reads_the_roster_from_a_source_that_syncs_membership_alone(self) -> None:
+ # Guards the HogQL and the narrow resolver together: the read runs without pull_requests /
+ # workflow_runs, lowercases the login, and carries the role. A break here is invisible,
+ # because the caller degrades to "not synced" rather than raising.
+ self._create_table(
+ "github_team_members",
+ TEAM_MEMBERS_COLUMNS,
+ [
+ _member_row(1, "Boss", "team-desktop", "maintainer"),
+ _member_row(2, "plain", "team-desktop", "member"),
+ # A per-repo sync of an org-scoped endpoint lands this membership twice: it must
+ # collapse to one row without demoting the maintainer.
+ _member_row(5, "boss", "team-desktop", "member"),
+ # Rows GitHub can land that reach no reader: no login to match, no team to file under.
+ _member_row(3, "", "team-desktop", "member"),
+ _member_row(4, "nobody", "", "member"),
+ ],
+ )
+
+ roster = api.get_github_team_roster(team=self.team)
+
+ assert roster == GitHubTeamRoster(
+ memberships=(
+ GitHubTeamMembership(
+ member_handle="boss", team_slug="team-desktop", team_name="Desktop", is_maintainer=True
+ ),
+ GitHubTeamMembership(
+ member_handle="plain", team_slug="team-desktop", team_name="Desktop", is_maintainer=False
+ ),
+ ),
+ synced=True,
+ )
+
+ def test_a_snapshot_without_roles_reports_every_member_as_a_plain_member(self) -> None:
+ # GitHub omits role from the documented member object, so a table can land without the column.
+ self._create_table("github_team_members", _WITHOUT_ROLE, [_member_row(1, "boss", "team-desktop", "maintainer")])
+
+ roster = api.get_github_team_roster(team=self.team)
+
+ assert [membership.is_maintainer for membership in roster.memberships] == [False]
+
+ def test_reports_not_synced_without_a_membership_snapshot(self) -> None:
+ assert api.get_github_team_roster(team=self.team) == GitHubTeamRoster(memberships=(), synced=False)
diff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.py
index de9ec36e6777..962fa4086690 100644
--- a/products/engineering_analytics/backend/tests/test_logic_sources.py
+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py
@@ -11,13 +11,16 @@ from products.engineering_analytics.backend.facade.contracts import GitHubSource
from products.engineering_analytics.backend.logic.sources import (
ISSUE_EVENTS_SCHEMA,
PULL_REQUESTS_SCHEMA,
+ TEAM_MEMBERS_SCHEMA,
WORKFLOW_JOBS_SCHEMA,
WORKFLOW_RUNS_SCHEMA,
GitHubTables,
JobSourceTables,
+ TeamMembershipTable,
list_github_sources,
resolve_github_tables,
resolve_job_source_tables,
+ resolve_team_membership_table,
)
from products.engineering_analytics.backend.logic.views.source_schema import (
PULL_REQUESTS_COLUMNS,
@@ -87,6 +90,36 @@ class TestResolveGitHubTables(BaseTest):
assert (tables.issue_events, tables.issue_events_team_requests) == ("flaggithub_issue_events", expected)
+ @parameterized.expand(
+ [
+ # GitHub's documented member object omits role, so probing keeps the roster read off a
+ # column a snapshot may not have.
+ ("with_roles", ["login", "team_slug", "role"], True),
+ ("without_roles", ["login", "team_slug"], False),
+ ]
+ )
+ def test_resolves_membership_snapshot_without_the_pull_request_endpoints(
+ self, _name: str, columns: list[str], expected_roles: bool
+ ) -> None:
+ # Membership syncs on its own, so routing must not depend on pull_requests + workflow_runs.
+ source = self._connect(prefix="roster", schemas=[])
+ table = create_warehouse_table_row(self.team, name="rostergithub_team_members", source=source)
+ table.columns = {
+ column: {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"} for column in columns
+ }
+ table.save()
+ link_schema(self.team, source, name=TEAM_MEMBERS_SCHEMA, table=table, should_sync=True)
+
+ assert resolve_team_membership_table(team=self.team) == TeamMembershipTable(
+ table="rostergithub_team_members", has_role=expected_roles
+ )
+
+ def test_resolves_no_membership_snapshot_when_the_endpoint_is_unsynced(self) -> None:
+ # The endpoint is off by default, so a connected source without it reports "not synced"
+ # rather than resolving some other table.
+ self._connect(prefix="myprefix", schemas=self._BOTH_SYNCED)
+ assert resolve_team_membership_table(team=self.team) is None
+
def test_repo_scoped_resolution_survives_non_dict_job_inputs(self) -> None:
# job_inputs is an EncryptedJSONField that can hold any JSON value; the repo-first ordering
# must treat a non-dict as "no repository input", not crash the whole resolution.
diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.md
index 88839088f922..c4dd8ea08238 100644
--- a/products/signals/backend/report_generation/AGENTS.md
+++ b/products/signals/backend/report_generation/AGENTS.md
@@ -27,6 +27,11 @@ It is exercised locally via management commands, and it is also used by the prod
The repository used for research is tracked separately via the `repo_selection` artefact.
+- `team_membership.py`
+ Resolves which teams a person belongs to, so a report can be routed at a team slug rather than at a name. Provider-neutral by design (a membership is a slug, a display name, and whether the person maintains the team); the synced GitHub org roster read through the engineering_analytics facade is the only source behind it today.
+ - Backs the `team` filter and the `teams` field on `scout-members-list` (`resolve_reviewers.list_project_members`).
+ - The roster is a warehouse snapshot, so it can lag the live team, and the membership endpoint is off by default at the source (it needs the org Members grant). A slug with no rows therefore means "not synced here", never "no such team", and callers must keep those two apart.
+ - A failed read degrades rather than raising, so a warehouse hiccup never takes down the member list beside it. It is marked `read_failed`, kept apart from a genuinely unsynced roster: a filtered call answers 503 and asks for a retry, because telling a scout to turn on a sync that is already on sends it to change a correct setting.
- `reviewer_telemetry.py`
Emits the `signals_suggested_reviewers_resolved` product-analytics event whenever a report's suggested reviewers are persisted, recording which GitHub logins link to a PostHog user and which don't (unlinkable reviewers can't be routed or run autostart, but still count as "assigned" in reviewer metrics).
- Called after the artefact write commits (via `transaction.on_commit` where a transaction is open), never in-transaction: the research activity (`source="pipeline"`), scout report creation and reviewer edits (`"scout"` / `"scout_edit"`), custom-agent persistence (`"custom_agent"`), the app reviewers PUT (`"user_edit"`), and the artefacts POST (`"api"`).
diff --git a/products/signals/backend/report_generation/resolve_reviewers.py b/products/signals/backend/report_generation/resolve_reviewers.py
index c85a67512fc1..f50c62b36586 100644
--- a/products/signals/backend/report_generation/resolve_reviewers.py
+++ b/products/signals/backend/report_generation/resolve_reviewers.py
@@ -38,6 +38,11 @@ from products.signals.backend.report_generation.repo_activity import (
get_area_activity,
repository_activity_needs_rebuild,
)
+from products.signals.backend.report_generation.team_membership import (
+ MembershipRoster,
+ MemberTeam,
+ resolve_membership_roster,
+)
from ..models import SignalReportArtefact, SignalScoutConfig
@@ -872,7 +877,7 @@ def get_org_member_github_logins_by_user_uuid(team_id: int, user_uuids: list[str
MAX_PROJECT_MEMBERS = 200
-@dataclass
+@frozen
class ProjectMemberIdentity:
"""One project member's routing identity — enough for a scout to pick a `suggested_reviewers` entry."""
@@ -881,12 +886,27 @@ class ProjectMemberIdentity:
first_name: str
last_name: str
github_login: str | None
+ teams: tuple[MemberTeam, ...] = ()
+
+
+@frozen
+class ProjectMemberRoster:
+ """The members a roster call resolved, plus what the membership snapshot could say about them."""
+
+ members: tuple[ProjectMemberIdentity, ...]
+ # False when nothing is synced, so every member's `teams` is empty and a filter cannot resolve.
+ membership_synced: bool
+ # True when the roster read failed, which is a retry rather than a sync to turn on.
+ membership_read_failed: bool
+ # False when the snapshot holds no rows under the asked-for slug. Distinct from an empty
+ # ``members``, which means the team is synced but nobody on it can review here.
+ team_is_covered: bool
def list_project_members(
- team: Team, *, search: str | None = None, limit: int = MAX_PROJECT_MEMBERS
-) -> list[ProjectMemberIdentity]:
- """Members with access to ``team`` — their UUID/email/name and resolved GitHub login.
+ team: Team, *, search: str | None = None, team_slug: str | None = None, limit: int = MAX_PROJECT_MEMBERS
+) -> ProjectMemberRoster:
+ """Members with access to ``team`` — their UUID/email/name, resolved GitHub login, and teams.
Backs the `scout-members-list` tool: the cold-start reviewer-routing path for a scout
that can't read an owner off a fetched entity's ``created_by`` and has no cached
@@ -897,7 +917,13 @@ def list_project_members(
with no linked GitHub identity gets a null login rather than dropping out. ``search``
(case-insensitive, over email + name) narrows the roster; the result is capped at ``limit`` so a
large org can't push its whole directory into the scout's context in one call.
+
+ ``team_slug`` narrows to the people on one team and puts its maintainers first, so a caller that
+ takes the first few entries takes the people most likely to own the work. Teams are matched on
+ the GitHub login, so a member with no linked GitHub identity carries no teams and never matches
+ a filter. Search and the filter compose, and the cap applies after both.
"""
+ roster = resolve_membership_roster(team)
users = team.all_users_with_access()
if search:
# Match the search against email, each name part, AND the concatenated full name, so a
@@ -909,17 +935,62 @@ def list_project_members(
| Q(last_name__icontains=search)
| Q(_full_name__icontains=search)
)
- users = users.prefetch_related(*_github_identity_prefetches()).order_by("id")[:limit]
- return [
- ProjectMemberIdentity(
- user_uuid=str(user.uuid),
- email=user.email,
- first_name=user.first_name,
- last_name=user.last_name,
- github_login=(login.lower() if (login := user.get_github_login()) else None),
+ users = users.prefetch_related(*_github_identity_prefetches()).order_by("id")
+ if team_slug is None:
+ users = users[:limit]
+ else:
+ # Narrowed in SQL, so a team filter never pulls a whole org's roster into memory to keep a
+ # handful of rows. The cap waits for the maintainer ordering, which needs the whole team.
+ users = _users_holding_logins(users, team, _logins_on_team(roster, team_slug))
+ members: list[ProjectMemberIdentity] = []
+ for user in users:
+ login = raw.lower() if (raw := user.get_github_login()) else None
+ members.append(
+ ProjectMemberIdentity(
+ user_uuid=str(user.uuid),
+ email=user.email,
+ first_name=user.first_name,
+ last_name=user.last_name,
+ github_login=login,
+ teams=roster.teams_for(login),
+ )
)
- for user in users
- ]
+ if team_slug is not None:
+ members = [member for member in members if _team_membership(member, team_slug) is not None]
+ # Stable, so members keep their id order inside each group and only the maintainer split moves.
+ members.sort(key=lambda member: not _is_maintainer_of(member, team_slug))
+ return ProjectMemberRoster(
+ members=tuple(members[:limit]),
+ membership_synced=roster.synced,
+ membership_read_failed=roster.read_failed,
+ team_is_covered=team_slug is None or team_slug in roster.covered_slugs,
+ )
+
+
+def _logins_on_team(roster: MembershipRoster, team_slug: str) -> frozenset[str]:
+ return frozenset(
+ login for login, teams in roster.teams_by_login.items() if any(team.slug == team_slug for team in teams)
+ )
+
+
+def _users_holding_logins(users: QuerySet, team: Team, logins: frozenset[str]) -> QuerySet:
+ """``users`` narrowed to those whose stored GitHub identity could be one of ``logins``.
+
+ A superset match on the same three identity sources ``User.get_github_login()`` reads, so the
+ caller still confirms each resolved login before it keeps the member.
+ """
+ if not logins:
+ return users.none()
+ return users.filter(id__in=_candidate_user_ids_for_org_and_logins(str(team.organization_id), logins))
+
+
+def _team_membership(member: ProjectMemberIdentity, team_slug: str) -> MemberTeam | None:
+ return next((team for team in member.teams if team.slug == team_slug), None)
+
+
+def _is_maintainer_of(member: ProjectMemberIdentity, team_slug: str) -> bool:
+ membership = _team_membership(member, team_slug)
+ return membership is not None and membership.is_maintainer
def resolve_org_github_login_to_users(team_id: int, github_logins: Iterable[str]) -> dict[str, User]:
diff --git a/products/signals/backend/report_generation/team_membership.py b/products/signals/backend/report_generation/team_membership.py
new file mode 100644
index 000000000000..b60485b502d6
--- /dev/null
+++ b/products/signals/backend/report_generation/team_membership.py
@@ -0,0 +1,108 @@
+"""Which teams a person belongs to, so a report can be routed at a team rather than at a name.
+
+Routing input often names a team: a slug in a scout note, a CODEOWNERS entry, an ``owners.yaml``
+owner. The reviewer artefact only holds individuals, so this is the step in between, and it is
+kept provider-neutral: a membership here is a slug, a display name, and whether the person maintains
+the team, none of which is GitHub's. The synced GitHub org roster is the only source behind it today.
+
+Two properties every caller has to carry:
+
+- The roster is a warehouse snapshot, so it is only as fresh as the source's last sync and can lag
+ the live team.
+- The membership endpoint is off by default (it needs the org Members grant), so a slug with no rows
+ means "not synced here", never "no such team".
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.models.team import Team
+
+from products.engineering_analytics.backend.facade.api import get_github_team_roster
+
+logger = structlog.get_logger(__name__)
+
+
+# Matches the vocabulary ``RoleExternalReference.provider`` uses for the same external-group idea.
+GITHUB_PROVIDER = "github"
+
+
+@frozen
+class MemberTeam:
+ """One team a person belongs to, on one provider."""
+
+ provider: str
+ slug: str
+ name: str
+ is_maintainer: bool
+
+
+@frozen
+class MembershipRoster:
+ """The project's team memberships, keyed by the identity a member is matched on."""
+
+ # False when no membership snapshot could be read at all, either unsynced or a failed read.
+ synced: bool
+ # True when the read itself failed, so a snapshot may well be synced. The two need telling
+ # apart: a caller that reports a timeout as "turn the sync on" sends a scout to change a
+ # setting that is already right.
+ read_failed: bool
+ # Lowercased GitHub login -> the teams that login is on, sorted by slug.
+ teams_by_login: Mapping[str, tuple[MemberTeam, ...]]
+ # Every slug the snapshot holds, including teams with no PostHog member on them, which is what
+ # separates "no rows for that team" from "nobody on that team can review here".
+ covered_slugs: frozenset[str]
+
+ def teams_for(self, login: str | None) -> tuple[MemberTeam, ...]:
+ return self.teams_by_login.get(login, ()) if login else ()
+
+
+_UNSYNCED = MembershipRoster(synced=False, read_failed=False, teams_by_login={}, covered_slugs=frozenset())
+_READ_FAILED = MembershipRoster(synced=False, read_failed=True, teams_by_login={}, covered_slugs=frozenset())
+
+
+def resolve_membership_roster(team: Team) -> MembershipRoster:
+ """The project's team memberships, or an unsynced roster when none can be read.
+
+ Userless on purpose: this resolves the roster server-side for the whole project, the same way
+ the member list beside it reads project access straight from the ORM. A scout token is an
+ automation rather than a person choosing warehouse sources, and team scoping is the boundary.
+
+ A failed read degrades rather than raising. Routing is one field of a report, so a warehouse
+ hiccup must not fail the roster call that also answers "who can review here". It comes back
+ marked ``read_failed`` so a caller can offer a retry instead of a sync it does not need.
+ """
+ try:
+ roster = get_github_team_roster(team=team)
+ except Exception:
+ logger.warning("signals.team_membership.roster_read_failed", team_id=team.pk, exc_info=True)
+ return _READ_FAILED
+ if not roster.synced:
+ return _UNSYNCED
+
+ teams_by_login: dict[str, list[MemberTeam]] = {}
+ covered_slugs: set[str] = set()
+ for membership in roster.memberships:
+ slug = membership.team_slug.lower()
+ covered_slugs.add(slug)
+ teams_by_login.setdefault(membership.member_handle.lower(), []).append(
+ MemberTeam(
+ provider=GITHUB_PROVIDER,
+ slug=slug,
+ name=membership.team_name,
+ is_maintainer=membership.is_maintainer,
+ )
+ )
+ return MembershipRoster(
+ synced=True,
+ read_failed=False,
+ teams_by_login={
+ login: tuple(sorted(teams, key=lambda member_team: member_team.slug))
+ for login, teams in teams_by_login.items()
+ },
+ covered_slugs=frozenset(covered_slugs),
+ )
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 54907625ab4a..dcda3e5296e2 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -101,6 +101,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
`SignalScoutViewSet` backs `scout-create`: it creates a custom `signals-scout-*` skill and its runnable config atomically, grants the report-channel tools server-side, and treats an identical definition as a retry while rejecting conflicting definitions.
`SignalScoutMembersViewSet` (`scout-members-list`) is the reviewer-routing roster:
it returns the project's members (those with access to the team) with `user_uuid` / `email` / `github_login` so a report-channel scout can populate `suggested_reviewers` at cold start. The roster is member PII the scout needs to route, gated on the internal `signal_scout_internal` scope object (`scope_object = "signal_scout_internal"`, default `list` → `signal_scout_internal:read`, satisfied by the sandbox token's `…:write`) — so, like `emit-signal`, it is reachable only inside a scout run and never enters a customer's public MCP catalog. (The narrower `signal_scout_report` scope was considered but is transient — kept only while emit-signal and emit-report coexist — so the durable tool stays on `signal_scout_internal`.) Membership is resolved server-side via `report_generation/resolve_reviewers.list_project_members` (through `Team.all_users_with_access()`, so private-project access control is honored), the project-nested path that the org-nested `org-members-list` tool (stripped + 403'd for a scoped-team token) can't provide.
+ Each row also carries the `teams` that member is on, and `?team=<slug>` narrows the roster to one team with its maintainers first, which is how a slug from a scout note, CODEOWNERS, or an `owners.yaml` owner becomes reviewers (`report_generation/team_membership.py` resolves the roster through the engineering_analytics facade). The filter returns 400 rather than an empty list when the project has no synced roster or the roster holds no rows for the slug: team rosters sync one by one, so an absent slug almost always means unsynced coverage, and a scout that reads an empty list as "no such team" stops routing to a team that exists.
The config viewset remains the lower-level no-wait creation path: `create` registers (upserts) a config for an already-authored skill with its schedule/emit posture in one call.
`list` is strictly read-only (its MCP tool is annotated `readOnly`) — it never mints config rows. The metadata viewset is the read-only `scout/metadata/current/` endpoint that reports enrollment + banner + enforced limits via `team_limits.resolve_team_metadata`.
diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.py
index f5cdfe39caf5..fbea2444ee91 100644
--- a/products/signals/backend/scout_harness/prompt.py
+++ b/products/signals/backend/scout_harness/prompt.py
@@ -512,6 +512,7 @@ This is the single highest-leverage field you set. `suggested_reviewers` (a list
- **Always try to set it.** Spend real effort identifying who owns the affected area, leaning on evidence you already gathered: code owners, recent authors on the relevant surface, the team that owns the product. Treat "I couldn't find an owner" as a last resort, not a default.
- **Identify a reviewer two ways, and prefer the uuid.** `user_uuid` (`{user_uuid: "..."}`) names a PostHog member directly, so it is the safer identity: it cannot be mis-typed into someone else, and it works for a member who never connected GitHub. `github_login` is a bare lowercase login (`{github_login: "octocat"}`, no `@`, no display name), matched exactly, so a guessed, mis-cased, or display-name handle reaches no one. Use the login when your evidence is commit authorship; use the uuid whenever your evidence names a PostHog user (an account owner, an entity's `created_by`).
- **No owner in your evidence? List the members.** `scout-members-list` returns this project's members with `email`, name, and resolved `github_login` (pass `search` to narrow a big project). Match the owner by email/name, then route to their `user_uuid`. Every member is routable, including one whose `github_login` is null — a null login only means no draft PR can be opened as that person, not that the report can't reach them. The org-scoped `org-member-get-github-login` / `org-members-list` tools are not available in a scout run, so this is the in-run lookup path.
+- **Got a team, not a person? Resolve the slug.** `scout-members-list` with `team=<bare slug>` (no `@your-org/` prefix) returns that team's members, maintainers first, so a slug from a note, from CODEOWNERS, or from an owners file becomes reviewers you can route. Take the first 1 to 3 and route them by `user_uuid`; prefer one when a maintainer clearly owns the area. An error back means the roster isn't synced for that slug, not that the team doesn't exist: fall back to name or email matching, and never report the team as missing. The roster is a periodic snapshot, so it can lag the live team.
- **Set `reason` on every reviewer you name.** One sentence of the concrete evidence tying this person to the affected surface ("created the affected dashboard", "human correction on the prior tracing report routed to them"). It is persisted on the report, so humans and future runs can tell an evidence-backed route from a guess without replaying your transcript. A reviewer you can't write a reason for is a reviewer you haven't verified.
- **Check for human corrections first.** A human swapping a suggested reviewer for someone else is the strongest ownership evidence there is, so treat it as authoritative precedent over commit history and fold it into your `reviewer:` memory keys. A `report_reviewer_correction` note tells you when one lands on a report you filed or on a login you already hold, and the condense rule for it is in *Notes left for you*. The project profile's `recent_reviewer_corrections` carries the recent ones; for history beyond that window, query `advanced-activity-logs-list` with `scopes=["SignalReport"]`, `activities=["suggested_reviewers_changed"]` (on an org without the audit-logs feature that call fails with a payment-required error: skip it, don't retry).
- **Weigh other precedent by its evidence, not its existence.** A comparable report's reviewer entries (via `inbox-report-artefacts-list`) or your own `reviewer:` memory are strong precedent when they carry `relevant_commits`, a concrete `reason`, or a human correction behind them, and are an earlier run's unexplained guess when they carry none of those. Precedent is self-reinforcing, so every blind reuse becomes the next run's precedent and compounds a mis-route indefinitely: corroborate from what you gathered this run (an entity's `created_by`, the owning team, recent authors in the data), or say so in `reason` ("inherited from report X, unverified").
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 513b0b3ffd01..7bdcafb62ef9 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -4010,6 +4010,31 @@ class ScoutMembersQuerySerializer(serializers.Serializer):
"large project's roster to the owner you're trying to match instead of pulling every member."
),
)
+ team = serializers.CharField(
+ required=False,
+ help_text=(
+ "Team slug (case-insensitive, no `@org/` prefix), for example `team-desktop`. Narrows the roster "
+ "to the members on that team, maintainers first, so a slug from a scout note, CODEOWNERS, or an "
+ "owners file resolves to people you can route to. Returns an error, not an empty list, when "
+ "the project has no synced team roster or the roster holds no rows for the slug."
+ ),
+ )
+
+
+class ScoutMemberTeamSerializer(serializers.Serializer):
+ """One team a member belongs to, from the project's synced team roster."""
+
+ provider = serializers.CharField(
+ help_text="Where the team is defined, for example `github`. Today every team comes from GitHub."
+ )
+ slug = serializers.CharField(help_text="The team's slug, lowercased. For example `team-desktop`.")
+ name = serializers.CharField(help_text="The team's display name. For example `Team Desktop`.")
+ is_maintainer = serializers.BooleanField(
+ help_text=(
+ "True when this member maintains the team. Prefer maintainers when you pick reviewers for a "
+ "team, and treat false as 'not known to maintain it': some rosters sync without roles."
+ )
+ )
class ScoutMemberSerializer(serializers.Serializer):
@@ -4033,3 +4058,11 @@ class ScoutMemberSerializer(serializers.Serializer):
"means no draft PR can be opened as that person."
),
)
+ teams = ScoutMemberTeamSerializer(
+ many=True,
+ help_text=(
+ "The teams this member is on, from the project's synced team roster. Empty when no roster is "
+ "synced, or when the member has no linked GitHub account, since the roster is keyed on that "
+ "login. The roster is a periodic snapshot, so it can lag the live team."
+ ),
+ )
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 890f1209e94a..c8cfa4289fa3 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -2281,6 +2281,34 @@ class SignalScoutMetadataViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
return Response(ScoutMetadataSerializer(metadata.as_dict()).data)
+# A team filter that finds nothing has two very different causes, and a scout that reads both as
+# "no such team" stops routing to a team that exists. The roster endpoint is off by default at the
+# GitHub source, so an absent slug is much more often unsynced coverage than a wrong name.
+MEMBERSHIP_NOT_SYNCED = (
+ "This project has no synced team roster, so a team slug can't be resolved to people. Turn on the "
+ "`teams` and `team_members` schemas for the GitHub data warehouse source (they need the "
+ "organization Members permission), or match the owner by name or email instead."
+)
+TEAM_NOT_IN_ROSTER = (
+ "The synced team roster holds no members for '{team}'. Teams sync one by one, so this usually means "
+ "'{team}' isn't synced here rather than that it doesn't exist. Match the owner by name or email "
+ "instead, and don't report the team as missing."
+)
+
+
+class _TeamRosterUnavailable(exceptions.APIException):
+ """503 for a team roster the warehouse could not answer for. The project may well sync it, so
+ this must not read as the "turn the sync on" message above, which would send a scout to change
+ a setting that is already right."""
+
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ default_code = "team_roster_unavailable"
+ default_detail = (
+ "Couldn't read this project's team roster, so a team slug can't be resolved right now. Try the "
+ "call again. If it keeps failing, match the owner by name or email instead."
+ )
+
+
class SignalScoutMembersViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Project member roster for reviewer routing — sandbox-only.
@@ -2325,20 +2353,31 @@ class SignalScoutMembersViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
summary="List project members for reviewer routing",
description=(
"Return the people who can review work on this project — one row per member with access to it, "
- "each with their `user_uuid`, `email`, `first_name`/`last_name`, and resolved GitHub `login` (null "
- "when they have no linked GitHub identity). The cold-start reviewer-routing path: when a finding's "
- "owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` "
- "memory or inbox precedent, list members, match the owner by email/name, then put their resolved "
- "`github_login` in `suggested_reviewers` on `emit-report` / `edit-report`. Pass `search` to narrow "
- f"a large roster; the result is capped at {MAX_PROJECT_MEMBERS}. Strictly team-scoped."
+ "each with their `user_uuid`, `email`, `first_name`/`last_name`, resolved GitHub `login` (null "
+ "when they have no linked GitHub identity), and the `teams` they're on. The cold-start "
+ "reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` "
+ "and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner "
+ "by email/name, then put their resolved `github_login` in `suggested_reviewers` on `emit-report` / "
+ "`edit-report`. Pass `team` to resolve a team slug to the people on it, maintainers first. Pass "
+ f"`search` to narrow a large roster; the result is capped at {MAX_PROJECT_MEMBERS}. Strictly "
+ "team-scoped."
),
operation_id="signals_scout_members_list",
)
def list(self, request: Request, *args, **kwargs) -> Response:
validated = getattr(request, "validated_query_data", {}) or {}
canonical_team = self.team.parent_team or self.team
- members = list_project_members(canonical_team, search=validated.get("search") or None)
- return Response(ScoutMemberSerializer([dataclasses.asdict(member) for member in members], many=True).data)
+ team_slug = (validated.get("team") or "").strip().lstrip("@").rsplit("/", 1)[-1].lower() or None
+ roster = list_project_members(canonical_team, search=validated.get("search") or None, team_slug=team_slug)
+ if team_slug is not None and roster.membership_read_failed:
+ raise _TeamRosterUnavailable
+ if team_slug is not None and not roster.membership_synced:
+ raise exceptions.ValidationError({"detail": MEMBERSHIP_NOT_SYNCED})
+ if team_slug is not None and not roster.team_is_covered:
+ raise exceptions.ValidationError({"detail": TEAM_NOT_IN_ROSTER.format(team=team_slug)})
+ return Response(
+ ScoutMemberSerializer([dataclasses.asdict(member) for member in roster.members], many=True).data
+ )
def _reject_if_enabled_cap_reached(team_id: int, skill_name: str) -> None:
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 7bbe03d35ae0..37d7ab85b167 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -35,6 +35,7 @@ from posthog.temporal.oauth import (
create_oauth_access_token_for_user,
)
+from products.engineering_analytics.backend.facade.contracts import GitHubTeamMembership, GitHubTeamRoster
from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.models import (
SignalProjectProfile,
@@ -4386,6 +4387,15 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):
start.assert_not_called()
+_TEAM_ROSTER = "products.signals.backend.report_generation.team_membership.get_github_team_roster"
+
+
+def _membership(login: str, slug: str, *, is_maintainer: bool = False) -> GitHubTeamMembership:
+ return GitHubTeamMembership(
+ member_handle=login, team_slug=slug, team_name=slug.replace("-", " ").title(), is_maintainer=is_maintainer
+ )
+
+
class TestScoutHarnessMembersAPI(APIBaseTest):
def setUp(self) -> None:
super().setUp()
@@ -4394,6 +4404,9 @@ class TestScoutHarnessMembersAPI(APIBaseTest):
def _url(self) -> str:
return f"/api/projects/{self.team.id}/signals/scout/members/"
+ def _link_github(self, user: User, login: str) -> None:
+ UserSocialAuth.objects.create(user=user, provider="github", uid=f"gh-{login}", extra_data={"login": login})
+
def test_lists_project_members_with_resolved_github_login(self) -> None:
# self.user has a GitHub identity (login lowercased on resolution); a second member has
# none, so their `github_login` is null rather than dropping out of the roster.
@@ -4434,6 +4447,70 @@ class TestScoutHarnessMembersAPI(APIBaseTest):
assert self.user.email in emails
assert "[email protected]" not in emails
+ def test_team_filter_returns_the_team_with_its_maintainers_first(self) -> None:
+ # Routing input names a team while the artefact holds individuals, so the slug resolves to
+ # people. Guards both halves: the filter dropping a non-member, and the maintainer split.
+ self._link_github(self.user, "Plain")
+ maintainer = User.objects.create_and_join(self.organization, "[email protected]", None, first_name="Boss")
+ self._link_github(maintainer, "boss")
+ outsider = User.objects.create_and_join(self.organization, "[email protected]", None, first_name="Other")
+ self._link_github(outsider, "other")
+ roster = GitHubTeamRoster(
+ memberships=(
+ _membership("plain", "team-desktop"),
+ _membership("boss", "team-desktop", is_maintainer=True),
+ _membership("other", "team-signals"),
+ ),
+ synced=True,
+ )
+
+ with patch(_TEAM_ROSTER, return_value=roster):
+ response = self.client.get(self._url(), data={"team": "@PostHog/Team-Desktop"})
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ rows = response.json()
+ assert [row["email"] for row in rows] == ["[email protected]", self.user.email]
+ assert rows[0]["teams"] == [
+ {"provider": "github", "slug": "team-desktop", "name": "Team Desktop", "is_maintainer": True}
+ ]
+
+ @parameterized.expand(
+ [
+ # Nothing synced, so a 200 with an empty list would read as "nobody is on that team".
+ ("unsynced", GitHubTeamRoster(memberships=(), synced=False), "no synced team roster"),
+ # Synced, but no rows under this slug. Teams sync one at a time, so it is not a missing team.
+ (
+ "slug_not_covered",
+ GitHubTeamRoster(memberships=(_membership("someone", "team-signals"),), synced=True),
+ "isn't synced here",
+ ),
+ ]
+ )
+ def test_team_filter_that_resolves_nothing_says_why(self, _name: str, roster, expected: str) -> None:
+ with patch(_TEAM_ROSTER, return_value=roster):
+ response = self.client.get(self._url(), data={"team": "team-desktop"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert expected in response.json()["detail"]
+
+ def test_team_filter_reports_a_failed_roster_read_as_retryable(self) -> None:
+ # A read failure and an unsynced project both resolve nothing, but the fixes differ. Telling
+ # a scout to turn a sync on when the sync is already on sends it to change a correct setting,
+ # and it caches that reason.
+ with patch(_TEAM_ROSTER, side_effect=RuntimeError("warehouse down")):
+ response = self.client.get(self._url(), data={"team": "team-desktop"})
+
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE, response.content
+ assert "Try the call again" in response.json()["detail"]
+
+ def test_unfiltered_roster_survives_a_failing_membership_read(self) -> None:
+ # Teams ride along on the member list, so a warehouse failure must not take the roster down.
+ with patch(_TEAM_ROSTER, side_effect=RuntimeError("warehouse down")):
+ response = self.client.get(self._url())
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert [row["teams"] for row in response.json()] == [[]]
+
@parameterized.expand([("session", None), ("public_read_token", "read_only")])
def test_non_scout_auth_cannot_list_members(self, _name: str, scopes: PosthogMcpScopes | None) -> None:
# The roster (member PII) is gated on the internal `signal_scout_internal` scope object, so neither
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index e2eabe506828..7121c9a02c0f 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3676,6 +3676,20 @@ export interface SignalScoutManualRunApi {
started: boolean
}
+/**
+ * One team a member belongs to, from the project's synced team roster.
+ */
+export interface ScoutMemberTeamApi {
+ /** Where the team is defined, for example `github`. Today every team comes from GitHub. */
+ provider: string
+ /** The team's slug, lowercased. For example `team-desktop`. */
+ slug: string
+ /** The team's display name. For example `Team Desktop`. */
+ name: string
+ /** True when this member maintains the team. Prefer maintainers when you pick reviewers for a team, and treat false as 'not known to maintain it': some rosters sync without roles. */
+ is_maintainer: boolean
+}
+
/**
* One project member's routing identity, for picking a `suggested_reviewers` entry on a report.
*/
@@ -3693,6 +3707,8 @@ export interface ScoutMemberApi {
* @nullable
*/
github_login: string | null
+ /** The teams this member is on, from the project's synced team roster. Empty when no roster is synced, or when the member has no linked GitHub account, since the roster is keyed on that login. The roster is a periodic snapshot, so it can lag the live team. */
+ teams: ScoutMemberTeamApi[]
}
/**
@@ -6325,6 +6341,11 @@ export type SignalsScoutMembersListParams = {
* @minLength 1
*/
search?: string
+ /**
+ * Team slug (case-insensitive, no `@org/` prefix), for example `team-desktop`. Narrows the roster to the members on that team, maintainers first, so a slug from a scout note, CODEOWNERS, or an owners file resolves to people you can route to. Returns an error, not an empty list, when the project has no synced team roster or the roster holds no rows for the slug.
+ * @minLength 1
+ */
+ team?: string
}
export type SignalsScoutNotesListParams = {
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 1e48058eff7f..9f0eaff07608 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -1388,7 +1388,7 @@ export const getSignalsScoutMembersListUrl = (projectId: string, params?: Signal
}
/**
- * Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, and resolved GitHub `login` (null when they have no linked GitHub identity). The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their resolved `github_login` in `suggested_reviewers` on `emit-report` / `edit-report`. Pass `search` to narrow a large roster; the result is capped at 200. Strictly team-scoped.
+ * Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, resolved GitHub `login` (null when they have no linked GitHub identity), and the `teams` they're on. The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their resolved `github_login` in `suggested_reviewers` on `emit-report` / `edit-report`. Pass `team` to resolve a team slug to the people on it, maintainers first. Pass `search` to narrow a large roster; the result is capped at 200. Strictly team-scoped.
* @summary List project members for reviewer routing
*/
export const signalsScoutMembersList = async (
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index d7ee0a581dd6..17b051bc958d 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -769,13 +769,18 @@ tools:
title: List project members for reviewer routing
description: >
Return the people who can review work on this project — one row per member with access to it, each with
- their `user_uuid`, `email`, `first_name`/`last_name`, and resolved GitHub `login` (null when they have no
- linked GitHub identity). The cold-start reviewer-routing path: when a finding's owner can't be read off a
- fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list
- members, match the owner by email/name, then put their `user_uuid` in `suggested_reviewers` on
- `scout-emit-report` / `scout-edit-report`. Every member is routable this way; a null `github_login` only
- means no draft PR can be opened as that person. Pass `search` to narrow a large roster. Strictly
- team-scoped.
+ their `user_uuid`, `email`, `first_name`/`last_name`, resolved GitHub `login` (null when they have no linked
+ GitHub identity), and the `teams` they belong to. The cold-start reviewer-routing path: when a finding's
+ owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or
+ inbox precedent, list members, match the owner by email/name, then put their `user_uuid` in
+ `suggested_reviewers` on `scout-emit-report` / `scout-edit-report`. Every member is routable this way; a
+ null `github_login` only means no draft PR can be opened as that person. Pass `search` to narrow a large
+ roster by name or email. Pass `team` with a bare team slug (no `@org/` prefix) to turn a slug from a note,
+ from CODEOWNERS, or from an owners file into the people on that team, maintainers first: take the first 1 to
+ 3 rows, which is the cap `suggested_reviewers` enforces anyway. A `team` that resolves to nobody comes back
+ as an error saying which case it hit, because team rosters sync one by one and a slug with no rows almost
+ always means it isn't synced here rather than that the team doesn't exist. The roster is a periodic
+ snapshot, so it can lag the live team. Strictly team-scoped.
scout-metadata-get:
operation: signals_scout_metadata_get
enabled: true
diff --git a/products/signals/skills/authoring-scouts/references/report-contract.md b/products/signals/skills/authoring-scouts/references/report-contract.md
index 7eca658aabe3..34a56fdd9131 100644
--- a/products/signals/skills/authoring-scouts/references/report-contract.md
+++ b/products/signals/skills/authoring-scouts/references/report-contract.md
@@ -484,11 +484,22 @@ Otherwise resolve a `github_login`, cheapest source first:
Reuse that reviewer for the same area — the safest general recipe, available to every scout.
3. **CODEOWNERS / git** (only if the scout has a repo checkout).
`.github/CODEOWNERS` for the owning path, or the last `git log` author for the file.
- Neither usually hands you a usable login directly: CODEOWNERS entries are often **team** slugs (`@your-org/team-name`) and `git log` gives a name + email — both must be resolved to an **individual** GitHub login before you write the reviewer (a team slug or an email won't match any user).
-4. **`scout-members-list`** — the in-run roster lookup, for the cold-start case where the cheaper paths above don't resolve an owner.
- It returns this project's members, each with `user_uuid`, email, name, and a resolved `github_login`. Pass `search=` to narrow the result. Match the owner and route with `user_uuid`.
+ Neither hands you a reviewer directly: CODEOWNERS entries are often **team** slugs (`@your-org/team-name`) and `git log` gives a name + email. A reviewer is always an individual, so resolve either to people with `scout-members-list` before you write it.
+4. **`scout-members-list`** — the in-run roster lookup, for the cold-start case where the cheaper paths above don't resolve an owner, and the way a team slug becomes reviewers.
+ It returns this project's members, each with `user_uuid`, email, name, a resolved `github_login`, and the `teams` they're on. Pass `search=` to narrow by name or email. Match the owner and route with `user_uuid`.
The org-scoped `org-members-list` / `org-member-get-github-login` tools are **not available in a scout run** — a scoped-team token can't reach the org-nested endpoint, so don't build a scout's reviewer recipe around them.
+**Resolving a team slug to reviewers.** Call `scout-members-list` with `team=<slug>` (bare slug, no `@your-org/` prefix, case-insensitive). It returns the members of that team with its maintainers first, so:
+
+- Take the **first 1 to 3** rows and route them. Three is the cap `suggested_reviewers` enforces anyway, and past the maintainers the order carries no ownership signal, so a longer list dilutes rather than widens.
+- Prefer **one** reviewer when a maintainer is clearly the owner of the area. Add the next one or two only when the work spans the team.
+- Route each with `user_uuid`, the same as any other reviewer.
+
+Two things the roster can't tell you, which change what you should do rather than what you should report:
+
+- **A slug with no rows means "not synced here", not "no such team".** The GitHub `teams` and `team_members` schemas are off by default and need the organization Members permission, so coverage is partial on most projects. The tool returns an error saying which case it hit. Fall back to matching the owner by name or email, and don't write a report claiming the team doesn't exist.
+- **The roster is a snapshot, so it can lag the live team.** Someone who joined or left since the last sync is wrong here. Treat a surprising result as stale data, and cross-check against a recent author or an inbox precedent before routing on it alone.
+
**If you can't confidently identify a reviewer, leave `suggested_reviewers` empty** — the report still surfaces for a human to grab.
**Never guess a handle**: a wrong login mis-assigns the report (or silently fails to assign), which is worse than leaving it open.
And remember `edit_report` can set reviewers on a report later — so a report that surfaced routed to no one isn't stuck; once you resolve an owner, edit it in (which also re-runs autostart).
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index b6e66c878b7c..93e4a3d5d44d 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10215,7 +10215,7 @@
}
},
"scout-members-list": {
- "description": "Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, and resolved GitHub `login` (null when they have no linked GitHub identity). The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their `user_uuid` in `suggested_reviewers` on `scout-emit-report` / `scout-edit-report`. Every member is routable this way; a null `github_login` only means no draft PR can be opened as that person. Pass `search` to narrow a large roster. Strictly team-scoped.",
+ "description": "Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, resolved GitHub `login` (null when they have no linked GitHub identity), and the `teams` they belong to. The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their `user_uuid` in `suggested_reviewers` on `scout-emit-report` / `scout-edit-report`. Every member is routable this way; a null `github_login` only means no draft PR can be opened as that person. Pass `search` to narrow a large roster by name or email. Pass `team` with a bare team slug (no `@org/` prefix) to turn a slug from a note, from CODEOWNERS, or from an owners file into the people on that team, maintainers first: take the first 1 to 3 rows, which is the cap `suggested_reviewers` enforces anyway. A `team` that resolves to nobody comes back as an error saying which case it hit, because team rosters sync one by one and a slug with no rows almost always means it isn't synced here rather than that the team doesn't exist. The roster is a periodic snapshot, so it can lag the live team. Strictly team-scoped.",
"category": "Signals",
"feature": "signals",
"summary": "List project members for reviewer routing",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index e56ab4c5c426..68cad18859fd 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10787,7 +10787,7 @@
}
},
"scout-members-list": {
- "description": "Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, and resolved GitHub `login` (null when they have no linked GitHub identity). The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their `user_uuid` in `suggested_reviewers` on `scout-emit-report` / `scout-edit-report`. Every member is routable this way; a null `github_login` only means no draft PR can be opened as that person. Pass `search` to narrow a large roster. Strictly team-scoped.",
+ "description": "Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, resolved GitHub `login` (null when they have no linked GitHub identity), and the `teams` they belong to. The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their `user_uuid` in `suggested_reviewers` on `scout-emit-report` / `scout-edit-report`. Every member is routable this way; a null `github_login` only means no draft PR can be opened as that person. Pass `search` to narrow a large roster by name or email. Pass `team` with a bare team slug (no `@org/` prefix) to turn a slug from a note, from CODEOWNERS, or from an owners file into the people on that team, maintainers first: take the first 1 to 3 rows, which is the cap `suggested_reviewers` enforces anyway. A `team` that resolves to nobody comes back as an error saying which case it hit, because team rosters sync one by one and a slug with no rows almost always means it isn't synced here rather than that the team doesn't exist. The roster is a periodic snapshot, so it can lag the live team. Strictly team-scoped.",
"category": "Signals",
"feature": "signals",
"summary": "List project members for reviewer routing",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bc254f0b40bf..c1b363b453bf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -87153,6 +87153,20 @@ export namespace Schemas {
runs_remaining_today: number | null;
}
+ /**
+ * One team a member belongs to, from the project's synced team roster.
+ */
+ export interface ScoutMemberTeam {
+ /** Where the team is defined, for example `github`. Today every team comes from GitHub. */
+ provider: string;
+ /** The team's slug, lowercased. For example `team-desktop`. */
+ slug: string;
+ /** The team's display name. For example `Team Desktop`. */
+ name: string;
+ /** True when this member maintains the team. Prefer maintainers when you pick reviewers for a team, and treat false as 'not known to maintain it': some rosters sync without roles. */
+ is_maintainer: boolean;
+ }
+
/**
* One project member's routing identity, for picking a `suggested_reviewers` entry on a report.
*/
@@ -87170,6 +87184,8 @@ export namespace Schemas {
* @nullable
*/
github_login: string | null;
+ /** The teams this member is on, from the project's synced team roster. Empty when no roster is synced, or when the member has no linked GitHub account, since the roster is keyed on that login. The roster is a periodic snapshot, so it can lag the live team. */
+ teams: ScoutMemberTeam[];
}
/**
@@ -113060,6 +113076,11 @@ export namespace Schemas {
* @minLength 1
*/
search?: string;
+ /**
+ * Team slug (case-insensitive, no `@org/` prefix), for example `team-desktop`. Narrows the roster to the members on that team, maintainers first, so a slug from a scout note, CODEOWNERS, or an owners file resolves to people you can route to. Returns an error, not an empty list, when the project has no synced team roster or the roster holds no rows for the slug.
+ * @minLength 1
+ */
+ team?: string;
};
export type SignalsScoutNotesListParams = {
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 383239df9f93..0744198ef01f 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -1319,7 +1319,7 @@ export const SignalsScoutConfigSyncQueryParams = () => zod.object({
})
/**
- * Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, and resolved GitHub `login` (null when they have no linked GitHub identity). The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their resolved `github_login` in `suggested_reviewers` on `emit-report` / `edit-report`. Pass `search` to narrow a large roster; the result is capped at 200. Strictly team-scoped.
+ * Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, resolved GitHub `login` (null when they have no linked GitHub identity), and the `teams` they're on. The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their resolved `github_login` in `suggested_reviewers` on `emit-report` / `edit-report`. Pass `team` to resolve a team slug to the people on it, maintainers first. Pass `search` to narrow a large roster; the result is capped at 200. Strictly team-scoped.
* @summary List project members for reviewer routing
*/
export const SignalsScoutMembersListParams = () => zod.object({
@@ -1338,6 +1338,13 @@ export const SignalsScoutMembersListQueryParams = () => zod.object({
.describe(
"Case-insensitive substring filter over member email and first\/last name. Use it to narrow a large project's roster to the owner you're trying to match instead of pulling every member."
),
+ team: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ 'Team slug (case-insensitive, no `@org\/` prefix), for example `team-desktop`. Narrows the roster to the members on that team, maintainers first, so a slug from a scout note, CODEOWNERS, or an owners file resolves to people you can route to. Returns an error, not an empty list, when the project has no synced team roster or the roster holds no rows for the slug.'
+ ),
})
/**
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 3ed7c907f570..9ac53ad7cfdd 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -1181,6 +1181,7 @@ const scoutMembersList = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/members/`,
query: {
search: params.search,
+ team: params.team,
},
})
return await withPostHogUrl(context, result, '/inbox')
@@ -2101,6 +2102,7 @@ const signalsScoutMembersList = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/members/`,
query: {
search: params.search,
+ team: params.team,
},
})
return await withPostHogUrl(context, result, '/inbox')