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): add scout-only activity summary search (#127443)

posthog[bot]79b55098ac39
diff --git a/products/signals/backend/activity_summary/prompt.py b/products/signals/backend/activity_summary/prompt.py
index d3792041871b..8208cf33defc 100644
--- a/products/signals/backend/activity_summary/prompt.py
+++ b/products/signals/backend/activity_summary/prompt.py
@@ -21,6 +21,10 @@ from products.signals.backend.activity_summary.render import (
days_text,
)
+# The document key that `summary_text` is embedded under.
+EMBEDDING_DOCUMENT_TYPE = "activity_summary"
+EMBEDDING_RENDERING = "summary_text"
+
PROMPT_VERSION = 8
MAX_THEMES = 6
diff --git a/products/signals/backend/activity_summary/read.py b/products/signals/backend/activity_summary/read.py
index 95f9b7ba5907..692b14e2f42b 100644
--- a/products/signals/backend/activity_summary/read.py
+++ b/products/signals/backend/activity_summary/read.py
@@ -107,19 +107,24 @@ def _computed(value: Any) -> dict[str, Any] | None:
return {"tasks": [], "mcp_sessions": [], **value}
-def _readable_config(team: Team) -> ActivitySummaryConfig | None:
+def readable_config(team: Team) -> ActivitySummaryConfig | None:
config = read_config()
return config if is_team_enrolled_for_read(config, team) else None
def get_summary(team: Team, user_id: int) -> ActivitySummaryView | None:
"""The user's current summary. A failed later update keeps the last good summary, so it is still ready."""
- config = _readable_config(team)
+ config = readable_config(team)
if config is None:
return None
row = UserActivitySummary.objects.for_team(team.id).filter(user_id=user_id).first()
- if row is None or not isinstance(row.summary, dict) or row.generated_at is None:
- return ActivitySummaryView(status=ActivitySummaryStatus.NOT_READY)
+ return (row and ready_view(row, config)) or ActivitySummaryView(status=ActivitySummaryStatus.NOT_READY)
+
+
+def ready_view(row: UserActivitySummary, config: ActivitySummaryConfig) -> ActivitySummaryView | None:
+ """The view of a stored summary, or `None` when no update succeeded yet."""
+ if not isinstance(row.summary, dict) or row.generated_at is None:
+ return None
return ActivitySummaryView(
status=ActivitySummaryStatus.READY,
headline=_headline(row.summary),
@@ -157,7 +162,7 @@ def list_versions(
With `version`, the list holds only that version, with its profile, or nothing when it does not exist.
"""
- config = _readable_config(team)
+ config = readable_config(team)
if config is None:
return None
rows = UserActivitySummaryVersion.objects.for_team(team.id).filter(summary_row__user_id=user_id)
diff --git a/products/signals/backend/activity_summary/search.py b/products/signals/backend/activity_summary/search.py
new file mode 100644
index 000000000000..d5a3f80bcda9
--- /dev/null
+++ b/products/signals/backend/activity_summary/search.py
@@ -0,0 +1,373 @@
+"""Search the activity summaries of a project's members, for scout reviewer routing.
+
+A keyword search matches the query terms in the profile, the headline, the theme labels and the names of
+owned and watched objects. A semantic search ranks the newest `summary_text` vector of each member by its
+distance to the query. A hybrid search merges both rankings with reciprocal rank fusion, because the vector
+holds only the headline and the theme labels, so an object name or a detail in the profile matches on
+keywords only. A failed semantic read leaves a hybrid search with the keyword ranking.
+
+Only members in `team.all_users_with_access()` can match, so a person who lost access drops out.
+"""
+
+import re
+import datetime
+from collections.abc import Iterable, Sequence
+from typing import Any, cast
+
+from django.db import models
+from django.db.models import prefetch_related_objects
+
+import structlog
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.clickhouse.workload import Workload
+from posthog.dataclasses import frozen
+from posthog.models import Team, User
+from posthog.ph_client import feature_enabled_or_false
+
+from products.signals.backend.activity_summary.prompt import EMBEDDING_DOCUMENT_TYPE, EMBEDDING_RENDERING
+from products.signals.backend.activity_summary.read import (
+ ActivitySummaryTheme,
+ ActivitySummaryView,
+ readable_config,
+ ready_view,
+)
+from products.signals.backend.models import UserActivitySummary
+from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS
+from products.signals.backend.report_embeddings import EMBEDDING_PRODUCT
+from products.signals.backend.signal_metadata import EMBEDDING_MODEL
+
+logger = structlog.get_logger(__name__)
+
+SEARCH_FLAG = "activity-summary-search"
+DEFAULT_LIMIT = 10
+MAX_LIMIT = 25
+# The standard constant from the reciprocal rank fusion paper. It keeps one top rank from outweighing
+# agreement between the two rankings.
+RRF_K = 60
+EMBEDDING_TIMEOUT_S = 10.0
+# A stalled read must end inside the MCP request deadline, so that a hybrid search can still return its keyword ranking.
+VECTOR_READ_MAX_EXECUTION_S = 10
+MIN_TERM_CHARS = 2
+SNIPPET_RADIUS = 60
+
+# The text-embedding-3-small-1536 table, which is the model `tick.emit_summary_embedding` writes.
+EMBEDDINGS_TABLE = "distributed_posthog_document_embeddings_text_embedding_3_small_1536"
+
+# `document_id` is `<user_id>:<date>`, so a member has one row per day with an update. The newest one is
+# the current summary. The user filter runs before the limit, so other filters cannot starve the result.
+NEAREST_MEMBERS_SQL = f"""
+SELECT user_id, cosineDistance(embedding, %(embedding)s) AS distance
+FROM (
+ SELECT
+ splitByChar(':', document_id)[1] AS user_id,
+ argMax(embedding, (timestamp, inserted_at)) AS embedding
+ FROM {EMBEDDINGS_TABLE}
+ WHERE team_id = %(team_id)s
+ AND product = %(product)s
+ AND document_type = %(document_type)s
+ AND rendering = %(rendering)s
+ GROUP BY user_id
+ HAVING user_id IN %(user_ids)s
+)
+WHERE length(embedding) = %(dimensions)s
+ORDER BY distance ASC
+LIMIT %(limit)s
+"""
+
+
+class SearchMode(models.TextChoices):
+ HYBRID = "hybrid"
+ SEMANTIC = "semantic"
+ KEYWORD = "keyword"
+
+
+class MatchKind(models.TextChoices):
+ SEMANTIC = "semantic"
+ HEADLINE = "headline"
+ THEMES = "themes"
+ OWNED = "owned"
+ WATCHED = "watched"
+ PROFILE = "profile"
+
+
+class SemanticSearchUnavailable(Exception):
+ """The query embedding or the vector read failed, so a semantic-only search has no ranking."""
+
+
+@frozen
+class SearchMatch:
+ kind: MatchKind
+ # A short excerpt around the first keyword match. Null for a semantic match.
+ snippet: str | None = None
+
+
+@frozen
+class ActivitySummarySearchHit:
+ user_uuid: str
+ first_name: str
+ last_name: str
+ github_login: str | None
+ # The fused rank score. Null when the search had no query, so the order is newest first.
+ score: float | None
+ matched_on: tuple[SearchMatch, ...]
+ headline: str | None
+ themes: tuple[ActivitySummaryTheme, ...]
+ modes: tuple[str, ...]
+ generated_at: datetime.datetime | None
+ stale: bool
+ profile: str | None = None
+
+
+@frozen
+class ActivitySummarySearchResult:
+ results: tuple[ActivitySummarySearchHit, ...]
+ # False when a hybrid search fell back to keywords, or when the search did not ask for vectors.
+ semantic_used: bool
+ # Members with access and no ready summary, so the caller can see how much of the project it covered.
+ not_ready_count: int
+
+
+@frozen
+class _Candidate:
+ user: User
+ view: ActivitySummaryView
+ computed: dict[str, Any]
+
+
+def search_enabled(team: Team) -> bool:
+ organization_id = str(team.organization_id)
+ try:
+ return (
+ feature_enabled_or_false(
+ SEARCH_FLAG,
+ organization_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ send_feature_flag_events=False,
+ only_evaluate_locally=True,
+ )
+ is True
+ )
+ except Exception:
+ logger.exception("activity_summary_search_flag_check_failed", team_id=team.id)
+ return False
+
+
+def search_summaries(
+ team: Team,
+ *,
+ query: str | None = None,
+ search_mode: SearchMode = SearchMode.HYBRID,
+ product: str | None = None,
+ exclude_user_uuids: Sequence[str] = (),
+ include_profile: bool = False,
+ limit: int = DEFAULT_LIMIT,
+) -> ActivitySummarySearchResult | None:
+ """Rank the members of `team` whose activity summary matches `query`, best first.
+
+ Returns `None` when the team is not enrolled for reads or the search flag is off. Raises
+ `SemanticSearchUnavailable` only for a semantic search, because a hybrid one keeps its keyword ranking.
+ """
+ config = readable_config(team)
+ if config is None or not search_enabled(team):
+ return None
+ limit = max(1, min(limit, MAX_LIMIT))
+ members = {user.id: user for user in team.all_users_with_access().order_by("id")}
+ # Two queries, not a join: the summary's user FK has no database constraint.
+ rows = UserActivitySummary.objects.for_team(team.id).filter(user_id__in=members.keys())
+ excluded = {str(value) for value in exclude_user_uuids}
+ candidates: dict[int, _Candidate] = {}
+ ready_count = 0
+ for row in rows:
+ view = ready_view(row, config)
+ if view is None:
+ continue
+ ready_count += 1
+ candidate = _Candidate(user=members[row.user_id], view=view, computed=view.computed or {})
+ if str(candidate.user.uuid) in excluded or (product and not _uses_product(candidate.computed, product)):
+ continue
+ candidates[row.user_id] = candidate
+ not_ready_count = len(members) - ready_count
+
+ if not query or not query.strip():
+ ordered = sorted(
+ candidates.values(),
+ key=lambda c: c.view.generated_at or datetime.datetime.min.replace(tzinfo=datetime.UTC),
+ reverse=True,
+ )
+ selected = ordered[:limit]
+ _prefetch_github_identities(selected)
+ hits = [_hit(c, score=None, matches=(), include_profile=include_profile) for c in selected]
+ return ActivitySummarySearchResult(results=tuple(hits), semantic_used=False, not_ready_count=not_ready_count)
+
+ keyword_ranking: list[int] = []
+ keyword_matches: dict[int, tuple[SearchMatch, ...]] = {}
+ if search_mode != SearchMode.SEMANTIC:
+ keyword_ranking, keyword_matches = _keyword_ranking(candidates, _terms(query))
+
+ semantic_ranking: list[int] = []
+ semantic_used = False
+ if search_mode != SearchMode.KEYWORD and candidates:
+ try:
+ semantic_ranking = _semantic_ranking(team, query, candidates.keys(), limit=len(candidates))
+ semantic_used = True
+ except Exception as error:
+ logger.exception("activity_summary_search_semantic_failed", team_id=team.id)
+ if search_mode == SearchMode.SEMANTIC:
+ raise SemanticSearchUnavailable() from error
+
+ scores = _fuse([keyword_ranking, semantic_ranking])
+ semantic_ids = set(semantic_ranking)
+ top_scores = sorted(scores.items(), key=lambda item: (-item[1], item[0]))[:limit]
+ _prefetch_github_identities([candidates[user_id] for user_id, _ in top_scores])
+ hits = [
+ _hit(
+ candidates[user_id],
+ score=round(score, 6),
+ matches=(
+ *((SearchMatch(kind=MatchKind.SEMANTIC),) if user_id in semantic_ids else ()),
+ *keyword_matches.get(user_id, ()),
+ ),
+ include_profile=include_profile,
+ )
+ for user_id, score in top_scores
+ ]
+ return ActivitySummarySearchResult(
+ results=tuple(hits), semantic_used=semantic_used, not_ready_count=not_ready_count
+ )
+
+
+def _prefetch_github_identities(candidates: Sequence[_Candidate]) -> None:
+ # Deferred: resolve_reviewers imports the engineering_analytics facade, which imports the signals facade.
+ from products.signals.backend.report_generation.resolve_reviewers import ( # noqa: PLC0415
+ _github_identity_prefetches,
+ )
+
+ prefetch_related_objects([candidate.user for candidate in candidates], *_github_identity_prefetches())
+
+
+def _uses_product(computed: dict[str, Any], product: str) -> bool:
+ products = computed.get("products")
+ if not isinstance(products, dict):
+ return False
+ return any(isinstance(values, list) and product in values for values in products.values())
+
+
+def _terms(query: str | None) -> list[str]:
+ words = re.findall(r"\w+", (query or "").lower())
+ return list(dict.fromkeys(word for word in words if len(word) >= MIN_TERM_CHARS))
+
+
+def _object_names(computed: dict[str, Any], key: str) -> str:
+ items = computed.get(key)
+ if not isinstance(items, list):
+ return ""
+ return "\n".join(str(item.get("name") or "") for item in items if isinstance(item, dict))
+
+
+def _keyword_fields(candidate: _Candidate) -> dict[MatchKind, str]:
+ view = candidate.view
+ return {
+ MatchKind.HEADLINE: view.headline or "",
+ MatchKind.THEMES: "\n".join(theme.label for theme in view.themes),
+ MatchKind.OWNED: _object_names(candidate.computed, "owned"),
+ MatchKind.WATCHED: _object_names(candidate.computed, "watched"),
+ MatchKind.PROFILE: view.profile or "",
+ }
+
+
+def _snippet(text: str, start: int) -> str:
+ lo, hi = max(0, start - SNIPPET_RADIUS), min(len(text), start + SNIPPET_RADIUS)
+ return ("…" if lo else "") + " ".join(text[lo:hi].split()) + ("…" if hi < len(text) else "")
+
+
+def _keyword_ranking(
+ candidates: dict[int, _Candidate], terms: list[str]
+) -> tuple[list[int], dict[int, tuple[SearchMatch, ...]]]:
+ """Members that match at least one term, the most distinct terms first, then the most matched fields."""
+ if not terms:
+ return [], {}
+ patterns = [re.compile(rf"\b{re.escape(term)}", re.IGNORECASE) for term in terms]
+ ranked: list[tuple[int, int, int]] = []
+ matches: dict[int, tuple[SearchMatch, ...]] = {}
+ for user_id, candidate in candidates.items():
+ matched_terms: set[int] = set()
+ found: list[SearchMatch] = []
+ for kind, text in _keyword_fields(candidate).items():
+ first: int | None = None
+ for index, pattern in enumerate(patterns):
+ if (match := pattern.search(text)) is not None:
+ matched_terms.add(index)
+ first = match.start() if first is None else min(first, match.start())
+ if first is not None:
+ found.append(SearchMatch(kind=kind, snippet=_snippet(text, first)))
+ if found:
+ ranked.append((user_id, len(matched_terms), len(found)))
+ matches[user_id] = tuple(found)
+ ranked.sort(key=lambda item: (-item[1], -item[2], item[0]))
+ return [user_id for user_id, _, _ in ranked], matches
+
+
+def _semantic_ranking(team: Team, query: str, user_ids: Iterable[int], *, limit: int) -> list[int]:
+ # Deferred: `posthog.api` loads the product routes, which import this module through the signals facade.
+ from posthog.api.embedding_worker import generate_embedding # noqa: PLC0415
+
+ embedding = generate_embedding(team, query, model=EMBEDDING_MODEL.value, timeout=EMBEDDING_TIMEOUT_S).embedding
+ tag_queries(
+ product=Product.SIGNALS, feature=Feature.ENRICHMENT, team_id=team.id, query_type="activity_summary_search"
+ )
+ rows = cast(
+ list[tuple[Any, ...]],
+ sync_execute(
+ NEAREST_MEMBERS_SQL,
+ {
+ "embedding": embedding,
+ "team_id": team.id,
+ "product": EMBEDDING_PRODUCT,
+ "document_type": EMBEDDING_DOCUMENT_TYPE,
+ "rendering": EMBEDDING_RENDERING,
+ "user_ids": [str(user_id) for user_id in user_ids],
+ "dimensions": EMBEDDING_DIMENSIONS,
+ "limit": limit,
+ },
+ settings={"max_execution_time": VECTOR_READ_MAX_EXECUTION_S, "timeout_overflow_mode": "throw"},
+ # A scout run calls this, and no person waits on the result.
+ workload=Workload.OFFLINE,
+ team_id=team.id,
+ ch_user=ClickHouseUser.SIGNALS,
+ )
+ or [],
+ )
+ return [int(user_id) for user_id, _ in rows]
+
+
+def _fuse(rankings: Sequence[Sequence[int]]) -> dict[int, float]:
+ scores: dict[int, float] = {}
+ for ranking in rankings:
+ for rank, user_id in enumerate(ranking, start=1):
+ scores[user_id] = scores.get(user_id, 0.0) + 1.0 / (RRF_K + rank)
+ return scores
+
+
+def _hit(
+ candidate: _Candidate, *, score: float | None, matches: tuple[SearchMatch, ...], include_profile: bool
+) -> ActivitySummarySearchHit:
+ user, view = candidate.user, candidate.view
+ login = user.get_github_login()
+ return ActivitySummarySearchHit(
+ user_uuid=str(user.uuid),
+ first_name=user.first_name,
+ last_name=user.last_name,
+ github_login=login.lower() if login else None,
+ score=score,
+ matched_on=matches,
+ headline=view.headline,
+ themes=view.themes,
+ modes=view.modes,
+ generated_at=view.generated_at,
+ stale=view.stale,
+ profile=view.profile if include_profile else None,
+ )
diff --git a/products/signals/backend/activity_summary/tick.py b/products/signals/backend/activity_summary/tick.py
index b97744ad90b9..37ad55c9addc 100644
--- a/products/signals/backend/activity_summary/tick.py
+++ b/products/signals/backend/activity_summary/tick.py
@@ -40,7 +40,12 @@ from products.signals.backend.activity_summary.logic import (
update_activity_summary,
)
from products.signals.backend.activity_summary.mcp_buffer import publish_team_ids
-from products.signals.backend.activity_summary.prompt import PROMPT_VERSION, summary_profile_text
+from products.signals.backend.activity_summary.prompt import (
+ EMBEDDING_DOCUMENT_TYPE,
+ EMBEDDING_RENDERING,
+ PROMPT_VERSION,
+ summary_profile_text,
+)
from products.signals.backend.activity_summary.queue import (
TRIGGERS,
VIEW_TRIGGERS,
@@ -63,8 +68,6 @@ from products.signals.backend.report_embeddings import EMBEDDING_PRODUCT
logger = structlog.get_logger(__name__)
TICK_WORKFLOW_NAME = "activity-summary-tick"
-EMBEDDING_DOCUMENT_TYPE = "activity_summary"
-EMBEDDING_RENDERING = "summary_text"
# The same document as `EMBEDDING_RENDERING`, embedded with the profile, the way report embeddings
# separate `title` from `title_summary`.
EMBEDDING_RENDERING_PROFILE = "summary_profile"
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index 092dd8be9c65..658f4a2e1e37 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -37,6 +37,11 @@ from products.signals.backend.activity_summary.read import (
ActivitySummaryVersionView as ActivitySummaryVersionView,
ActivitySummaryView as ActivitySummaryView,
)
+from products.signals.backend.activity_summary.search import (
+ ActivitySummarySearchResult as ActivitySummarySearchResult,
+ SearchMode,
+ search_summaries,
+)
from products.signals.backend.anomaly_scores import search as anomaly_search
from products.signals.backend.anomaly_scores.search import (
AnomalyDashboardNotFound as AnomalyDashboardNotFound,
@@ -238,6 +243,28 @@ def list_activity_summary_versions(
return activity_summary_read.list_versions(team, user_id, limit=limit, version=version)
+def search_activity_summaries(
+ *,
+ team: Team,
+ query: str | None,
+ search_mode: SearchMode,
+ product: str | None,
+ exclude_user_uuids: list[str],
+ include_profile: bool,
+ limit: int,
+) -> ActivitySummarySearchResult | None:
+ """The project members whose activity summary matches `query`, or None when search is off for the team."""
+ return search_summaries(
+ team,
+ query=query,
+ search_mode=search_mode,
+ product=product,
+ exclude_user_uuids=exclude_user_uuids,
+ include_profile=include_profile,
+ limit=limit,
+ )
+
+
def search_anomalies(*, team: Team, user: User, filters: AnomalySearchFilters, now: datetime) -> AnomalySearchResult:
"""The anomaly rate of each scored insight series the user can read, most anomalous first."""
return anomaly_search.search(team, user, filters, now)
diff --git a/products/signals/backend/presentation/activity_summary.py b/products/signals/backend/presentation/activity_summary.py
index 8ec7680eb617..95b17da8b88e 100644
--- a/products/signals/backend/presentation/activity_summary.py
+++ b/products/signals/backend/presentation/activity_summary.py
@@ -6,11 +6,12 @@ from django.db import models
from drf_spectacular.utils import OpenApiResponse, extend_schema_serializer
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound, PermissionDenied
+from rest_framework.exceptions import APIException, NotFound, PermissionDenied
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.fields import JSONTolerantListField
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import (
@@ -20,13 +21,21 @@ from posthog.auth import (
is_mcp_request,
)
from posthog.event_usage import report_user_action
-from posthog.models import User
+from posthog.models import Team, User
from posthog.permissions import APIScopePermission, is_service_auth
from products.signals.backend.activity_summary.prompt import ActivitySummaryMode
from products.signals.backend.activity_summary.read import DEFAULT_VERSIONS_LIMIT, ActivitySummaryStatus
from products.signals.backend.activity_summary.render import Product
+from products.signals.backend.activity_summary.search import (
+ DEFAULT_LIMIT as SEARCH_DEFAULT_LIMIT,
+ MAX_LIMIT as SEARCH_MAX_LIMIT,
+ MatchKind,
+ SearchMode,
+ SemanticSearchUnavailable,
+)
from products.signals.backend.facade import api as signals_facade
+from products.signals.backend.presentation.scout_permissions import ScoutCanonicalTeamAccessPermission
READ_EVENT = "activity summary read"
@@ -280,3 +289,166 @@ class ActivitySummaryViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
count=len(versions),
)
return Response(ActivitySummaryVersionSerializer([asdict(version) for version in versions], many=True).data)
+
+
+class ActivitySummarySearchQuerySerializer(serializers.Serializer):
+ query = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=500,
+ help_text="Natural language or keywords, such as an object name, a topic or a product area. "
+ "Without a query, the search lists members with a summary, the newest summary first.",
+ )
+ search_mode = serializers.ChoiceField(
+ choices=SearchMode.choices,
+ default=SearchMode.HYBRID,
+ help_text="`hybrid` merges the keyword and semantic rankings. `semantic` ranks by meaning only, and "
+ "returns 503 when the vector search fails. `keyword` matches query terms in the profile, the headline, "
+ "the theme labels and the names of owned and watched objects.",
+ )
+ product = serializers.ChoiceField(
+ choices=ActivitySummaryProduct.choices,
+ required=False,
+ help_text="Only members who work in or visit this product.",
+ )
+ exclude_user_uuids = JSONTolerantListField(
+ child=serializers.UUIDField(),
+ required=False,
+ default=list,
+ help_text="Members to leave out, such as people you already checked.",
+ )
+ include_profile = serializers.BooleanField(
+ default=False,
+ help_text="Add the one-page markdown profile to each result. Set it only for the people you want to read.",
+ )
+ limit = serializers.IntegerField(
+ min_value=1,
+ max_value=SEARCH_MAX_LIMIT,
+ default=SEARCH_DEFAULT_LIMIT,
+ help_text="The most results to return, best match first.",
+ )
+
+
+class ActivitySummarySearchMatchSerializer(serializers.Serializer):
+ kind = serializers.ChoiceField(
+ choices=MatchKind.choices,
+ help_text="`semantic` for a vector match, else the summary field a keyword matched.",
+ )
+ snippet = serializers.CharField(
+ allow_null=True, help_text="A short excerpt around the first keyword match. Null for a semantic match."
+ )
+
+
+class ActivitySummarySearchHitSerializer(serializers.Serializer):
+ user_uuid = serializers.UUIDField(help_text="The member. Use it in `suggested_reviewers`.")
+ first_name = serializers.CharField(help_text="The member's first name.")
+ last_name = serializers.CharField(help_text="The member's last name.")
+ github_login = serializers.CharField(
+ allow_null=True, help_text="The member's GitHub login, lowercase. Null when no GitHub identity is linked."
+ )
+ score = serializers.FloatField(
+ allow_null=True,
+ help_text="The reciprocal rank fusion score. Higher is a better match. Null when the request had no query.",
+ )
+ matched_on = ActivitySummarySearchMatchSerializer(many=True, help_text="Why this member matched.")
+ headline = serializers.CharField(
+ allow_null=True, help_text="One or two sentences about what the member works on in this project."
+ )
+ themes = ActivitySummaryThemeSerializer(many=True, help_text="The main threads of the member's work.")
+ modes = serializers.ListField(
+ child=serializers.ChoiceField(choices=ActivitySummaryMode.choices),
+ help_text="How the member works in this project overall, the main mode first.",
+ )
+ generated_at = serializers.DateTimeField(allow_null=True, help_text="When this summary was written.")
+ stale = serializers.BooleanField(help_text="True when a newer version will replace this summary soon.")
+ profile = serializers.CharField(
+ allow_null=True, help_text="The one-page markdown profile. Set only when the request sets `include_profile`."
+ )
+
+
+class ActivitySummarySearchResultSerializer(serializers.Serializer):
+ results = ActivitySummarySearchHitSerializer(many=True, help_text="The matching members, best match first.")
+ semantic_used = serializers.BooleanField(
+ help_text="False when the search used keywords only: a `keyword` search, a request with no query, or a "
+ "`hybrid` search whose vector search failed."
+ )
+ not_ready_count = serializers.IntegerField(
+ help_text="Members with access to the project and no summary yet. The search cannot find them."
+ )
+
+
+class _SemanticSearchUnavailable(APIException):
+ status_code = 503
+ default_detail = "The semantic search is unavailable. Try again, or use `search_mode=hybrid` or `keyword`."
+ default_code = "semantic_search_unavailable"
+
+
+class ActivitySummaryMembersViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Search the activity summaries of a project's members, for reviewer routing in a scout run.
+
+ `scope_object = "signal_scout_internal"` makes this reachable only with a scout sandbox token, as
+ `SignalScoutMembersViewSet` is: session auth, personal API keys and user-grantable OAuth tokens are rejected.
+ """
+
+ serializer_class = ActivitySummarySearchResultSerializer
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [IsAuthenticated, APIScopePermission, ScoutCanonicalTeamAccessPermission]
+ scope_object = "signal_scout_internal"
+ pagination_class = None
+
+ @validated_request(
+ query_serializer=ActivitySummarySearchQuerySerializer,
+ responses={200: OpenApiResponse(response=ActivitySummarySearchResultSerializer)},
+ summary="Search member activity summaries",
+ description="Find the project members whose activity summary matches a topic, an object or a product, "
+ "including people who only open the work and never edit it. Returns 404 when the search is not available "
+ "for this project.",
+ operation_id="signals_activity_summary_members_search",
+ )
+ @action(detail=False, methods=["GET"], required_scopes=["signal_scout_internal:read"])
+ def search(self, request: ValidatedRequest, *args: object, **kwargs: object) -> Response:
+ query = request.validated_query_data
+ team = self.team
+ properties = {
+ "search_mode": query["search_mode"],
+ "has_query": bool((query.get("query") or "").strip()),
+ "has_product": query.get("product") is not None,
+ "excluded_count": len(query["exclude_user_uuids"]),
+ "include_profile": query["include_profile"],
+ }
+ try:
+ result = signals_facade.search_activity_summaries(
+ team=team,
+ query=query.get("query"),
+ search_mode=query["search_mode"],
+ product=query.get("product"),
+ exclude_user_uuids=[str(value) for value in query["exclude_user_uuids"]],
+ include_profile=query["include_profile"],
+ limit=query["limit"],
+ )
+ except SemanticSearchUnavailable:
+ self._capture(request, team, "semantic_unavailable", **properties)
+ raise _SemanticSearchUnavailable()
+ if result is None:
+ self._capture(request, team, "not_enrolled", **properties)
+ raise NotFound()
+ self._capture(
+ request,
+ team,
+ ActivitySummaryStatus.READY,
+ **properties,
+ count=len(result.results),
+ semantic_used=result.semantic_used,
+ not_ready_count=result.not_ready_count,
+ )
+ return Response(ActivitySummarySearchResultSerializer(asdict(result)).data)
+
+ def _capture(self, request: Request, team: Team, status: str, **properties: Any) -> None:
+ # Counts and modes only. The query can repeat report content, and the results are member data.
+ report_user_action(
+ request.user,
+ READ_EVENT,
+ properties={"endpoint": "search", "status": status, "via_mcp": is_mcp_request(request), **properties},
+ team=team,
+ request=request,
+ )
diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.py
index 640b92c969cc..9277f6cf5825 100644
--- a/products/signals/backend/routes.py
+++ b/products/signals/backend/routes.py
@@ -1,7 +1,7 @@
from posthog.api.routing import RouterRegistry
import products.signals.backend.views as signals
-from products.signals.backend.presentation.activity_summary import ActivitySummaryViewSet
+from products.signals.backend.presentation.activity_summary import ActivitySummaryMembersViewSet, ActivitySummaryViewSet
from products.signals.backend.presentation.anomalies import AnomalyViewSet
from products.signals.backend.presentation.inbox_summary import InboxSummaryViewSet
from products.signals.backend.presentation.onboarding import InboxOnboardingViewSet
@@ -35,6 +35,12 @@ def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"signals/activity_summary", ActivitySummaryViewSet, "project_signals_activity_summary", ["team_id"]
)
+ routers.projects.register(
+ r"signals/activity_summary_members",
+ ActivitySummaryMembersViewSet,
+ "project_signals_activity_summary_members",
+ ["team_id"],
+ )
routers.projects.register(r"signals/anomalies", AnomalyViewSet, "project_signals_anomalies", ["team_id"])
routers.projects.register(
r"signals/scout/rubrics", SignalScoutRubricViewSet, "project_signals_scout_rubrics", ["team_id"]
diff --git a/products/signals/backend/test/test_activity_summary_api.py b/products/signals/backend/test/test_activity_summary_api.py
index f9634acc1851..80e7e03b23c4 100644
--- a/products/signals/backend/test/test_activity_summary_api.py
+++ b/products/signals/backend/test/test_activity_summary_api.py
@@ -1,3 +1,4 @@
+import json
import datetime
import dataclasses
from typing import Any
@@ -8,12 +9,14 @@ from unittest.mock import patch
from parameterized import parameterized
-from posthog.models import User
+from posthog.api.embedding_worker import EmbeddingResponse
+from posthog.models import Organization, User
from products.signals.backend.activity_summary.config import ActivitySummaryConfig
from products.signals.backend.activity_summary.prompt import PROMPT_VERSION
from products.signals.backend.activity_summary.render import RENDER_VERSION
from products.signals.backend.models import UserActivitySummary, UserActivitySummaryVersion
+from products.signals.backend.test.test_scout_harness_api import _authenticate_as_scout
NOW = datetime.datetime(2026, 10, 19, 12, tzinfo=datetime.UTC)
SUMMARY = {
@@ -245,3 +248,132 @@ class TestActivitySummaryAPI(APIBaseTest):
"computed": COMPUTED,
}
]
+
+
+SEARCH = "products.signals.backend.activity_summary.search"
+
+
+@time_machine.travel(NOW, tick=False)
+class TestActivitySummarySearchAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ self.config = ActivitySummaryConfig(enabled=True, organization_ids=(str(self.organization.id),))
+ for target, kwargs in (
+ ("products.signals.backend.activity_summary.read.read_config", {"side_effect": lambda: self.config}),
+ (f"{SEARCH}.feature_enabled_or_false", {"return_value": True}),
+ ("posthog.api.embedding_worker.generate_embedding", {"return_value": EmbeddingResponse([0.1], 1, False)}),
+ ):
+ patcher = patch(target, **kwargs)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.sync_execute = patch(f"{SEARCH}.sync_execute", return_value=[]).start()
+ self.addCleanup(patch.stopall)
+ self.reader = User.objects.create_and_join(self.organization, "[email protected]", None, first_name="Reader")
+ _authenticate_as_scout(self)
+
+ def _summary(self, user: User, headline: str, watched: str = "") -> None:
+ UserActivitySummary.objects.for_team(self.team.id).create(
+ team=self.team,
+ user=user,
+ status=UserActivitySummary.Status.OK,
+ summary={**SUMMARY, "headline": headline, "profile": f"## Work\n- {headline}"},
+ summary_text=headline,
+ generated_at=NOW,
+ prompt_version=PROMPT_VERSION,
+ render_version=RENDER_VERSION,
+ version=1,
+ computed={
+ **COMPUTED,
+ "watched": [
+ {
+ "ref": "o21",
+ "type": "dashboard",
+ "id": "7",
+ "name": watched,
+ "open_days": 9,
+ "last_at": "2026-10-18",
+ "not_theirs": True,
+ }
+ ]
+ if watched
+ else [],
+ },
+ )
+
+ def _search(self, **params: Any) -> Any:
+ return self.client.get(f"/api/projects/{self.team.id}/signals/activity_summary_members/search/", params)
+
+ def test_keyword_search_finds_a_reader_and_keeps_out_people_without_access(self) -> None:
+ self._summary(self.user, "Builds the billing dashboards.")
+ self._summary(self.reader, "Plans the roadmap.", watched="Onboarding drop-off")
+ outsider = User.objects.create_and_join(Organization.objects.create(name="Other"), "[email protected]", None)
+ self._summary(outsider, "Studies onboarding drop-off.")
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+
+ response = self._search(query="onboarding drop-off", search_mode="keyword")
+
+ assert response.status_code == 200, response.content
+ body = response.json()
+ assert [hit["user_uuid"] for hit in body["results"]] == [str(self.reader.uuid)]
+ assert body["results"][0]["matched_on"] == [{"kind": "watched", "snippet": "Onboarding drop-off"}]
+ assert body["results"][0]["profile"] is None
+ assert body["semantic_used"] is False
+ assert body["not_ready_count"] == 1
+ self.sync_execute.assert_not_called()
+
+ def test_hybrid_ranks_a_member_found_both_ways_first(self) -> None:
+ self._summary(self.user, "Builds onboarding funnels.")
+ self._summary(self.reader, "Watches activation.")
+ self.sync_execute.return_value = [(str(self.reader.id), 0.2), (str(self.user.id), 0.3)]
+
+ response = self._search(query="onboarding", include_profile="true")
+
+ body = response.json()
+ assert [hit["user_uuid"] for hit in body["results"]] == [str(self.user.uuid), str(self.reader.uuid)]
+ assert [match["kind"] for match in body["results"][0]["matched_on"]] == ["semantic", "headline", "profile"]
+ assert body["results"][0]["profile"] == "## Work\n- Builds onboarding funnels."
+ assert body["semantic_used"] is True
+
+ @parameterized.expand([("hybrid", 200), ("semantic", 503)])
+ def test_a_failed_vector_read_degrades_only_a_hybrid_search(self, mode: str, expected_status: int) -> None:
+ self._summary(self.reader, "Watches onboarding.")
+ self.sync_execute.side_effect = RuntimeError("clickhouse down")
+
+ response = self._search(query="onboarding", search_mode=mode)
+
+ assert response.status_code == expected_status, response.content
+ if expected_status == 200:
+ assert response.json()["semantic_used"] is False
+ assert [hit["user_uuid"] for hit in response.json()["results"]] == [str(self.reader.uuid)]
+
+ @parameterized.expand([("repeated_params", False), ("mcp_json_array", True)])
+ def test_excluded_members_and_other_products_drop_out(self, _name: str, json_encoded: bool) -> None:
+ self._summary(self.user, "Builds onboarding funnels.")
+ self._summary(self.reader, "Watches onboarding.")
+ excluded = [str(self.user.uuid)]
+ exclude_user_uuids = json.dumps(excluded) if json_encoded else excluded
+
+ response = self._search(
+ query="onboarding", search_mode="keyword", exclude_user_uuids=exclude_user_uuids, product="surveys"
+ )
+ assert response.json()["results"] == []
+ response = self._search(query="onboarding", search_mode="keyword", exclude_user_uuids=exclude_user_uuids)
+ assert response.status_code == 200, response.content
+ assert [hit["user_uuid"] for hit in response.json()["results"]] == [str(self.reader.uuid)]
+
+ @parameterized.expand([("flag_off", True), ("not_enrolled", False)])
+ def test_returns_404_when_search_is_off(self, _name: str, flag_off: bool) -> None:
+ if flag_off:
+ patch(f"{SEARCH}.feature_enabled_or_false", return_value=False).start()
+ else:
+ self.config = dataclasses.replace(self.config, enabled=False)
+
+ assert self._search(query="onboarding").status_code == 404
+
+ def test_session_auth_cannot_search(self) -> None:
+ self.client.credentials()
+ self.client.force_login(self.user)
+
+ assert self._search(query="onboarding").status_code == 403
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 289700031e8f..00bce3f162d2 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -308,6 +308,93 @@ export interface ActivitySummaryVersionApi {
computed: ActivitySummaryComputedApi | null
}
+/**
+ * * `semantic` - Semantic
+ * * `headline` - Headline
+ * * `themes` - Themes
+ * * `owned` - Owned
+ * * `watched` - Watched
+ * * `profile` - Profile
+ */
+export type MatchKindEnumApi = (typeof MatchKindEnumApi)[keyof typeof MatchKindEnumApi]
+
+export const MatchKindEnumApi = {
+ Semantic: 'semantic',
+ Headline: 'headline',
+ Themes: 'themes',
+ Owned: 'owned',
+ Watched: 'watched',
+ Profile: 'profile',
+} as const
+
+export interface ActivitySummarySearchMatchApi {
+ /** `semantic` for a vector match, else the summary field a keyword matched.
+ *
+ * * `semantic` - Semantic
+ * * `headline` - Headline
+ * * `themes` - Themes
+ * * `owned` - Owned
+ * * `watched` - Watched
+ * * `profile` - Profile */
+ kind: MatchKindEnumApi
+ /**
+ * A short excerpt around the first keyword match. Null for a semantic match.
+ * @nullable
+ */
+ snippet: string | null
+}
+
+export interface ActivitySummarySearchHitApi {
+ /** The member. Use it in `suggested_reviewers`. */
+ user_uuid: string
+ /** The member's first name. */
+ first_name: string
+ /** The member's last name. */
+ last_name: string
+ /**
+ * The member's GitHub login, lowercase. Null when no GitHub identity is linked.
+ * @nullable
+ */
+ github_login: string | null
+ /**
+ * The reciprocal rank fusion score. Higher is a better match. Null when the request had no query.
+ * @nullable
+ */
+ score: number | null
+ /** Why this member matched. */
+ matched_on: ActivitySummarySearchMatchApi[]
+ /**
+ * One or two sentences about what the member works on in this project.
+ * @nullable
+ */
+ headline: string | null
+ /** The main threads of the member's work. */
+ themes: ActivitySummaryThemeApi[]
+ /** How the member works in this project overall, the main mode first. */
+ modes: ActivitySummaryModeEnumApi[]
+ /**
+ * When this summary was written.
+ * @nullable
+ */
+ generated_at: string | null
+ /** True when a newer version will replace this summary soon. */
+ stale: boolean
+ /**
+ * The one-page markdown profile. Set only when the request sets `include_profile`.
+ * @nullable
+ */
+ profile: string | null
+}
+
+export interface ActivitySummarySearchResultApi {
+ /** The matching members, best match first. */
+ results: ActivitySummarySearchHitApi[]
+ /** False when the search used keywords only: a `keyword` search, a request with no query, or a `hybrid` search whose vector search failed. */
+ semantic_used: boolean
+ /** Members with access to the project and no summary yet. The search cannot find them. */
+ not_ready_count: number
+}
+
/**
* * `hour` - Hour
* * `day` - Day
@@ -10805,6 +10892,114 @@ export type SignalsActivitySummaryVersionsRetrieveParams = {
version?: number
}
+export type SignalsActivitySummaryMembersSearchParams = {
+ /**
+ * Members to leave out, such as people you already checked.
+ */
+ exclude_user_uuids?: string[]
+ /**
+ * Add the one-page markdown profile to each result. Set it only for the people you want to read.
+ */
+ include_profile?: boolean
+ /**
+ * The most results to return, best match first.
+ * @minimum 1
+ * @maximum 25
+ */
+ limit?: number
+ /**
+ * Only members who work in or visit this product.
+ *
+ * * `product_analytics` - Product Analytics
+ * * `dashboards` - Dashboards
+ * * `web_analytics` - Web Analytics
+ * * `session_replay` - Session Replay
+ * * `heatmaps` - Heatmaps
+ * * `error_tracking` - Error Tracking
+ * * `experiments` - Experiments
+ * * `feature_flags` - Feature Flags
+ * * `early_access_features` - Early Access Features
+ * * `surveys` - Surveys
+ * * `product_tours` - Product Tours
+ * * `notebooks` - Notebooks
+ * * `cohorts` - Cohorts
+ * * `persons` - Persons
+ * * `data_management` - Data Management
+ * * `data_warehouse` - Data Warehouse
+ * * `data_pipelines` - Data Pipelines
+ * * `workflows` - Workflows
+ * * `ai_observability` - Ai Observability
+ * * `mcp_analytics` - Mcp Analytics
+ * * `logs` - Logs
+ * * `tracing` - Tracing
+ * * `endpoints` - Endpoints
+ * * `revenue_analytics` - Revenue Analytics
+ * * `customer_analytics` - Customer Analytics
+ * * `inbox` - Inbox
+ * * `canvases` - Canvases
+ * * `support` - Support
+ * @minLength 1
+ */
+ product?: SignalsActivitySummaryMembersSearchProduct
+ /**
+ * Natural language or keywords, such as an object name, a topic or a product area. Without a query, the search lists members with a summary, the newest summary first.
+ * @maxLength 500
+ */
+ query?: string
+ /**
+ * `hybrid` merges the keyword and semantic rankings. `semantic` ranks by meaning only, and returns 503 when the vector search fails. `keyword` matches query terms in the profile, the headline, the theme labels and the names of owned and watched objects.
+ *
+ * * `hybrid` - Hybrid
+ * * `semantic` - Semantic
+ * * `keyword` - Keyword
+ * @minLength 1
+ */
+ search_mode?: SignalsActivitySummaryMembersSearchSearchMode
+}
+
+export type SignalsActivitySummaryMembersSearchProduct =
+ (typeof SignalsActivitySummaryMembersSearchProduct)[keyof typeof SignalsActivitySummaryMembersSearchProduct]
+
+export const SignalsActivitySummaryMembersSearchProduct = {
+ ProductAnalytics: 'product_analytics',
+ Dashboards: 'dashboards',
+ WebAnalytics: 'web_analytics',
+ SessionReplay: 'session_replay',
+ Heatmaps: 'heatmaps',
+ ErrorTracking: 'error_tracking',
+ Experiments: 'experiments',
+ FeatureFlags: 'feature_flags',
+ EarlyAccessFeatures: 'early_access_features',
+ Surveys: 'surveys',
+ ProductTours: 'product_tours',
+ Notebooks: 'notebooks',
+ Cohorts: 'cohorts',
+ Persons: 'persons',
+ DataManagement: 'data_management',
+ DataWarehouse: 'data_warehouse',
+ DataPipelines: 'data_pipelines',
+ Workflows: 'workflows',
+ AiObservability: 'ai_observability',
+ McpAnalytics: 'mcp_analytics',
+ Logs: 'logs',
+ Tracing: 'tracing',
+ Endpoints: 'endpoints',
+ RevenueAnalytics: 'revenue_analytics',
+ CustomerAnalytics: 'customer_analytics',
+ Inbox: 'inbox',
+ Canvases: 'canvases',
+ Support: 'support',
+} as const
+
+export type SignalsActivitySummaryMembersSearchSearchMode =
+ (typeof SignalsActivitySummaryMembersSearchSearchMode)[keyof typeof SignalsActivitySummaryMembersSearchSearchMode]
+
+export const SignalsActivitySummaryMembersSearchSearchMode = {
+ Hybrid: 'hybrid',
+ Semantic: 'semantic',
+ Keyword: 'keyword',
+} as const
+
export type SignalsAnomaliesInsightRetrieveParams = {
/**
* Earliest bucket start in the range. A relative date such as `-30d`, or an ISO 8601 date.
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 4ec5b635f5cf..8e701b1a1bdd 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -10,6 +10,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
ActivitySummaryApi,
+ ActivitySummarySearchResultApi,
ActivitySummaryVersionApi,
AnomalyInsightResponseApi,
AnomalySearchResponseApi,
@@ -145,6 +146,7 @@ import type {
SignalTeamConfigApi,
SignalUserAutonomyConfigApi,
SignalUserAutonomyConfigCreateApi,
+ SignalsActivitySummaryMembersSearchParams,
SignalsActivitySummaryVersionsRetrieveParams,
SignalsAnomaliesInsightRetrieveParams,
SignalsAnomaliesSearchRetrieveParams,
@@ -257,6 +259,40 @@ export const signalsActivitySummaryVersionsRetrieve = async (
})
}
+export const getSignalsActivitySummaryMembersSearchUrl = (
+ projectId: string,
+ params?: SignalsActivitySummaryMembersSearchParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/signals/activity_summary_members/search/?${stringifiedParams}`
+ : `/api/projects/${projectId}/signals/activity_summary_members/search/`
+}
+
+/**
+ * Find the project members whose activity summary matches a topic, an object or a product, including people who only open the work and never edit it. Returns 404 when the search is not available for this project.
+ * @summary Search member activity summaries
+ */
+export const signalsActivitySummaryMembersSearch = async (
+ projectId: string,
+ params?: SignalsActivitySummaryMembersSearchParams,
+ options?: RequestInit
+): Promise<ActivitySummarySearchResultApi> => {
+ return apiMutator<ActivitySummarySearchResultApi>(getSignalsActivitySummaryMembersSearchUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getSignalsAnomaliesInsightRetrieveUrl = (
projectId: string,
params: SignalsAnomaliesInsightRetrieveParams
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 99ffe8e6ef9f..235dd7d17672 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -23,6 +23,29 @@ tools:
users. `stale: true` means a newer version will replace it soon. A 404 means activity summaries are not
available for this project.
feature_flag: activity-summary
+ activity-summary-search:
+ operation: signals_activity_summary_members_search
+ enabled: true
+ scopes:
+ - signal_scout_internal:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Search member activity summaries
+ description: >
+ Find the project members whose activity summary matches a topic, an object name or a product, to route a
+ report to people connected to the work. It also finds people who only open the work and never edit it, such
+ as product managers, which the activity log cannot show. Search as you search anything: start broad with the
+ object, the topic and other wordings, then narrow with `product` or rephrase, and pass `exclude_user_uuids`
+ to skip people you already checked. Set `include_profile` only for the few people worth reading. `hybrid`
+ (the default) merges keyword and semantic ranking; `matched_on` says why each member matched. A result is a
+ lead, not an owner. Check it against the report before you select the person. If you select someone because
+ they open an object often, the `reason` must say so, such as "opens this dashboard most days", and must not
+ claim ownership. Ownership rules and human reviewer corrections take priority over this search.
+ `not_ready_count` is the number of members with no summary, whom the search cannot find. A 404 means the
+ search is not available for this project.
+ feature_flag: activity-summary-search
activity-summary-versions-list:
operation: signals_activity_summary_versions_retrieve
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index efad30b56a73..34a443be341d 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -663,6 +663,22 @@
},
"feature_flag": "activity-summary"
},
+ "activity-summary-search": {
+ "description": "Find the project members whose activity summary matches a topic, an object name or a product, to route a report to people connected to the work. It also finds people who only open the work and never edit it, such as product managers, which the activity log cannot show. Search as you search anything: start broad with the object, the topic and other wordings, then narrow with `product` or rephrase, and pass `exclude_user_uuids` to skip people you already checked. Set `include_profile` only for the few people worth reading. `hybrid` (the default) merges keyword and semantic ranking; `matched_on` says why each member matched. A result is a lead, not an owner. Check it against the report before you select the person. If you select someone because they open an object often, the `reason` must say so, such as \"opens this dashboard most days\", and must not claim ownership. Ownership rules and human reviewer corrections take priority over this search. `not_ready_count` is the number of members with no summary, whom the search cannot find. A 404 means the search is not available for this project.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Search member activity summaries",
+ "title": "Search member activity summaries",
+ "required_scopes": ["signal_scout_internal:read"],
+ "api_operations": ["GET /api/projects/{project_id}/signals/activity_summary_members/search/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "activity-summary-search"
+ },
"activity-summary-versions-list": {
"description": "List earlier versions of the current user's activity summary in this project, newest first, to see how their focus changed over time. Each version has a headline, the themes, the modes and `recent_shift`, which says what changed since the version before it. The list leaves out the profile and the `computed` fields to stay small. Pass `version` to get one version with its full profile and the `computed` fields that its theme refs point at. A 404 means activity summaries are not available for this project, or that the requested version does not exist.",
"category": "Signals",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 52245cfe76b7..a3598f273977 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -663,6 +663,22 @@
},
"feature_flag": "activity-summary"
},
+ "activity-summary-search": {
+ "description": "Find the project members whose activity summary matches a topic, an object name or a product, to route a report to people connected to the work. It also finds people who only open the work and never edit it, such as product managers, which the activity log cannot show. Search as you search anything: start broad with the object, the topic and other wordings, then narrow with `product` or rephrase, and pass `exclude_user_uuids` to skip people you already checked. Set `include_profile` only for the few people worth reading. `hybrid` (the default) merges keyword and semantic ranking; `matched_on` says why each member matched. A result is a lead, not an owner. Check it against the report before you select the person. If you select someone because they open an object often, the `reason` must say so, such as \"opens this dashboard most days\", and must not claim ownership. Ownership rules and human reviewer corrections take priority over this search. `not_ready_count` is the number of members with no summary, whom the search cannot find. A 404 means the search is not available for this project.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Search member activity summaries",
+ "title": "Search member activity summaries",
+ "required_scopes": ["signal_scout_internal:read"],
+ "api_operations": ["GET /api/projects/{project_id}/signals/activity_summary_members/search/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "activity-summary-search"
+ },
"activity-summary-versions-list": {
"description": "List earlier versions of the current user's activity summary in this project, newest first, to see how their focus changed over time. Each version has a headline, the themes, the modes and `recent_shift`, which says what changed since the version before it. The list leaves out the profile and the `computed` fields to stay small. Pass `version` to get one version with its full profile and the `computed` fields that its theme refs point at. A 404 means activity summaries are not available for this project, or that the requested version does not exist.",
"category": "Signals",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ca05bc1f1367..2e5176ff15ba 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -5699,6 +5699,94 @@ export namespace Schemas {
stale: boolean;
}
+ /**
+ * * `semantic` - Semantic
+ * * `headline` - Headline
+ * * `themes` - Themes
+ * * `owned` - Owned
+ * * `watched` - Watched
+ * * `profile` - Profile
+ */
+ export type MatchKindEnum = typeof MatchKindEnum[keyof typeof MatchKindEnum];
+
+
+ export const MatchKindEnum = {
+ Semantic: 'semantic',
+ Headline: 'headline',
+ Themes: 'themes',
+ Owned: 'owned',
+ Watched: 'watched',
+ Profile: 'profile',
+ } as const;
+
+ export interface ActivitySummarySearchMatch {
+ /** `semantic` for a vector match, else the summary field a keyword matched.
+ *
+ * * `semantic` - Semantic
+ * * `headline` - Headline
+ * * `themes` - Themes
+ * * `owned` - Owned
+ * * `watched` - Watched
+ * * `profile` - Profile */
+ kind: MatchKindEnum;
+ /**
+ * A short excerpt around the first keyword match. Null for a semantic match.
+ * @nullable
+ */
+ snippet: string | null;
+ }
+
+ export interface ActivitySummarySearchHit {
+ /** The member. Use it in `suggested_reviewers`. */
+ user_uuid: string;
+ /** The member's first name. */
+ first_name: string;
+ /** The member's last name. */
+ last_name: string;
+ /**
+ * The member's GitHub login, lowercase. Null when no GitHub identity is linked.
+ * @nullable
+ */
+ github_login: string | null;
+ /**
+ * The reciprocal rank fusion score. Higher is a better match. Null when the request had no query.
+ * @nullable
+ */
+ score: number | null;
+ /** Why this member matched. */
+ matched_on: ActivitySummarySearchMatch[];
+ /**
+ * One or two sentences about what the member works on in this project.
+ * @nullable
+ */
+ headline: string | null;
+ /** The main threads of the member's work. */
+ themes: ActivitySummaryTheme[];
+ /** How the member works in this project overall, the main mode first. */
+ modes: ActivitySummaryModeEnum[];
+ /**
+ * When this summary was written.
+ * @nullable
+ */
+ generated_at: string | null;
+ /** True when a newer version will replace this summary soon. */
+ stale: boolean;
+ /**
+ * The one-page markdown profile. Set only when the request sets `include_profile`.
+ * @nullable
+ */
+ profile: string | null;
+ }
+
+ export interface ActivitySummarySearchResult {
+ /** The matching members, best match first. */
+ results: ActivitySummarySearchHit[];
+ /** False when the search used keywords only: a `keyword` search, a request with no query, or a `hybrid` search whose vector search failed. */
+ semantic_used: boolean;
+ /** Members with access to the project and no summary yet. The search cannot find them. */
+ not_ready_count: number;
+ }
+
export interface ActivitySummaryVersion {
/** The number of this version. Higher numbers are newer. */
version: number;
@@ -142688,6 +142776,114 @@ export namespace Schemas {
version?: number;
};
+ export type SignalsActivitySummaryMembersSearchParams = {
+ /**
+ * Members to leave out, such as people you already checked.
+ */
+ exclude_user_uuids?: string[];
+ /**
+ * Add the one-page markdown profile to each result. Set it only for the people you want to read.
+ */
+ include_profile?: boolean;
+ /**
+ * The most results to return, best match first.
+ * @minimum 1
+ * @maximum 25
+ */
+ limit?: number;
+ /**
+ * Only members who work in or visit this product.
+ *
+ * * `product_analytics` - Product Analytics
+ * * `dashboards` - Dashboards
+ * * `web_analytics` - Web Analytics
+ * * `session_replay` - Session Replay
+ * * `heatmaps` - Heatmaps
+ * * `error_tracking` - Error Tracking
+ * * `experiments` - Experiments
+ * * `feature_flags` - Feature Flags
+ * * `early_access_features` - Early Access Features
+ * * `surveys` - Surveys
+ * * `product_tours` - Product Tours
+ * * `notebooks` - Notebooks
+ * * `cohorts` - Cohorts
+ * * `persons` - Persons
+ * * `data_management` - Data Management
+ * * `data_warehouse` - Data Warehouse
+ * * `data_pipelines` - Data Pipelines
+ * * `workflows` - Workflows
+ * * `ai_observability` - Ai Observability
+ * * `mcp_analytics` - Mcp Analytics
+ * * `logs` - Logs
+ * * `tracing` - Tracing
+ * * `endpoints` - Endpoints
+ * * `revenue_analytics` - Revenue Analytics
+ * * `customer_analytics` - Customer Analytics
+ * * `inbox` - Inbox
+ * * `canvases` - Canvases
+ * * `support` - Support
+ * @minLength 1
+ */
+ product?: SignalsActivitySummaryMembersSearchProduct;
+ /**
+ * Natural language or keywords, such as an object name, a topic or a product area. Without a query, the search lists members with a summary, the newest summary first.
+ * @maxLength 500
+ */
+ query?: string;
+ /**
+ * `hybrid` merges the keyword and semantic rankings. `semantic` ranks by meaning only, and returns 503 when the vector search fails. `keyword` matches query terms in the profile, the headline, the theme labels and the names of owned and watched objects.
+ *
+ * * `hybrid` - Hybrid
+ * * `semantic` - Semantic
+ * * `keyword` - Keyword
+ * @minLength 1
+ */
+ search_mode?: SignalsActivitySummaryMembersSearchSearchMode;
+ };
+
+ export type SignalsActivitySummaryMembersSearchProduct = typeof SignalsActivitySummaryMembersSearchProduct[keyof typeof SignalsActivitySummaryMembersSearchProduct];
+
+
+ export const SignalsActivitySummaryMembersSearchProduct = {
+ ProductAnalytics: 'product_analytics',
+ Dashboards: 'dashboards',
+ WebAnalytics: 'web_analytics',
+ SessionReplay: 'session_replay',
+ Heatmaps: 'heatmaps',
+ ErrorTracking: 'error_tracking',
+ Experiments: 'experiments',
+ FeatureFlags: 'feature_flags',
+ EarlyAccessFeatures: 'early_access_features',
+ Surveys: 'surveys',
+ ProductTours: 'product_tours',
+ Notebooks: 'notebooks',
+ Cohorts: 'cohorts',
+ Persons: 'persons',
+ DataManagement: 'data_management',
+ DataWarehouse: 'data_warehouse',
+ DataPipelines: 'data_pipelines',
+ Workflows: 'workflows',
+ AiObservability: 'ai_observability',
+ McpAnalytics: 'mcp_analytics',
+ Logs: 'logs',
+ Tracing: 'tracing',
+ Endpoints: 'endpoints',
+ RevenueAnalytics: 'revenue_analytics',
+ CustomerAnalytics: 'customer_analytics',
+ Inbox: 'inbox',
+ Canvases: 'canvases',
+ Support: 'support',
+ } as const;
+
+ export type SignalsActivitySummaryMembersSearchSearchMode = typeof SignalsActivitySummaryMembersSearchSearchMode[keyof typeof SignalsActivitySummaryMembersSearchSearchMode];
+
+
+ export const SignalsActivitySummaryMembersSearchSearchMode = {
+ Hybrid: 'hybrid',
+ Semantic: 'semantic',
+ Keyword: 'keyword',
+ } as const;
+
export type SignalsAnomaliesInsightRetrieveParams = {
/**
* Earliest bucket start in the range. A relative date such as `-30d`, or an ISO 8601 date.
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index b0714f6702e5..50d82e028b89 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 81 enabled ops
+ * PostHog API - MCP 82 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -45,6 +45,91 @@ export const SignalsActivitySummaryVersionsRetrieveQueryParams = () => zod.objec
.describe('Return only this version, with its full profile. Returns 404 when the version does not exist.'),
})
+/**
+ * Find the project members whose activity summary matches a topic, an object or a product, including people who only open the work and never edit it. Returns 404 when the search is not available for this project.
+ * @summary Search member activity summaries
+ */
+export const SignalsActivitySummaryMembersSearchParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const signalsActivitySummaryMembersSearchQueryIncludeProfileDefault = false
+export const signalsActivitySummaryMembersSearchQueryLimitDefault = 10
+export const signalsActivitySummaryMembersSearchQueryLimitMax = 25
+
+export const signalsActivitySummaryMembersSearchQueryQueryMax = 500
+
+export const signalsActivitySummaryMembersSearchQuerySearchModeDefault = `hybrid`
+
+export const SignalsActivitySummaryMembersSearchQueryParams = () => zod.object({
+ exclude_user_uuids: zod
+ .array(zod.string())
+ .optional()
+ .describe('Members to leave out, such as people you already checked.'),
+ include_profile: zod
+ .boolean()
+ .default(signalsActivitySummaryMembersSearchQueryIncludeProfileDefault)
+ .describe('Add the one-page markdown profile to each result. Set it only for the people you want to read.'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(signalsActivitySummaryMembersSearchQueryLimitMax)
+ .default(signalsActivitySummaryMembersSearchQueryLimitDefault)
+ .describe('The most results to return, best match first.'),
+ product: zod
+ .enum([
+ 'product_analytics',
+ 'dashboards',
+ 'web_analytics',
+ 'session_replay',
+ 'heatmaps',
+ 'error_tracking',
+ 'experiments',
+ 'feature_flags',
+ 'early_access_features',
+ 'surveys',
+ 'product_tours',
+ 'notebooks',
+ 'cohorts',
+ 'persons',
+ 'data_management',
+ 'data_warehouse',
+ 'data_pipelines',
+ 'workflows',
+ 'ai_observability',
+ 'mcp_analytics',
+ 'logs',
+ 'tracing',
+ 'endpoints',
+ 'revenue_analytics',
+ 'customer_analytics',
+ 'inbox',
+ 'canvases',
+ 'support',
+ ])
+ .optional()
+ .describe(
+ 'Only members who work in or visit this product.\n\n\* `product_analytics` - Product Analytics\n\* `dashboards` - Dashboards\n\* `web_analytics` - Web Analytics\n\* `session_replay` - Session Replay\n\* `heatmaps` - Heatmaps\n\* `error_tracking` - Error Tracking\n\* `experiments` - Experiments\n\* `feature_flags` - Feature Flags\n\* `early_access_features` - Early Access Features\n\* `surveys` - Surveys\n\* `product_tours` - Product Tours\n\* `notebooks` - Notebooks\n\* `cohorts` - Cohorts\n\* `persons` - Persons\n\* `data_management` - Data Management\n\* `data_warehouse` - Data Warehouse\n\* `data_pipelines` - Data Pipelines\n\* `workflows` - Workflows\n\* `ai_observability` - Ai Observability\n\* `mcp_analytics` - Mcp Analytics\n\* `logs` - Logs\n\* `tracing` - Tracing\n\* `endpoints` - Endpoints\n\* `revenue_analytics` - Revenue Analytics\n\* `customer_analytics` - Customer Analytics\n\* `inbox` - Inbox\n\* `canvases` - Canvases\n\* `support` - Support'
+ ),
+ query: zod
+ .string()
+ .max(signalsActivitySummaryMembersSearchQueryQueryMax)
+ .optional()
+ .describe(
+ 'Natural language or keywords, such as an object name, a topic or a product area. Without a query, the search lists members with a summary, the newest summary first.'
+ ),
+ search_mode: zod
+ .enum(['hybrid', 'semantic', 'keyword'])
+ .default(signalsActivitySummaryMembersSearchQuerySearchModeDefault)
+ .describe(
+ '`hybrid` merges the keyword and semantic rankings. `semantic` ranks by meaning only, and returns 503 when the vector search fails. `keyword` matches query terms in the profile, the headline, the theme labels and the names of owned and watched objects.\n\n\* `hybrid` - Hybrid\n\* `semantic` - Semantic\n\* `keyword` - Keyword'
+ ),
+})
+
/**
* Read-only anomaly rates of the saved trends insights that anomaly scoring checks.
* @summary Get the scored anomaly history of an insight
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 9ef65de4224f..aa52c1df1be9 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -31,6 +31,35 @@ const activitySummaryGet = (): ToolBase<ReturnType<typeof ActivitySummaryGetSche
},
})
+const ActivitySummarySearchSchema = () => {
+ const SignalsActivitySummaryMembersSearchQueryParams = orvalSchemas.SignalsActivitySummaryMembersSearchQueryParams()
+ return SignalsActivitySummaryMembersSearchQueryParams
+}
+
+const activitySummarySearch = (): ToolBase<
+ ReturnType<typeof ActivitySummarySearchSchema>,
+ Schemas.ActivitySummarySearchResult
+> => ({
+ name: 'activity-summary-search',
+ schema: ActivitySummarySearchSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof ActivitySummarySearchSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ActivitySummarySearchResult>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/activity_summary_members/search/`,
+ query: {
+ exclude_user_uuids: params.exclude_user_uuids,
+ include_profile: params.include_profile,
+ limit: params.limit,
+ product: params.product,
+ query: params.query,
+ search_mode: params.search_mode,
+ },
+ })
+ return result
+ },
+})
+
const ActivitySummaryVersionsListSchema = () => {
const SignalsActivitySummaryVersionsRetrieveQueryParams =
orvalSchemas.SignalsActivitySummaryVersionsRetrieveQueryParams()
@@ -3640,6 +3669,7 @@ const signalsScoutScratchpadSearch = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'activity-summary-get': activitySummaryGet,
+ 'activity-summary-search': activitySummarySearch,
'activity-summary-versions-list': activitySummaryVersionsList,
'anomaly-insight-get': anomalyInsightGet,
'anomaly-search': anomalySearch,
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index ce174ccec966..c57395b2bdeb 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -1180,7 +1180,7 @@ describe('Tool Filtering - Feature Flags', () => {
)
expect(flags).toContain('ai-observability-offline-evaluations')
expect(allFlags).not.toContain('dashboard-widgets')
- expect(flags).toHaveLength(35)
+ expect(flags).toHaveLength(36)
})
it('keeps human and task context wiki tools on separate scopes', () => {
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index 5a5d365f1c42..2797409d0ac8 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -114,6 +114,7 @@ async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {
'insight-data-checks': true,
'workflows-transactional-email-api': true,
'activity-summary': true,
+ 'activity-summary-search': true,
'personal-inbox-ranking': true,
'aeo-citation-tracking': true,
'mcp-session-recording-console-logs': true,