:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): serve the personal inbox ranking via for_me endpoint and mcp tool (#126454)
posthog[bot]c77543798c7c
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.mdindex 304ff6fbd331..2ed138533a79 100644--- a/products/signals/backend/management/AGENTS.md+++ b/products/signals/backend/management/AGENTS.md@@ -281,6 +281,9 @@ uv run manage.py run_personal_inbox_ranking --team-id 1 --user-id 1 --focus "cheA person with no ready activity summary still gets a list, marked `personalized: False`.When the model call fails or answers outside the schema, the list is in model order and `fallback_reason` says why.+`GET /api/projects/:id/signals/reports/for_me/` (`../personal_ranking/serve.py`) serves the same list to the user it describes, when the flag is on for that user.+It reuses the latest row for `freshness_minutes` while the input hash matches, and limits builds per person with `build_burst`, `builds_per_hour` and `builds_per_day` from the same payload.+## Tips- Compare runs by saving output: `list_signal_reports --json > run_baseline.json`diff --git a/products/signals/backend/personal_ranking/candidates.py b/products/signals/backend/personal_ranking/candidates.pyindex c568b722002e..1f440a1440b9 100644--- a/products/signals/backend/personal_ranking/candidates.py+++ b/products/signals/backend/personal_ranking/candidates.py@@ -261,8 +261,9 @@ def _clean(text: str | None, limit: int) -> str:def gather_candidates(- team: Team, user: User, config: PersonalRankingConfig, *, now: datetime.datetime+ team: Team, user: User, config: PersonalRankingConfig, *, now: datetime.datetime, with_sources: bool = True) -> list[Candidate]:+ """`with_sources=False` skips the ClickHouse read of each report's source, which only the prompt shows."""can_view_ranking = can_view_inbox_ranking(user, team)merged = merge_pools(_pools(team, user, config, now=now, can_view_ranking=can_view_ranking), config.max_candidates)if not merged:@@ -281,7 +282,7 @@ def gather_candidates(predictions = load_predictions(team.id, found) if can_view_ranking else {}needs_you = _needs_you(team.id, user, reports)try:- sources = fetch_source_products_for_reports(team, found)+ sources = fetch_source_products_for_reports(team, found) if with_sources else {}except Exception:# The source is context, so a ClickHouse failure must not stop the ranking.logger.exception("signals.personal_ranking.source_products_failed", team_id=team.id)diff --git a/products/signals/backend/personal_ranking/config.py b/products/signals/backend/personal_ranking/config.pyindex bf3aa7daf089..327807855f72 100644--- a/products/signals/backend/personal_ranking/config.py+++ b/products/signals/backend/personal_ranking/config.py@@ -55,6 +55,12 @@ class PersonalRankingConfig:focus_max_chars: int = 500timeout_seconds: float = 30.0max_completion_tokens: int = 8000+ # The `for_me` endpoint reuses a stored list this many minutes old or newer while its inputs are the same.+ freshness_minutes: int = 60+ # Builds one person may start from the endpoint: a short burst, an hourly refill and a daily cap.+ build_burst: int = 2+ builds_per_hour: int = 12+ builds_per_day: int = 40DEFAULTS = PersonalRankingConfig()@@ -76,6 +82,10 @@ _MAXIMUMS: dict[str, int] = {"focus_max_chars": 2000,"timeout_seconds": 120,"max_completion_tokens": 16000,+ "freshness_minutes": 1440,+ "build_burst": 20,+ "builds_per_hour": 120,+ "builds_per_day": 500,"reason_max_chars": 500,}diff --git a/products/signals/backend/personal_ranking/logic.py b/products/signals/backend/personal_ranking/logic.pyindex 90f09cdf3420..db6d3c760fc0 100644--- a/products/signals/backend/personal_ranking/logic.py+++ b/products/signals/backend/personal_ranking/logic.py@@ -137,10 +137,13 @@ def normalize_focus(focus: str | None, max_chars: int) -> str | None:def input_hash(candidates: list[Candidate], *, activity_summary_version: int | None, focus: str | None) -> str:- """Changes when a candidate, its status, priority, PR state, needs-you facts or score, the summary, the prompt or the focus changes."""+ """Changes when a candidate, its text, status, priority, PR state, needs-you facts or score, the summary, the prompt or the focus changes."""rows = sorted([candidate.report_id,+ # The prompt shows this text, so an edit makes the stored reasons out of date.+ candidate.title,+ candidate.summary_lead,candidate.status,candidate.priority,candidate.pull_request_state,diff --git a/products/signals/backend/personal_ranking/serve.py b/products/signals/backend/personal_ranking/serve.pynew file mode 100644index 000000000000..e52f61c3b510--- /dev/null+++ b/products/signals/backend/personal_ranking/serve.py@@ -0,0 +1,233 @@+"""Serve one person's ranked inbox list to the `for_me` endpoint: reuse a stored list, or build a new one.++A stored list is reused while it is younger than `freshness_minutes` and its input hash matches the current+inputs. A request with `focus` always builds. The focus is part of the hash, so an unfocused request never+reuses a focused list. Builds spend two per-person token buckets. A throttled request gets the latest stored+list, or `BuildThrottledError` when there is none.+"""++import datetime+from collections.abc import Mapping, Sequence+from typing import Any, Literal++from django.utils import timezone++import structlog++from posthog.dataclasses import frozen+from posthog.models import Team, User+from posthog.token_bucket import BucketDecision, BucketUnavailable, Budget, consume, refund++from products.signals.backend.activity_summary.read import ActivitySummaryStatus, get_summary+from products.signals.backend.models import PersonalInboxRanking+from products.signals.backend.personal_ranking.candidates import Candidate, gather_candidates+from products.signals.backend.personal_ranking.config import PersonalRankingConfig, read_config+from products.signals.backend.personal_ranking.logic import build_personal_ranking, input_hash, normalize_focus+from products.signals.backend.ranking.report_predictions import ReportPredictions++logger = structlog.get_logger(__name__)++ServeStatus = Literal["ready", "unavailable"]++_BUCKET_PREFIX = "personal_ranking_build_rate"+_DAILY_BUILD_COST = 24+++class BuildThrottledError(Exception):+ def __init__(self, retry_after: int | None) -> None:+ super().__init__("Personal inbox ranking build throttled.")+ self.retry_after = retry_after+++@frozen+class ServedReport:+ id: str+ title: str+ status: str+ priority: str | None+ pull_request_state: str | None+ # None when the person cannot see the ranking model's output.+ predictions: ReportPredictions | None+++@frozen+class ServedEntry:+ rank: int+ tier: str+ reason: str+ next_step: str | None+ matched_theme: str | None+ needs_you: tuple[str, ...]+ ranked_by: str+ report: ServedReport+++@frozen+class ServedFold:+ report_id: str+ into_report_id: str+ reason: str+++@frozen+class ServedRanking:+ status: ServeStatus+ personalized: bool+ # True when the list comes from storage, False when this request built it.+ cached: bool+ # True when the list does not reflect the current inputs, because a build was throttled.+ stale: bool+ fallback_reason: str | None+ generated_at: datetime.datetime | None+ latency_ms: int | None+ activity_summary_version: int | None+ candidates_considered: int+ ranked_count: int+ results: tuple[ServedEntry, ...]+ folded: tuple[ServedFold, ...]+++UNAVAILABLE = ServedRanking(+ status="unavailable",+ personalized=False,+ cached=False,+ stale=False,+ fallback_reason=None,+ generated_at=None,+ latency_ms=None,+ activity_summary_version=None,+ candidates_considered=0,+ ranked_count=0,+ results=(),+ folded=(),+)+++def _spend_build(team_id: int, user_id: int, config: PersonalRankingConfig) -> int | None:+ """Spend one build from both buckets. Returns None when allowed, else the seconds until the next build."""+ hourly = Budget(burst=config.build_burst, per_hour=config.builds_per_hour)+ # A build costs one token per hour of the day, and the bucket refills `builds_per_day` tokens an hour,+ # so it refills exactly `builds_per_day` builds a day. A whole-token rate per build would round it up.+ daily = Budget(burst=config.builds_per_day * _DAILY_BUILD_COST, per_hour=config.builds_per_day)+ hourly_key = f"{_BUCKET_PREFIX}:hour:{team_id}:{user_id}"+ hourly_decision = consume(hourly_key, hourly)+ if isinstance(hourly_decision, BucketDecision) and not hourly_decision.allowed:+ return hourly_decision.retry_after+ daily_decision = consume(f"{_BUCKET_PREFIX}:day:{team_id}:{user_id}", daily, cost=_DAILY_BUILD_COST)+ if isinstance(daily_decision, BucketDecision) and not daily_decision.allowed:+ if isinstance(hourly_decision, BucketDecision):+ refund(hourly_key, hourly)+ return daily_decision.retry_after+ if isinstance(hourly_decision, BucketUnavailable) or isinstance(daily_decision, BucketUnavailable):+ # Fail open, so an unreachable Redis does not hide the list.+ logger.warning("signals.personal_ranking.build_bucket_unavailable", team_id=team_id, user_id=user_id)+ return None+++def _ready_summary_version(team: Team, user: User) -> int | None:+ summary = get_summary(team, user.id)+ return summary.version if summary is not None and summary.status == ActivitySummaryStatus.READY else None+++def _served_report(candidate: Candidate) -> ServedReport:+ return ServedReport(+ id=candidate.report_id,+ title=candidate.title,+ status=candidate.status,+ priority=candidate.priority,+ pull_request_state=candidate.pull_request_state,+ predictions=candidate.predictions,+ )+++def _entries(ranked: Sequence[Mapping[str, Any]], by_id: Mapping[str, Candidate], limit: int) -> list[ServedEntry]:+ entries: list[ServedEntry] = []+ for row in ranked:+ candidate = by_id.get(row["report_id"])+ # A report that left the candidates since the build, for example a resolved one, drops out.+ if candidate is None:+ continue+ theme = (row.get("matched") or {}).get("theme")+ entries.append(+ ServedEntry(+ rank=row["rank"],+ tier=row["tier"],+ reason=row["reason"],+ next_step=row.get("next_step"),+ matched_theme=theme,+ # The current facts, not the model's echo of them, and also set on entries the model did not rank.+ needs_you=candidate.needs_you,+ ranked_by=row["ranked_by"],+ report=_served_report(candidate),+ )+ )+ if len(entries) == limit:+ break+ return entries+++def _serve_row(+ row: PersonalInboxRanking, candidates: Sequence[Candidate], *, limit: int, cached: bool, stale: bool+) -> ServedRanking:+ result = row.result or {}+ ranked = result.get("ranked") or []+ by_id = {candidate.report_id: candidate for candidate in candidates}+ return ServedRanking(+ status="ready",+ personalized=row.personalized,+ cached=cached,+ stale=stale,+ fallback_reason=row.fallback_reason,+ generated_at=row.created_at,+ latency_ms=row.latency_ms,+ activity_summary_version=row.activity_summary_version,+ candidates_considered=len(row.candidate_ids or ()),+ ranked_count=len(ranked),+ results=tuple(_entries(ranked, by_id, limit)),+ folded=tuple(+ ServedFold(report_id=fold["report_id"], into_report_id=fold["into_report_id"], reason=fold["reason"])+ for fold in result.get("folded") or ()+ ),+ )+++def serve_personal_ranking(+ team: Team,+ user: User,+ *,+ limit: int | None = None,+ refresh: bool = False,+ focus: str | None = None,+ config: PersonalRankingConfig | None = None,+) -> ServedRanking:+ config = config or read_config()+ if not config.enabled:+ return UNAVAILABLE+ limit = min(max(limit or config.default_limit, 1), config.max_limit)+ focus = normalize_focus(focus, config.focus_max_chars)+ now = timezone.now()++ latest = (+ PersonalInboxRanking.objects.for_team(team.id).filter(user_id=user.id).order_by("-created_at", "-id").first()+ )+ candidates = gather_candidates(team, user, config, now=now, with_sources=False)+ current_hash = input_hash(candidates, activity_summary_version=_ready_summary_version(team, user), focus=focus)+ current = (+ latest is not None+ and latest.created_at >= now - datetime.timedelta(minutes=config.freshness_minutes)+ and latest.input_hash == current_hash+ )+ if latest is not None and current and not refresh and focus is None:+ return _serve_row(latest, candidates, limit=limit, cached=True, stale=False)++ retry_after = _spend_build(team.id, user.id, config)+ if retry_after is not None:+ if latest is None:+ raise BuildThrottledError(retry_after)+ return _serve_row(latest, candidates, limit=limit, cached=True, stale=not current)++ build = build_personal_ranking(team, user, focus=focus, limit=limit, config=config)+ if build.ranking_id is None:+ return UNAVAILABLE+ row = PersonalInboxRanking.objects.for_team(team.id).get(id=build.ranking_id, team_id=team.id, user_id=user.id)+ return _serve_row(row, build.candidates, limit=limit, cached=False, stale=False)diff --git a/products/signals/backend/ranking/access.py b/products/signals/backend/ranking/access.pyindex 44b873115e95..c27c30bc7394 100644--- a/products/signals/backend/ranking/access.py+++ b/products/signals/backend/ranking/access.py@@ -22,12 +22,17 @@ INBOX_MODEL_SORT_FLAG = "inbox-model-sort"def can_view_inbox_ranking(user: User, team: Team) -> bool:if user.is_staff:return True+ return user_flag_enabled(INBOX_MODEL_SORT_FLAG, user, team)+++def user_flag_enabled(flag: str, user: User, team: Team) -> bool:+ """Evaluate `flag` locally for `user` in `team`, with the properties the web client registers. A failure denies."""if not user.distinct_id:return Falseorganization = team.organizationtry:return feature_enabled_or_false(- INBOX_MODEL_SORT_FLAG,+ flag,user.distinct_id,groups={"organization": str(organization.id), "project": str(team.uuid)},person_properties={@@ -54,5 +59,5 @@ def can_view_inbox_ranking(user: User, team: Team) -> bool:send_feature_flag_events=False,)except Exception:- logger.exception("signals.inbox_ranking.flag_failed", team_id=team.id, user_id=user.id)+ logger.exception("signals.inbox_ranking.flag_failed", flag=flag, team_id=team.id, user_id=user.id)return Falsediff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex e49ea4f21da4..23f8f2dca6ba 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -3,7 +3,7 @@ import uuidimport dataclassesfrom collections.abc import Mappingfrom datetime import datetime, timedelta-from typing import TYPE_CHECKING, cast+from typing import TYPE_CHECKING, Any, castfrom django.db.models import Prefetch, TextChoicesfrom django.utils import timezone@@ -70,6 +70,7 @@ if TYPE_CHECKING:from drf_spectacular.utils import Directionfrom products.signals.backend.implementation_pr import ImplementationPr+ from products.signals.backend.personal_ranking.serve import ServedRankingfrom products.signals.backend.report_claims import ReportClaimfrom products.signals.backend.report_plan import ReportPlan, ReportPlanStep@@ -103,7 +104,7 @@ from .models import (from .pull_request_label import DEFAULT_PULL_REQUEST_LABELfrom .ranking.inbox_sort import inbox_merge_keyfrom .ranking.public_outcomes import RankingOutcome-from .ranking.report_predictions import read_report_predictions+from .ranking.report_predictions import ReportPredictions, read_report_predictionsfrom .ranking.staleness import EDIT_ARTEFACT_TYPESfrom .report_charts import CHART_SIZES, MAX_CHART_CAPTION_LENGTH, MAX_CHART_ID_LENGTH, MAX_CHART_TITLE_LENGTHfrom .report_generation.resolve_reviewers import enrich_reviewer_dicts_with_org_members, trusted_manual_reviewer_adders@@ -1447,6 +1448,187 @@ def _ranking_payload(return {"status": status.value, "model": model, "scored_at": scored_at, "predictions": predictions or []}+class PersonalRankingStatus(TextChoices):+ READY = "ready", "ready"+ UNAVAILABLE = "unavailable", "unavailable"+++class PersonalRankingTier(TextChoices):+ TOP = "top", "top"+ WORTH_A_LOOK = "worth_a_look", "worth_a_look"+ LATER = "later", "later"+++class PersonalRankingRankedBy(TextChoices):+ LLM = "llm", "llm"+ MODEL = "model", "model"+++class PersonalRankingNeedsYou(TextChoices):+ SUGGESTED_REVIEWER = "suggested_reviewer", "suggested_reviewer"+ CLAIMED = "claimed", "claimed"+ WAITING_ON_INPUT = "waiting_on_input", "waiting_on_input"+++class PersonalRankingQuerySerializer(serializers.Serializer):+ limit = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=100,+ help_text="The most reports to return, best first. Defaults to 25. Values above the configured maximum (50) use the maximum.",+ )+ refresh = serializers.BooleanField(+ default=False,+ help_text="Build a new list even when the stored one is current. A build calls a model and can take 30 seconds or more.",+ )+ focus = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=2000,+ help_text=(+ "Free text about what to put first, such as `error tracking` or `billing reports`. A request with "+ "focus always builds a new list, and an unfocused request never reuses it."+ ),+ )+++class PersonalRankingReportSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="The report id. Pass it to inbox-reports-retrieve for the full report.")+ title = serializers.CharField(help_text="The report title.")+ status = serializers.ChoiceField(choices=SignalReport.Status.choices, help_text="The report status.")+ priority = serializers.ChoiceField(+ choices=AutonomyPriority.choices, allow_null=True, help_text="The report priority, P0 to P4, or null."+ )+ implementation_pr_state = serializers.ChoiceField(+ choices=SignalReportAssignment.PrState.choices,+ allow_null=True,+ help_text="The state of the report's implementation pull request, or null when it has none.",+ )+ ranking = ReportRankingSerializer(help_text="The ranking model's predictions for the report.")+++class PersonalRankingMatchedSerializer(serializers.Serializer):+ theme = serializers.CharField(+ allow_null=True, help_text="The theme of your activity summary that the report matches, or null."+ )+ needs_you = serializers.ListField(+ child=serializers.ChoiceField(choices=PersonalRankingNeedsYou.choices),+ help_text="Why the report needs you: you are a suggested reviewer, you claimed it, or it waits on your input.",+ )+++class PersonalRankingEntrySerializer(serializers.Serializer):+ rank = serializers.IntegerField(help_text="The position in your list. 1 is the first.")+ tier = serializers.ChoiceField(choices=PersonalRankingTier.choices, help_text="top, worth_a_look or later.")+ reason = serializers.CharField(help_text="Why the report has this place in your list.")+ next_step = serializers.CharField(+ allow_null=True, help_text="A suggested next step for the top entries. Null for the others."+ )+ matched = PersonalRankingMatchedSerializer(help_text="What in your work the report matches.")+ ranked_by = serializers.ChoiceField(+ choices=PersonalRankingRankedBy.choices,+ help_text="llm: the language model placed the report. model: it kept its place in the inbox order.",+ )+ report = PersonalRankingReportSerializer(help_text="A compact view of the report.")+++class PersonalRankingFoldSerializer(serializers.Serializer):+ report_id = serializers.UUIDField(help_text="The report that the list leaves out.")+ into_report_id = serializers.UUIDField(help_text="The report in the list that covers the same work.")+ reason = serializers.CharField(help_text="Why the two reports are about the same work.")+++class PersonalRankingSerializer(serializers.Serializer):+ status = serializers.ChoiceField(+ choices=PersonalRankingStatus.choices,+ help_text="ready: the list is in `results`. unavailable: personal ranking is off now, and `results` is empty.",+ )+ personalized = serializers.BooleanField(+ help_text=(+ "True when the language model ranked the list with your activity summary. False when you have no "+ "summary yet or the build fell back to the inbox order."+ )+ )+ cached = serializers.BooleanField(+ help_text="True when the list comes from storage, false when this request built it."+ )+ stale = serializers.BooleanField(+ help_text=(+ "True when the list does not match your current inbox, because you reached the build limit. "+ "Try `refresh` again later."+ )+ )+ fallback_reason = serializers.CharField(+ allow_null=True,+ help_text=(+ "Why the list is in inbox order and not ranked by the language model: llm_error, timeout, "+ "malformed_output, truncated_output, no_candidates or ai_not_approved. Null when the model ranked it."+ ),+ )+ generated_at = serializers.DateTimeField(allow_null=True, help_text="When the list was built.")+ latency_ms = serializers.IntegerField(+ allow_null=True,+ help_text="How long the model call of the build took, in ms. Null when there was no model call.",+ )+ activity_summary_version = serializers.IntegerField(+ allow_null=True, help_text="The version of your activity summary that the build read, or null."+ )+ candidates_considered = serializers.IntegerField(help_text="How many reports the build considered.")+ ranked_count = serializers.IntegerField(+ help_text="How many reports the stored list ranks. `results` holds at most `limit` of them."+ )+ results = PersonalRankingEntrySerializer(+ many=True,+ help_text=(+ "Your reports, best first. A report that left your inbox since the build, for example a resolved one, "+ "is left out."+ ),+ )+ folded = PersonalRankingFoldSerializer(+ many=True, help_text="Reports the list leaves out because another report in it covers the same work."+ )+++def personal_ranking_payload(served: "ServedRanking") -> dict[str, Any]:+ def ranking(predictions: ReportPredictions | None) -> dict:+ if predictions is None:+ return _ranking_payload(RankingStatus.NOT_AVAILABLE)+ return _ranking_payload(+ RankingStatus(predictions.status),+ model=predictions.model,+ scored_at=predictions.scored_at,+ predictions=[dataclasses.asdict(prediction) for prediction in predictions.predictions],+ )++ return {+ **{+ field.name: getattr(served, field.name)+ for field in dataclasses.fields(served)+ if field.name not in {"results", "folded"}+ },+ "results": [+ {+ "rank": entry.rank,+ "tier": entry.tier,+ "reason": entry.reason,+ "next_step": entry.next_step,+ "matched": {"theme": entry.matched_theme, "needs_you": list(entry.needs_you)},+ "ranked_by": entry.ranked_by,+ "report": {+ "id": entry.report.id,+ "title": entry.report.title,+ "status": entry.report.status,+ "priority": entry.report.priority,+ "implementation_pr_state": entry.report.pull_request_state,+ "ranking": ranking(entry.report.predictions),+ },+ }+ for entry in served.results+ ],+ "folded": [dataclasses.asdict(fold) for fold in served.folded],+ }++class SignalReportPriorityUpdateSerializer(serializers.Serializer):priority = serializers.ChoiceField(choices=AutonomyPriority.choices,diff --git a/products/signals/backend/test/test_personal_ranking.py b/products/signals/backend/test/test_personal_ranking.pyindex 50197e5ec723..f7aafce0be0c 100644--- a/products/signals/backend/test/test_personal_ranking.py+++ b/products/signals/backend/test/test_personal_ranking.py@@ -5,7 +5,8 @@ from io import StringIOfrom types import SimpleNamespacefrom typing import Any-from posthog.test.base import BaseTest+import time_machine+from posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import MagicMock, patchfrom django.core.management import call_command@@ -16,6 +17,10 @@ import httpxfrom openai import APITimeoutErrorfrom parameterized import parameterized+from posthog.models import User+from posthog.redis import TEST_clear_clients+from posthog.token_bucket import TEST_reset_scripts+from products.signals.backend.activity_summary.read import (ActivitySummaryStatus,ActivitySummaryTheme,@@ -452,3 +457,121 @@ class TestBuildPersonalRanking(BaseTest):assert "status: ok" in outputassert "next: Review the PR" in outputassert all(f"] {report.title} (" in output for report in reports.values())+++class TestForMeEndpoint(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ TEST_clear_clients()+ TEST_reset_scripts()+ self.organization.is_ai_data_processing_approved = False+ self.organization.save()+ self.payload: dict[str, Any] = {"build_burst": 10}+ self.flag_enabled = True+ for target, value in (+ (+ "products.signals.backend.personal_ranking.config.read_flag_payload",+ MagicMock(side_effect=lambda *_: self.payload),+ ),+ (+ "products.signals.backend.ranking.access.feature_enabled_or_false",+ MagicMock(side_effect=lambda *_args, **_kwargs: self.flag_enabled),+ ),+ (+ "products.signals.backend.personal_ranking.candidates.fetch_source_products_for_reports",+ MagicMock(return_value={}),+ ),+ ("products.signals.backend.personal_ranking.logic.posthoganalytics.capture", MagicMock()),+ ):+ patcher = patch(target, value)+ patcher.start()+ self.addCleanup(patcher.stop)++ def _url(self, **params: Any) -> str:+ query = "&".join(f"{key}={value}" for key, value in params.items())+ return f"/api/projects/{self.team.id}/signals/reports/for_me/" + (f"?{query}" if query else "")++ def _claimed_report(self, title: str) -> SignalReport:+ report = SignalReport.objects.create(+ team=self.team, title=title, summary=title, signal_count=1, total_weight=1.0, status="ready"+ )+ SignalReportAssignment.all_teams.create(team=self.team, report=report, actor_kind="user", actor_user=self.user)+ return report++ def _rows(self) -> int:+ return PersonalInboxRanking.objects.for_team(self.team.id).filter(user_id=self.user.id).count()++ def _get(self, **params: Any) -> dict[str, Any]:+ response = self.client.get(self._url(**params))+ assert response.status_code == 200, response.json()+ return response.json()++ def test_reuses_a_current_list_and_builds_when_inputs_change(self) -> None:+ first = self._claimed_report("First")+ body = self._get()+ assert (body["cached"], body["fallback_reason"], self._rows()) == (False, "ai_not_approved", 1)+ assert [entry["report"]["id"] for entry in body["results"]] == [str(first.id)]+ assert body["results"][0]["matched"]["needs_you"] == ["claimed"]++ assert (self._get()["cached"], self._rows()) == (True, 1)+ assert (self._get(refresh="true")["cached"], self._rows()) == (False, 2)++ first.title = "First, edited"+ first.save()+ assert (self._get()["cached"], self._rows()) == (False, 3)++ second = self._claimed_report("Second")+ body = self._get()+ assert (body["cached"], self._rows()) == (False, 4)+ assert {entry["report"]["id"] for entry in body["results"]} == {str(first.id), str(second.id)}++ assert (self._get(focus="checkout")["cached"], self._rows()) == (False, 5)+ assert (self._get()["cached"], self._rows()) == (False, 6)++ def test_throttled_build_returns_the_stored_list_or_429(self) -> None:+ self.payload = {"build_burst": 1, "builds_per_hour": 1}+ first = self._claimed_report("First")+ self._get()++ assert (self._get(refresh="true")["cached"], self._rows()) == (True, 1)+ self._claimed_report("Second")+ body = self._get()+ assert (body["cached"], body["stale"], self._rows()) == (True, True, 1)+ assert [entry["report"]["id"] for entry in body["results"]] == [str(first.id)]++ PersonalInboxRanking.objects.for_team(self.team.id).all().delete()+ assert self.client.get(self._url()).status_code == 429++ def test_daily_cap_holds_across_hours(self) -> None:+ self.payload = {"build_burst": 10, "builds_per_hour": 120, "builds_per_day": 2}+ self._claimed_report("First")+ with time_machine.travel(timezone.now(), tick=False) as traveller:+ self._get()+ self._get(refresh="true")++ traveller.shift(datetime.timedelta(hours=3))+ assert (self._get(refresh="true")["cached"], self._rows()) == (True, 2)++ traveller.shift(datetime.timedelta(hours=9))+ assert (self._get(refresh="true")["cached"], self._rows()) == (False, 3)++ def test_another_user_never_reads_your_list(self) -> None:+ self._get()+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")+ self.client.force_login(other)++ body = self._get()++ assert body["cached"] is False+ assert PersonalInboxRanking.objects.for_team(self.team.id).filter(user_id=other.id).count() == 1++ @parameterized.expand([("flag_off", {"enabled": True}, False), ("kill_switch", {"enabled": False}, True)])+ def test_unavailable(self, _name: str, payload: dict[str, Any], flag_enabled: bool) -> None:+ self.payload, self.flag_enabled = payload, flag_enabled+ response = self.client.get(self._url())+ if flag_enabled:+ assert response.status_code == 200+ assert (response.json()["status"], response.json()["results"]) == ("unavailable", [])+ else:+ assert response.status_code == 404+ assert self._rows() == 0diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex be5990987918..2bc6bda1ea34 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -1,6 +1,7 @@import reimport jsonimport math+import timeimport uuidfrom collections.abc import Callable, Iterable, Sequencefrom contextlib import ExitStack@@ -77,7 +78,12 @@ from posthog.models.integration import GitHubIntegrationfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegrationfrom posthog.oauth_provenance import is_sandbox_oauth_request, is_sandbox_origin_request-from posthog.permissions import APIScopePermission, get_authenticator_scoped_team_ids, get_authenticator_scopes+from posthog.permissions import (+ APIScopePermission,+ get_authenticator_scoped_team_ids,+ get_authenticator_scopes,+ is_service_auth,+)from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottlefrom posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissions@@ -152,11 +158,13 @@ from products.signals.backend.models import (SignalTeamConfig,SignalUserAutonomyConfig,)+from products.signals.backend.personal_ranking.config import PERSONAL_INBOX_RANKING_FLAG+from products.signals.backend.personal_ranking.serve import BuildThrottledError, serve_personal_rankingfrom products.signals.backend.pr_ci_status import pr_ci_statuses_for_references, rollup_ci_statusfrom products.signals.backend.presentation.scout_permissions import ScoutCanonicalTeamAccessPermissionfrom products.signals.backend.pull_requests import import_report_pull_requestsfrom products.signals.backend.quota import self_driving_quota_enforcement_enabled, self_driving_quota_gate-from products.signals.backend.ranking.access import can_view_inbox_ranking+from products.signals.backend.ranking.access import can_view_inbox_ranking, user_flag_enabledfrom products.signals.backend.ranking.inbox_sort import (PRIORITY_ORDERING,RANKER_ORDERINGS,@@ -242,6 +250,8 @@ from products.signals.backend.scout_harness.trial_access import trial_state_errofrom products.signals.backend.scout_report.trial_inbox import TrialInboxReads, private_report_artefactsfrom products.signals.backend.serializers import (CommitDiffResponseSerializer,+ PersonalRankingQuerySerializer,+ PersonalRankingSerializer,PullRequestChecksPermissionErrorSerializer,PullRequestChecksResponseSerializer,PullRequestCiStatusesResponseSerializer,@@ -283,6 +293,7 @@ from products.signals.backend.serializers import (SignalTeamConfigSerializer,SignalUserAutonomyConfigCreateSerializer,SignalUserAutonomyConfigSerializer,+ personal_ranking_payload,)from products.signals.backend.signal_metadata import (ReportSignalMeta,@@ -1723,6 +1734,60 @@ class SignalReportViewSet(RankingOutcomesResponseSerializer({"status": status_value.value, "model": model, "outcomes": outcomes}).data)+ @validated_request(+ query_serializer=PersonalRankingQuerySerializer,+ responses={+ 200: OpenApiResponse(response=PersonalRankingSerializer),+ 404: OpenApiResponse(description="Personal ranking is not available to the caller."),+ 429: OpenApiResponse(description="The build limit is reached and no stored list exists yet."),+ },+ summary="Get your personal ranked inbox",+ description=(+ "Your open inbox reports, ranked for you by one language model call over your activity summary, the "+ "reports that need you and the ranking model's predictions. Each entry has a reason and a compact report. "+ "A current stored list returns at once. Otherwise the request builds a new list, which can take 30 "+ "seconds or more. Only the user the list is about can read it."+ ),+ )+ @action(detail=False, methods=["get"], url_path="for_me", required_scopes=["task:read"], pagination_class=None)+ def for_me(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ user = request.user+ # A list describes one person, so only that person's own credentials can read it.+ if (+ is_service_auth(request)+ or not isinstance(user, User)+ or trial_store_for_request(request, self.team_id) is not None+ or not user_flag_enabled(PERSONAL_INBOX_RANKING_FLAG, user, self.team)+ ):+ raise NotFound()+ query = request.validated_query_data+ started = time.monotonic()+ try:+ served = serve_personal_ranking(+ self.team, user, limit=query.get("limit"), refresh=query["refresh"], focus=query.get("focus")+ )+ except BuildThrottledError as error:+ raise exceptions.Throttled(wait=error.retry_after)+ report_user_action(+ user,+ "personal inbox ranking read",+ properties={+ "via_mcp": is_mcp_request(request),+ "status": served.status,+ "cached": served.cached,+ "stale": served.stale,+ "personalized": served.personalized,+ "fallback_reason": served.fallback_reason,+ "refresh": query["refresh"],+ "has_focus": bool(query.get("focus")),+ "result_count": len(served.results),+ "duration_ms": round((time.monotonic() - started) * 1000),+ },+ team=self.team,+ request=request,+ )+ return Response(PersonalRankingSerializer(personal_ranking_payload(served)).data)+@validated_request(query_serializer=SignalReportFilterQuerySerializer,responses={200: SignalReportSectionCountsSerializer},diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex bf59f1b94e60..ccf4255e3642 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -5958,6 +5958,184 @@ export interface SignalReportBulkClaimResponseApi {not_found_count: number}+/**+ * * `ready` - ready+ * * `unavailable` - unavailable+ */+export type PersonalRankingStatusEnumApi =+ (typeof PersonalRankingStatusEnumApi)[keyof typeof PersonalRankingStatusEnumApi]++export const PersonalRankingStatusEnumApi = {+ Ready: 'ready',+ Unavailable: 'unavailable',+} as const++/**+ * * `top` - top+ * * `worth_a_look` - worth_a_look+ * * `later` - later+ */+export type PersonalRankingTierEnumApi = (typeof PersonalRankingTierEnumApi)[keyof typeof PersonalRankingTierEnumApi]++export const PersonalRankingTierEnumApi = {+ Top: 'top',+ WorthALook: 'worth_a_look',+ Later: 'later',+} as const++/**+ * * `suggested_reviewer` - suggested_reviewer+ * * `claimed` - claimed+ * * `waiting_on_input` - waiting_on_input+ */+export type PersonalRankingNeedsYouEnumApi =+ (typeof PersonalRankingNeedsYouEnumApi)[keyof typeof PersonalRankingNeedsYouEnumApi]++export const PersonalRankingNeedsYouEnumApi = {+ SuggestedReviewer: 'suggested_reviewer',+ Claimed: 'claimed',+ WaitingOnInput: 'waiting_on_input',+} as const++export interface PersonalRankingMatchedApi {+ /**+ * The theme of your activity summary that the report matches, or null.+ * @nullable+ */+ theme: string | null+ /** Why the report needs you: you are a suggested reviewer, you claimed it, or it waits on your input. */+ needs_you: PersonalRankingNeedsYouEnumApi[]+}++/**+ * * `llm` - llm+ * * `model` - model+ */+export type PersonalRankingRankedByEnumApi =+ (typeof PersonalRankingRankedByEnumApi)[keyof typeof PersonalRankingRankedByEnumApi]++export const PersonalRankingRankedByEnumApi = {+ Llm: 'llm',+ Model: 'model',+} as const++export interface PersonalRankingReportApi {+ /** The report id. Pass it to inbox-reports-retrieve for the full report. */+ id: string+ /** The report title. */+ title: string+ /** The report status.+ *+ * * `potential` - Potential+ * * `candidate` - Candidate+ * * `in_progress` - In Progress+ * * `pending_input` - Pending Input+ * * `ready` - Ready+ * * `monitoring` - Monitoring+ * * `resolved` - Resolved+ * * `closed` - Closed+ * * `failed` - Failed+ * * `deleted` - Deleted+ * * `suppressed` - Suppressed */+ status: SignalReportStatusEnumApi+ /** The report priority, P0 to P4, or null.+ *+ * * `P0` - P0+ * * `P1` - P1+ * * `P2` - P2+ * * `P3` - P3+ * * `P4` - P4 */+ priority: AutonomyPriorityEnumApi | null+ /** The state of the report's implementation pull request, or null when it has none.+ *+ * * `unknown` - Unknown+ * * `draft` - Draft+ * * `open` - Open+ * * `closed` - Closed+ * * `merged` - Merged */+ implementation_pr_state: SignalReportAssignmentPrStateEnumApi | null+ /** The ranking model's predictions for the report. */+ ranking: ReportRankingApi+}++export interface PersonalRankingEntryApi {+ /** The position in your list. 1 is the first. */+ rank: number+ /** top, worth_a_look or later.+ *+ * * `top` - top+ * * `worth_a_look` - worth_a_look+ * * `later` - later */+ tier: PersonalRankingTierEnumApi+ /** Why the report has this place in your list. */+ reason: string+ /**+ * A suggested next step for the top entries. Null for the others.+ * @nullable+ */+ next_step: string | null+ /** What in your work the report matches. */+ matched: PersonalRankingMatchedApi+ /** llm: the language model placed the report. model: it kept its place in the inbox order.+ *+ * * `llm` - llm+ * * `model` - model */+ ranked_by: PersonalRankingRankedByEnumApi+ /** A compact view of the report. */+ report: PersonalRankingReportApi+}++export interface PersonalRankingFoldApi {+ /** The report that the list leaves out. */+ report_id: string+ /** The report in the list that covers the same work. */+ into_report_id: string+ /** Why the two reports are about the same work. */+ reason: string+}++export interface PersonalRankingApi {+ /** ready: the list is in `results`. unavailable: personal ranking is off now, and `results` is empty.+ *+ * * `ready` - ready+ * * `unavailable` - unavailable */+ status: PersonalRankingStatusEnumApi+ /** True when the language model ranked the list with your activity summary. False when you have no summary yet or the build fell back to the inbox order. */+ personalized: boolean+ /** True when the list comes from storage, false when this request built it. */+ cached: boolean+ /** True when the list does not match your current inbox, because you reached the build limit. Try `refresh` again later. */+ stale: boolean+ /**+ * Why the list is in inbox order and not ranked by the language model: llm_error, timeout, malformed_output, truncated_output, no_candidates or ai_not_approved. Null when the model ranked it.+ * @nullable+ */+ fallback_reason: string | null+ /**+ * When the list was built.+ * @nullable+ */+ generated_at: string | null+ /**+ * How long the model call of the build took, in ms. Null when there was no model call.+ * @nullable+ */+ latency_ms: number | null+ /**+ * The version of your activity summary that the build read, or null.+ * @nullable+ */+ activity_summary_version: number | null+ /** How many reports the build considered. */+ candidates_considered: number+ /** How many reports the stored list ranks. `results` holds at most `limit` of them. */+ ranked_count: number+ /** Your reports, best first. A report that left your inbox since the build, for example a resolved one, is left out. */+ results: PersonalRankingEntryApi[]+ /** Reports the list leaves out because another report in it covers the same work. */+ folded: PersonalRankingFoldApi[]+}+/*** * `passing` - Passing* * `failing` - Failing@@ -10893,6 +11071,24 @@ export type SignalsReportsAvailableReviewersRetrieve200 = {}}+export type SignalsReportsForMeRetrieveParams = {+ /**+ * Free text about what to put first, such as `error tracking` or `billing reports`. A request with focus always builds a new list, and an unfocused request never reuses it.+ * @maxLength 2000+ */+ focus?: string+ /**+ * The most reports to return, best first. Defaults to 25. Values above the configured maximum (50) use the maximum.+ * @minimum 1+ * @maximum 100+ */+ limit?: number+ /**+ * Build a new list even when the stored one is current. A build calls a model and can take 30 seconds or more.+ */+ refresh?: boolean+}+export type SignalsReportsPrCiStatusesParams = {/*** Comma-separated report UUIDs to resolve CI state for, at most 100 per request.diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 1db2d903b973..1322f4965f82 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -43,6 +43,7 @@ import type {PatchedSignalSourceConfigApi,PauseResponseApi,PauseUntilRequestApi,+ PersonalRankingApi,ProjectProfileApi,PullRequestChecksResponseApi,PullRequestCiStatusesResponseApi,@@ -158,6 +159,7 @@ import type {SignalsReportPrReviewCommentsCreateParams,SignalsReportsAvailableReviewersRetrieve200,SignalsReportsAvailableReviewersRetrieveParams,+ SignalsReportsForMeRetrieveParams,SignalsReportsListParams,SignalsReportsPrCiStatusesParams,SignalsReportsSectionCountsRetrieveParams,@@ -1542,6 +1544,37 @@ export const signalsReportsBulkClaim = async (})}+export const getSignalsReportsForMeRetrieveUrl = (projectId: string, params?: SignalsReportsForMeRetrieveParams) => {+ 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/reports/for_me/?${stringifiedParams}`+ : `/api/projects/${projectId}/signals/reports/for_me/`+}++/**+ * Your open inbox reports, ranked for you by one language model call over your activity summary, the reports that need you and the ranking model's predictions. Each entry has a reason and a compact report. A current stored list returns at once. Otherwise the request builds a new list, which can take 30 seconds or more. Only the user the list is about can read it.+ * @summary Get your personal ranked inbox+ */+export const signalsReportsForMeRetrieve = async (+ projectId: string,+ params?: SignalsReportsForMeRetrieveParams,+ options?: RequestInit+): Promise<PersonalRankingApi> => {+ return apiMutator<PersonalRankingApi>(getSignalsReportsForMeRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsReportsPrCiStatusesUrl = (projectId: string, params: SignalsReportsPrCiStatusesParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex e70a507a9eb1..55e73e6f2719 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -409,6 +409,26 @@ tools:note:description: The person's context for why the report was or was not useful, up to 4000 characters.input_schema: SignalReportFeedbackNoteSchema+ inbox-reports-for-me:+ operation: signals_reports_for_me_retrieve+ enabled: true+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get your personal ranked inbox+ description: >+ Get the current user's own open inbox reports, ranked for them. One language model call ranks the reports+ that need them (suggested reviewer, claimed, waiting on their input) and the reports the ranking model rates+ highest, using their activity summary. Use it for "what should I work on" and "my top N" questions in place+ of paging inbox-reports-list. Each entry has a rank, a tier, a short reason, a next step for the top entries+ and a compact report. Read the full report with inbox-reports-retrieve before you act on it. The list is+ personal: only the user it describes can read it. A current stored list returns at once; otherwise the call+ builds one, which can take 30 seconds or more. `refresh` and `focus` always build a new list, and builds are+ rate limited. `personalized: false` means the user has no activity summary yet or the build fell back to the+ inbox order (see `fallback_reason`). `stale: true` means the build limit was reached and the list may miss+ recent changes. `status: unavailable` means personal ranking is off for now.+ feature_flag: personal-inbox-rankinginbox-reports-leave-reviewers:operation: signals_reports_reviewers_me_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 8ef5f73d1ea5..a39545b9e4d0 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7982,6 +7982,22 @@"readOnlyHint": false}},+ "inbox-reports-for-me": {+ "description": "Get the current user's own open inbox reports, ranked for them. One language model call ranks the reports that need them (suggested reviewer, claimed, waiting on their input) and the reports the ranking model rates highest, using their activity summary. Use it for \"what should I work on\" and \"my top N\" questions in place of paging inbox-reports-list. Each entry has a rank, a tier, a short reason, a next step for the top entries and a compact report. Read the full report with inbox-reports-retrieve before you act on it. The list is personal: only the user it describes can read it. A current stored list returns at once; otherwise the call builds one, which can take 30 seconds or more. `refresh` and `focus` always build a new list, and builds are rate limited. `personalized: false` means the user has no activity summary yet or the build fell back to the inbox order (see `fallback_reason`). `stale: true` means the build limit was reached and the list may miss recent changes. `status: unavailable` means personal ranking is off for now.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Get your personal ranked inbox",+ "title": "Get your personal ranked inbox",+ "required_scopes": ["task:read"],+ "api_operations": ["GET /api/projects/{project_id}/signals/reports/for_me/"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "personal-inbox-ranking"+ },"inbox-reports-leave-reviewers": {"description": "Take the authenticated user off this report's suggested reviewers, leaving the other reviewers in place. Use it when a report was routed to them by mistake, so it stops reaching them without closing it for anyone else. The report's own state does not change: it stays open for whoever is left, and for the project. Succeeds whether or not the user was on the list, so a repeat call is safe. When the user says why, pass `removal_reason` and put their own words in `removal_note`. For example, \"I'm not on that team any more\" is `wrong_area` with that sentence as the note. Research reads the reason and scouts read the note when they route later reports. To change who else reviews a report, edit its `suggested_reviewers` artefact instead.","category": "Signals",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 3168bf513816..c6f85c53c624 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8214,6 +8214,22 @@"readOnlyHint": false}},+ "inbox-reports-for-me": {+ "description": "Get the current user's own open inbox reports, ranked for them. One language model call ranks the reports that need them (suggested reviewer, claimed, waiting on their input) and the reports the ranking model rates highest, using their activity summary. Use it for \"what should I work on\" and \"my top N\" questions in place of paging inbox-reports-list. Each entry has a rank, a tier, a short reason, a next step for the top entries and a compact report. Read the full report with inbox-reports-retrieve before you act on it. The list is personal: only the user it describes can read it. A current stored list returns at once; otherwise the call builds one, which can take 30 seconds or more. `refresh` and `focus` always build a new list, and builds are rate limited. `personalized: false` means the user has no activity summary yet or the build fell back to the inbox order (see `fallback_reason`). `stale: true` means the build limit was reached and the list may miss recent changes. `status: unavailable` means personal ranking is off for now.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Get your personal ranked inbox",+ "title": "Get your personal ranked inbox",+ "required_scopes": ["task:read"],+ "api_operations": ["GET /api/projects/{project_id}/signals/reports/for_me/"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "personal-inbox-ranking"+ },"inbox-reports-leave-reviewers": {"description": "Take the authenticated user off this report's suggested reviewers, leaving the other reviewers in place. Use it when a report was routed to them by mistake, so it stops reaching them without closing it for anyone else. The report's own state does not change: it stays open for whoever is left, and for the project. Succeeds whether or not the user was on the list, so a repeat call is safe. When the user says why, pass `removal_reason` and put their own words in `removal_note`. For example, \"I'm not on that team any more\" is `wrong_area` with that sentence as the note. Research reads the reason and scouts read the note when they route later reports. To change who else reviews a report, edit its `suggested_reviewers` artefact instead.","category": "Signals",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e2eba467a049..542525210de6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -95908,6 +95908,185 @@ export namespace Schemas {properties?: PersonUpdatePropertyRequestProperties;}+ /**+ * * `ready` - ready+ * * `unavailable` - unavailable+ */+ export type PersonalRankingStatusEnum = typeof PersonalRankingStatusEnum[keyof typeof PersonalRankingStatusEnum];+++ export const PersonalRankingStatusEnum = {+ Ready: 'ready',+ Unavailable: 'unavailable',+ } as const;++ /**+ * * `top` - top+ * * `worth_a_look` - worth_a_look+ * * `later` - later+ */+ export type PersonalRankingTierEnum = typeof PersonalRankingTierEnum[keyof typeof PersonalRankingTierEnum];+++ export const PersonalRankingTierEnum = {+ Top: 'top',+ WorthALook: 'worth_a_look',+ Later: 'later',+ } as const;++ /**+ * * `suggested_reviewer` - suggested_reviewer+ * * `claimed` - claimed+ * * `waiting_on_input` - waiting_on_input+ */+ export type PersonalRankingNeedsYouEnum = typeof PersonalRankingNeedsYouEnum[keyof typeof PersonalRankingNeedsYouEnum];+++ export const PersonalRankingNeedsYouEnum = {+ SuggestedReviewer: 'suggested_reviewer',+ Claimed: 'claimed',+ WaitingOnInput: 'waiting_on_input',+ } as const;++ export interface PersonalRankingMatched {+ /**+ * The theme of your activity summary that the report matches, or null.+ * @nullable+ */+ theme: string | null;+ /** Why the report needs you: you are a suggested reviewer, you claimed it, or it waits on your input. */+ needs_you: PersonalRankingNeedsYouEnum[];+ }++ /**+ * * `llm` - llm+ * * `model` - model+ */+ export type PersonalRankingRankedByEnum = typeof PersonalRankingRankedByEnum[keyof typeof PersonalRankingRankedByEnum];+++ export const PersonalRankingRankedByEnum = {+ Llm: 'llm',+ Model: 'model',+ } as const;++ export interface PersonalRankingReport {+ /** The report id. Pass it to inbox-reports-retrieve for the full report. */+ id: string;+ /** The report title. */+ title: string;+ /** The report status.+ *+ * * `potential` - Potential+ * * `candidate` - Candidate+ * * `in_progress` - In Progress+ * * `pending_input` - Pending Input+ * * `ready` - Ready+ * * `monitoring` - Monitoring+ * * `resolved` - Resolved+ * * `closed` - Closed+ * * `failed` - Failed+ * * `deleted` - Deleted+ * * `suppressed` - Suppressed */+ status: SignalReportStatusEnum;+ /** The report priority, P0 to P4, or null.+ *+ * * `P0` - P0+ * * `P1` - P1+ * * `P2` - P2+ * * `P3` - P3+ * * `P4` - P4 */+ priority: AutonomyPriorityEnum | null;+ /** The state of the report's implementation pull request, or null when it has none.+ *+ * * `unknown` - Unknown+ * * `draft` - Draft+ * * `open` - Open+ * * `closed` - Closed+ * * `merged` - Merged */+ implementation_pr_state: SignalReportAssignmentPrStateEnum | null;+ /** The ranking model's predictions for the report. */+ ranking: ReportRanking;+ }++ export interface PersonalRankingEntry {+ /** The position in your list. 1 is the first. */+ rank: number;+ /** top, worth_a_look or later.+ *+ * * `top` - top+ * * `worth_a_look` - worth_a_look+ * * `later` - later */+ tier: PersonalRankingTierEnum;+ /** Why the report has this place in your list. */+ reason: string;+ /**+ * A suggested next step for the top entries. Null for the others.+ * @nullable+ */+ next_step: string | null;+ /** What in your work the report matches. */+ matched: PersonalRankingMatched;+ /** llm: the language model placed the report. model: it kept its place in the inbox order.+ *+ * * `llm` - llm+ * * `model` - model */+ ranked_by: PersonalRankingRankedByEnum;+ /** A compact view of the report. */+ report: PersonalRankingReport;+ }++ export interface PersonalRankingFold {+ /** The report that the list leaves out. */+ report_id: string;+ /** The report in the list that covers the same work. */+ into_report_id: string;+ /** Why the two reports are about the same work. */+ reason: string;+ }++ export interface PersonalRanking {+ /** ready: the list is in `results`. unavailable: personal ranking is off now, and `results` is empty.+ *+ * * `ready` - ready+ * * `unavailable` - unavailable */+ status: PersonalRankingStatusEnum;+ /** True when the language model ranked the list with your activity summary. False when you have no summary yet or the build fell back to the inbox order. */+ personalized: boolean;+ /** True when the list comes from storage, false when this request built it. */+ cached: boolean;+ /** True when the list does not match your current inbox, because you reached the build limit. Try `refresh` again later. */+ stale: boolean;+ /**+ * Why the list is in inbox order and not ranked by the language model: llm_error, timeout, malformed_output, truncated_output, no_candidates or ai_not_approved. Null when the model ranked it.+ * @nullable+ */+ fallback_reason: string | null;+ /**+ * When the list was built.+ * @nullable+ */+ generated_at: string | null;+ /**+ * How long the model call of the build took, in ms. Null when there was no model call.+ * @nullable+ */+ latency_ms: number | null;+ /**+ * The version of your activity summary that the build read, or null.+ * @nullable+ */+ activity_summary_version: number | null;+ /** How many reports the build considered. */+ candidates_considered: number;+ /** How many reports the stored list ranks. `results` holds at most `limit` of them. */+ ranked_count: number;+ /** Your reports, best first. A report that left your inbox since the build, for example a resolved one, is left out. */+ results: PersonalRankingEntry[];+ /** Reports the list leaves out because another report in it covers the same work. */+ folded: PersonalRankingFold[];+ }+export interface _Summary {/** Inclusive UTC start of the spend window resolved from the request. */date_from: string;@@ -142002,6 +142181,24 @@ export namespace Schemas {email: string;}};+ export type SignalsReportsForMeRetrieveParams = {+ /**+ * Free text about what to put first, such as `error tracking` or `billing reports`. A request with focus always builds a new list, and an unfocused request never reuses it.+ * @maxLength 2000+ */+ focus?: string;+ /**+ * The most reports to return, best first. Defaults to 25. Values above the configured maximum (50) use the maximum.+ * @minimum 1+ * @maximum 100+ */+ limit?: number;+ /**+ * Build a new list even when the stored one is current. A build calls a model and can take 30 seconds or more.+ */+ refresh?: boolean;+ };+export type SignalsReportsPrCiStatusesParams = {/*** Comma-separated report UUIDs to resolve CI state for, at most 100 per request.diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex c8d75a38bd76..037b2cf1ecb0 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 80 enabled ops+ * PostHog API - MCP 81 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -1418,6 +1418,48 @@ export const SignalsReportsBulkStateCreateBody = () => zod.object({),})+/**+ * Your open inbox reports, ranked for you by one language model call over your activity summary, the reports that need you and the ranking model's predictions. Each entry has a reason and a compact report. A current stored list returns at once. Otherwise the request builds a new list, which can take 30 seconds or more. Only the user the list is about can read it.+ * @summary Get your personal ranked inbox+ */+export const SignalsReportsForMeRetrieveParams = () => 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 signalsReportsForMeRetrieveQueryFocusMax = 2000++export const signalsReportsForMeRetrieveQueryLimitMax = 100++export const signalsReportsForMeRetrieveQueryRefreshDefault = false++export const SignalsReportsForMeRetrieveQueryParams = () => zod.object({+ focus: zod+ .string()+ .max(signalsReportsForMeRetrieveQueryFocusMax)+ .optional()+ .describe(+ 'Free text about what to put first, such as `error tracking` or `billing reports`. A request with focus always builds a new list, and an unfocused request never reuses it.'+ ),+ limit: zod+ .number()+ .min(1)+ .max(signalsReportsForMeRetrieveQueryLimitMax)+ .optional()+ .describe(+ 'The most reports to return, best first. Defaults to 25. Values above the configured maximum (50) use the maximum.'+ ),+ refresh: zod+ .boolean()+ .default(signalsReportsForMeRetrieveQueryRefreshDefault)+ .describe(+ 'Build a new list even when the stored one is current. A build calls a model and can take 30 seconds or more.'+ ),+})+/*** What each public outcome of the served ranking model predicts, with its horizon, cohort, base rate and readability from the model that scored this project's reports. Users who cannot see the ranking model get status not_available and no outcomes.* @summary List the ranking model's public outcomesdiff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex 226170f8b63a..f546ba1e232b 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -636,6 +636,29 @@ const inboxReportsFeedbackCreate = (): ToolBase<},})+const InboxReportsForMeSchema = () => {+ const SignalsReportsForMeRetrieveQueryParams = orvalSchemas.SignalsReportsForMeRetrieveQueryParams()+ return SignalsReportsForMeRetrieveQueryParams+}++const inboxReportsForMe = (): ToolBase<ReturnType<typeof InboxReportsForMeSchema>, Schemas.PersonalRanking> => ({+ name: 'inbox-reports-for-me',+ schema: InboxReportsForMeSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof InboxReportsForMeSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PersonalRanking>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/for_me/`,+ query: {+ focus: params.focus,+ limit: params.limit,+ refresh: params.refresh,+ },+ })+ return result+ },+})+const InboxReportsLeaveReviewersSchema = () => {const SignalsReportsReviewersMeCreateBody = orvalSchemas.SignalsReportsReviewersMeCreateBody()const SignalsReportsReviewersMeCreateParams = orvalSchemas.SignalsReportsReviewersMeCreateParams()@@ -3635,6 +3658,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'inbox-reports-bulk-set-state': inboxReportsBulkSetState,'inbox-reports-claim': inboxReportsClaim,'inbox-reports-feedback-create': inboxReportsFeedbackCreate,+ 'inbox-reports-for-me': inboxReportsForMe,'inbox-reports-leave-reviewers': inboxReportsLeaveReviewers,'inbox-reports-list': inboxReportsList,'inbox-reports-merge': inboxReportsMerge,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-for-me.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-for-me.jsonnew file mode 100644index 000000000000..263b5d25a77e--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-for-me.json@@ -0,0 +1,22 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "focus": {+ "description": "Free text about what to put first, such as `error tracking` or `billing reports`. A request with focus always builds a new list, and an unfocused request never reuses it.",+ "maxLength": 2000,+ "type": "string"+ },+ "limit": {+ "description": "The most reports to return, best first. Defaults to 25. Values above the configured maximum (50) use the maximum.",+ "maximum": 100,+ "minimum": 1,+ "type": "number"+ },+ "refresh": {+ "default": false,+ "description": "Build a new list even when the stored one is current. A build calls a model and can take 30 seconds or more.",+ "type": "boolean"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 492e6e41dc75..ccce2bc6fdc2 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1126,6 +1126,7 @@ describe('Tool Filtering - Feature Flags', () => {'logs-agent-tools','workflows-transactional-email-api','activity-summary',+ 'personal-inbox-ranking','anomalies-search','workflows-email-domain-agent-setup','feature-flag-rules-v2-mcp',diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.tsindex 1b48dbc61dfe..391d2aca28d2 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,+ 'personal-inbox-ranking': true,'aeo-citation-tracking': true,'mcp-session-recording-console-logs': true,'anomalies-search': true,