: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): add scout metadata endpoint for enrolled limits + banner (#65155)
Andrew Maguiref162a666c5e6
diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.pyindex 6bc0b5d8c3ed..ed0532cf8a0b 100644--- a/products/signals/backend/routes.py+++ b/products/signals/backend/routes.py@@ -4,6 +4,7 @@ import products.signals.backend.views as signalsfrom products.signals.backend.scout_harness.views import (SignalProjectProfileViewSet,SignalScoutConfigViewSet,+ SignalScoutMetadataViewSet,SignalScoutRunViewSet,SignalScratchpadViewSet,)@@ -51,3 +52,9 @@ def register_routes(routers: RouterRegistry) -> None:"environment_signals_scout_project_profile",["team_id"],)+ routers.projects.register(+ r"signals/scout/metadata",+ SignalScoutMetadataViewSet,+ "environment_signals_scout_metadata",+ ["team_id"],+ )diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex cd43639e6046..163cf02e9d94 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -75,18 +75,29 @@ it is exercised via the `run_signals_scout` management command (see `../manageme`ACTIVITY_SLACK_S`, and `WORKFLOW_HARD_CEILING_S` (`= DEFAULT_MAX_RUNTIME_S +ACTIVITY_SLACK_S`, the activity-level ceiling that gates the workflow's`start_to_close_timeout`).+- `team_limits.py`+ Single source of truth for a team's effective scout caps + metadata, resolved from the+ `signals-scout` flag payload in one read. The same three-layer cap resolution+ (`team_configs[team]` → `default_team_config` → code constant) the coordinator enforces at+ dispatch, plus enrollment (`guaranteed_team_ids` / `skip_team_ids`, with a cloud/dev-gated+ fallback) and the editorial banner string. Kept free of the temporalio stack so it stays+ cheap to import on the API path; both the coordinator and the metadata endpoint import from+ here so the reported caps never drift from what dispatch allows. `resolve_team_metadata()`+ backs the metadata viewset.- `serializers.py`DRF serializers for the harness HTTP surface (runs, scratchpad, project profile).Annotated for drf-spectacular so the generated MCP tools have informative schemas.- `views.py``SignalScoutRunViewSet`, `SignalScoutConfigViewSet`, `SignalScratchpadViewSet`,- `SignalProjectProfileViewSet`.+ `SignalProjectProfileViewSet`, `SignalScoutMetadataViewSet`.Routed under `environment_signals_scout_*` basenames in `posthog/api/__init__.py`and exposed as `signals-scout-*` MCP tools via `products/signals/mcp/tools.yaml`.The config viewset is the no-wait creation path: `create` registers (upserts) aconfig for an already-authored skill with its schedule/emit posture in one call.`list` is strictly read-only (its MCP tool is annotated `readOnly`) — it never- mints config rows.+ mints config rows. The metadata viewset is the read-only `scout/metadata/current/`+ endpoint that reports enrollment + banner + enforced limits via+ `team_limits.resolve_team_metadata`.## Mental modeldiff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 5aed85473ea5..794cc462acd3 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -1110,3 +1110,45 @@ class SignalScoutConfigCreateSerializer(serializers.Serializer):if not value.startswith(SIGNALS_SCOUT_SKILL_PREFIX):raise serializers.ValidationError(f"Scout skill names must start with '{SIGNALS_SCOUT_SKILL_PREFIX}'.")return value+++# --- Team metadata ---------------------------------------------------------+++class ScoutLimitsSerializer(serializers.Serializer):+ """A team's enforced scout run caps and current usage.++ These are the values the coordinator actually applies at dispatch (resolved per-team override →+ fleet-wide default → code constant), so the UI can show the real throttle rather than what a+ user thinks they configured.+ """++ max_runs_per_tick = serializers.IntegerField(+ help_text="Most scout runs the team can start in a single 30-minute coordinator tick."+ )+ max_runs_per_day = serializers.IntegerField(+ allow_null=True,+ help_text="Most scout runs the team can start per rolling 24 hours, or null when uncapped.",+ )+ runs_today = serializers.IntegerField(+ help_text="Scout runs the team has started in the trailing 24 hours.",+ )+ runs_remaining_today = serializers.IntegerField(+ allow_null=True,+ help_text="Runs still allowed in the trailing 24h window (max_runs_per_day − runs_today), or null when uncapped.",+ )+++class ScoutMetadataSerializer(serializers.Serializer):+ """Team-scoped scout metadata for the inbox / Code-app UIs: enrollment, the alpha banner, and+ the enforced limits. Sourced from the `signals-scout` flag payload so the banner and caps can+ change without a deploy to either app."""++ enrolled = serializers.BooleanField(+ help_text="Whether this project is enrolled to run scouts (set via the signals-scout flag allowlist)."+ )+ banner_message = serializers.CharField(+ allow_null=True,+ help_text="Free-form announcement banner to show above the scout UI (e.g. alpha run-limit notice), or null when unset.",+ )+ limits = ScoutLimitsSerializer(help_text="The team's enforced scout run caps and current usage.")diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.pynew file mode 100644index 000000000000..46cb5e1255f5--- /dev/null+++ b/products/signals/backend/scout_harness/team_limits.py@@ -0,0 +1,356 @@+"""Per-team scout limits + metadata, resolved from the `signals-scout` flag payload.++Single source of truth for "what caps and allowances does this team actually have": the+flag-payload read and three-layer cap resolution that the coordinator enforces at dispatch and+the HTTP surface (`scout_harness/views.py` → the `signals-scout-metadata` endpoint) reports to the+UI. Kept free of the temporalio workflow/scheduler stack so it stays cheap to import on the API+path; both sides import from here so the reported caps never drift from what dispatch allows.+"""++from __future__ import annotations++import json+from dataclasses import dataclass+from datetime import datetime, timedelta++from django.conf import settings+from django.db.models import Count+from django.utils import timezone++import structlog+import posthoganalytics++from posthog.cloud_utils import is_cloud+from posthog.exceptions_capture import capture_exception+from posthog.models import Team++from products.signals.backend.models import SignalScoutRun++logger = structlog.get_logger(__name__)++# Team-level dogfood gate. The single team gate (no per-team model boolean): the flag's JSON+# payload picks which teams run scouts; per-scout SignalScoutConfig rows pick which+# scouts/schedules.+SIGNALS_SCOUT_DOGFOOD_FLAG = "signals-scout"++# Fixed distinct_id for the payload read — enrollment is team-list-in-payload, not per-user.+SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID = "internal_signals_scout_team_discovery"++# Fail-safe allowlist used when the flag payload is missing/invalid — but only on PostHog+# Cloud or local dev (see `_fallback_team_ids`). 1 (local dev), 2 (internal), 148051 (dev).+DEFAULT_ENROLLED_TEAM_IDS: list[int] = [1, 2, 148051]++# Per-team slice of the tick budget. Bounds what one team can consume per tick (and thus+# per day: cap × ticks/day), so a team registering many scouts degrades its own cadence,+# not everyone else's. Sized well above the canonical fleet (~16 scouts) so a fully-enrolled+# team is never trimmed; round-robin allocation still keeps any one team from starving the+# others even when this is close to the global cap.+#+# This is the LAST-RESORT default. Effective per-team cap resolves through three layers,+# most specific first (see `_resolve_max_runs_per_tick`): a team's own `team_configs` entry →+# the fleet-wide `default_team_config` → this code constant. The two flag layers are read+# fresh each tick, so the launch posture (e.g. cap every enrolled team at 1 run/tick via+# `default_team_config`, then hand a close partner more headroom via `team_configs`) is+# tunable in the flag UI with no deploy.+MAX_RUNS_PER_TEAM_PER_TICK = 50++# Key inside a `team_configs` entry (or the `default_team_config` blob) that overrides+# `MAX_RUNS_PER_TEAM_PER_TICK`. Both blobs share the same inner shape — a forward-looking+# override bag — so add more per-team-tunable settings here and each consumer reads + validates+# the key it cares about.+TEAM_CONFIG_MAX_RUNS_PER_TICK = "max_runs_per_tick"++# Per-team DAILY run budget — the cost guarantee the per-tick cap can't express. The tick cap+# bounds bursts (≤ cap per 30-min tick → ≤ cap × 48/day); this bounds the day directly, so a+# launch team that enables many scouts (or cranks their intervals down) still runs at most N+# times a day. Counted over a rolling 24h window of dispatched runs and folded into the per-team+# tick cap (the tighter of the two binds each tick — see `_allocate_tick_budget`).+#+# `None` = no daily cap (the historical behaviour; the per-tick cap stays the only bound). Like+# the tick cap, the effective value resolves most-specific-first (see `_resolve_max_runs_per_day`):+# a team's `team_configs` entry → the fleet-wide `default_team_config` → this code constant. Left+# `None` so existing teams are unchanged; the launch posture sets a small N on+# `default_team_config` in the flag, no deploy.+MAX_RUNS_PER_TEAM_PER_DAY: int | None = None++# Key inside `team_configs` / `default_team_config` that overrides `MAX_RUNS_PER_TEAM_PER_DAY`.+TEAM_CONFIG_MAX_RUNS_PER_DAY = "max_runs_per_day"++# Rolling window the per-team daily budget is counted over.+DAILY_BUDGET_WINDOW = timedelta(hours=24)++# Flag payload key carrying an alpha/announcement banner for the scout UIs (cloud inbox + the+# Code app). A free-form editorial string set in the flag UI so wording changes need no deploy to+# either app. Absent / non-string / blank → no banner.+SIGNALS_SCOUT_BANNER_KEY = "scouts_banner_message"+++def _fallback_team_ids() -> list[int]:+ """Default allowlist when the flag payload is absent/unreadable — gated to PostHog Cloud+ and local dev. A self-hosted instance (where teams 1/2 exist but no one opted into scouts)+ fails closed instead, so the coordinator never starts LLM scout runs for an unintended+ tenant; a self-hoster opts in by setting the payload explicitly."""+ return list(DEFAULT_ENROLLED_TEAM_IDS) if (is_cloud() or settings.DEBUG) else []+++def _read_flag_payload() -> dict | None:+ """Read + parse the `signals-scout` flag's JSON payload once.++ The flag must stay 100%-on so the payload is served for the synthetic discovery+ distinct_id — `match_value=True` additionally forces the true-variant payload under local+ evaluation. Returns the parsed dict, or `None` when the payload is absent / not an object /+ unreadable. A read error never breaks dispatch: callers apply their own fallback to `None`.+ Enrollment and per-team configs both derive from a single call to this so they always see+ the same snapshot. Mirrors `posthog/temporal/ai_observability/team_discovery.py`.+ """+ try:+ payload = posthoganalytics.get_feature_flag_payload(+ SIGNALS_SCOUT_DOGFOOD_FLAG, SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID, match_value=True+ )+ if isinstance(payload, str):+ payload = json.loads(payload)+ return payload if isinstance(payload, dict) else None+ except Exception as error:+ capture_exception(error)+ return None+++def _enrolled_team_ids(payload: dict | None) -> set[int]:+ """Project ids enrolled in scouts, parsed from the `signals-scout` flag payload.++ Flag-driven enrollment, no deploy: edit `guaranteed_team_ids` in the flag UI to enroll (or+ drain) a team on the next tick; `skip_team_ids` is an override kill-switch.+ Fail-safe: a missing/invalid payload (`None`) or malformed value falls back to+ `_fallback_team_ids`.+ """+ fallback = _fallback_team_ids()+ if payload is None:+ return set(fallback)++ # Absent key or malformed value → fallback. An explicit empty list is honored as an+ # intentional "drain all teams" — not coerced to the fallback.+ guaranteed = payload.get("guaranteed_team_ids", fallback)+ if not isinstance(guaranteed, list) or not all(isinstance(t, int) for t in guaranteed):+ guaranteed = fallback++ skip = payload.get("skip_team_ids", [])+ if not isinstance(skip, list) or not all(isinstance(t, int) for t in skip):+ skip = []++ return set(guaranteed) - set(skip)+++def _team_configs(payload: dict | None) -> dict[int, dict]:+ """Optional per-team config overrides, parsed from the same `signals-scout` flag payload as+ enrollment. Returns `{team_id: config_dict}`.++ Payload key `team_configs` is a `{team_id: {…}}` map — a forward-looking per-team override+ bag. Today the only honored key is `max_runs_per_tick` (overrides `MAX_RUNS_PER_TEAM_PER_TICK`+ for that team — give an important dogfooder more headroom or hold a noisy one lower, no+ deploy); add more per-team settings under the same blob later. The override takes precedence+ over the global default for its team; teams not listed keep the global default.++ Absent/malformed (`None` payload included) → `{}` (everyone on the defaults). Defensive+ parse: JSON object keys arrive as strings so they're coerced to int; entries whose value+ isn't a dict are dropped. Each consumer validates the specific key it reads (see+ `_allocate_tick_budget._team_cap`). Keys are canonicalized to parent projects at planning+ time (see `_canonicalize_team_config_keys`).+ """+ if payload is None:+ return {}++ raw = payload.get("team_configs", {})+ if not isinstance(raw, dict):+ return {}++ configs: dict[int, dict] = {}+ for key, value in raw.items():+ if not isinstance(value, dict):+ continue+ try:+ team_id = int(key)+ except (TypeError, ValueError):+ continue+ configs[team_id] = value+ return configs+++def _default_team_config(payload: dict | None) -> dict:+ """Fleet-wide default config applied to every enrolled team, parsed from the `signals-scout`+ flag payload key `default_team_config`.++ Same inner shape as a `team_configs` entry (today: `max_runs_per_tick`). It sits between a+ per-team `team_configs` override and the code constant in `_resolve_max_runs_per_tick`, so a+ single fleet-wide cost guardrail (e.g. cap every enrolled team at 1 run/tick for launch) can+ be set in the flag UI with no deploy, while specific teams still get more headroom via+ `team_configs`. Absent/malformed (`None` payload included) → `{}` (everyone falls back to the+ code constants — unchanged behaviour).+ """+ if payload is None:+ return {}+ raw = payload.get("default_team_config", {})+ return raw if isinstance(raw, dict) else {}+++def _resolve_max_runs_per_tick(team_id: int, team_configs: dict[int, dict], default_team_config: dict) -> int:+ """Effective per-tick cap for a team, most-specific layer first.++ `team_configs[team_id]` (per-team override) → `default_team_config` (fleet-wide default) →+ `MAX_RUNS_PER_TEAM_PER_TICK` (code constant). Both flag blobs are arbitrary JSON, so the+ `max_runs_per_tick` value is validated at each layer (positive int, not bool); an absent or+ malformed value falls through to the next layer rather than failing the tick.+ """+ for source in ((team_configs.get(team_id) or {}), default_team_config):+ override = source.get(TEAM_CONFIG_MAX_RUNS_PER_TICK)+ if isinstance(override, int) and not isinstance(override, bool) and override > 0:+ return override+ return MAX_RUNS_PER_TEAM_PER_TICK+++def _resolve_max_runs_per_day(team_id: int, team_configs: dict[int, dict], default_team_config: dict) -> int | None:+ """Effective per-team daily run budget, most-specific layer first.++ `team_configs[team_id]` (per-team override) → `default_team_config` (fleet-wide default) →+ `MAX_RUNS_PER_TEAM_PER_DAY` (code constant, `None` = unbounded). Same per-layer fallback and+ validation (positive int, not bool) as `_resolve_max_runs_per_tick`: a malformed value at one+ layer falls through to the next rather than failing the tick. `None` means no daily cap — only+ the per-tick cap binds, the historical behaviour.+ """+ for source in ((team_configs.get(team_id) or {}), default_team_config):+ override = source.get(TEAM_CONFIG_MAX_RUNS_PER_DAY)+ if isinstance(override, int) and not isinstance(override, bool) and override > 0:+ return override+ return MAX_RUNS_PER_TEAM_PER_DAY+++def _runs_today_by_team(team_ids: set[int], window_start: datetime) -> dict[int, int]:+ """Scout runs dispatched per team within the trailing daily-budget window.++ Counts `SignalScoutRun` bridge rows (created at run start), so the budget tracks runs that+ actually happened — the durable, cost-relevant signal. Uses the unscoped `all_teams` manager,+ matching the coordinator's other cross-team reads. A run dispatched this tick but not yet+ started isn't counted until its row lands; the per-tick cap bounds that brief window.+ """+ if not team_ids:+ return {}+ rows = (+ SignalScoutRun.all_teams.filter(team_id__in=team_ids, created_at__gte=window_start)+ .values("team_id")+ .annotate(n=Count("id"))+ )+ return {row["team_id"]: row["n"] for row in rows}+++def _canonicalize_team_config_keys(team_configs: dict[int, dict]) -> dict[int, dict]:+ """Remap child-env config keys to their parent project id so per-team overrides line up with+ the canonical team ids planning uses — `_participating_teams` canonicalizes enrollment the+ same way, so an operator listing a child env id in both `guaranteed_team_ids` and+ `team_configs` keeps its override. If both a parent and one of its child envs are keyed, the+ explicit parent-keyed config wins regardless of dict order."""+ if not team_configs:+ return team_configs+ parent_of = {+ team_id: (parent_id or team_id)+ for team_id, parent_id in Team.objects.filter(id__in=team_configs.keys()).values_list("id", "parent_team_id")+ }+ canonical: dict[int, dict] = {}+ for team_id, config in team_configs.items():+ canonical_id = parent_of.get(team_id, team_id)+ # A parent/standalone key (team_id == canonical_id) always wins; a child remap only+ # fills in when no parent-keyed config is present for that project.+ if team_id == canonical_id or canonical_id not in canonical:+ canonical[canonical_id] = config+ return canonical+++def read_banner_message(payload: dict | None) -> str | None:+ """Editorial alpha/announcement banner from the flag payload, or `None` when unset.++ Absent key, non-string value, or a blank/whitespace-only string all collapse to `None` so the+ UIs render nothing rather than an empty banner.+ """+ if payload is None:+ return None+ message = payload.get(SIGNALS_SCOUT_BANNER_KEY)+ if not isinstance(message, str):+ return None+ return message.strip() or None+++def _is_team_enrolled(canonical_team_id: int, enrolled_ids: set[int]) -> bool:+ """Whether a canonical project runs scouts, canonicalizing any child-env entries in the+ enrolled set to their parent the same way `_participating_teams` does — so an operator can+ list either the child env id or the parent project id in `guaranteed_team_ids`."""+ if canonical_team_id in enrolled_ids:+ return True+ canonical_enrolled = {+ (parent_id or team_id)+ for team_id, parent_id in Team.objects.filter(id__in=enrolled_ids).values_list("id", "parent_team_id")+ }+ return canonical_team_id in canonical_enrolled+++@dataclass(frozen=True)+class ScoutTeamLimits:+ """A team's effective scout run caps + current usage, all resolved the way dispatch enforces."""++ max_runs_per_tick: int+ max_runs_per_day: int | None+ runs_today: int+ runs_remaining_today: int | None+++@dataclass(frozen=True)+class ScoutTeamMetadata:+ """Team-scoped scout metadata for the UI surfaces: enrollment, the editorial banner, and the+ enforced limits/usage. The banner is fleet-wide (one string in the flag); limits are per-team."""++ enrolled: bool+ banner_message: str | None+ limits: ScoutTeamLimits++ def as_dict(self) -> dict:+ return {+ "enrolled": self.enrolled,+ "banner_message": self.banner_message,+ "limits": {+ "max_runs_per_tick": self.limits.max_runs_per_tick,+ "max_runs_per_day": self.limits.max_runs_per_day,+ "runs_today": self.limits.runs_today,+ "runs_remaining_today": self.limits.runs_remaining_today,+ },+ }+++def resolve_team_metadata(canonical_team_id: int) -> ScoutTeamMetadata:+ """Resolve a team's enforced scout limits + the announcement banner from the `signals-scout`+ flag, in one flag-payload read.++ `canonical_team_id` must be the parent/project id (the HTTP surface passes+ `_canonical_team_id(view)`). Caps use the exact three-layer resolution the coordinator+ enforces at dispatch (`team_configs[team]` → `default_team_config` → code constant), so the+ reported numbers match what dispatch actually allows — the whole point of the endpoint is to+ show the user the *enforced* throttle, not the value they think they set. `runs_today` is the+ trailing-24h dispatched-run count; `runs_remaining_today` is `None` when the daily budget is+ unbounded.+ """+ payload = _read_flag_payload()+ team_configs = _canonicalize_team_config_keys(_team_configs(payload))+ default_team_config = _default_team_config(payload)++ max_runs_per_day = _resolve_max_runs_per_day(canonical_team_id, team_configs, default_team_config)+ runs_today = _runs_today_by_team({canonical_team_id}, timezone.now() - DAILY_BUDGET_WINDOW).get(+ canonical_team_id, 0+ )+ runs_remaining_today = None if max_runs_per_day is None else max(0, max_runs_per_day - runs_today)++ return ScoutTeamMetadata(+ enrolled=_is_team_enrolled(canonical_team_id, _enrolled_team_ids(payload)),+ banner_message=read_banner_message(payload),+ limits=ScoutTeamLimits(+ max_runs_per_tick=_resolve_max_runs_per_tick(canonical_team_id, team_configs, default_team_config),+ max_runs_per_day=max_runs_per_day,+ runs_today=runs_today,+ runs_remaining_today=runs_remaining_today,+ ),+ )diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 75380dcbbd81..977dc842a95e 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -71,6 +71,7 @@ from products.signals.backend.scout_harness.serializers import (ProjectProfileSerializer,RememberRequestSerializer,ScoutEmissionReportLinkSerializer,+ ScoutMetadataSerializer,ScratchpadEntrySerializer,SearchMemoryQuerySerializer,SearchRecentRunsQuerySerializer,@@ -80,6 +81,7 @@ from products.signals.backend.scout_harness.serializers import (SignalScoutRunDetailSerializer,SignalScoutRunSummarySerializer,)+from products.signals.backend.scout_harness.team_limits import resolve_team_metadatafrom products.signals.backend.scout_harness.tools.emit import EvidenceEntry, InvalidEmitError, emit_finding_syncfrom products.signals.backend.scout_harness.tools.profile import get_project_profilefrom products.signals.backend.scout_harness.tools.runs import get_run, search_recent_runs@@ -676,6 +678,60 @@ class SignalProjectProfileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSereturn Response(ProjectProfileSerializer(profile.as_dict()).data)+class SignalScoutMetadataViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """Team-scoped scout metadata: enrollment, the alpha banner, and the enforced run limits.++ All resolved from the `signals-scout` flag payload — the same read and three-layer cap+ resolution the coordinator applies at dispatch — so the UI shows the *enforced* throttle, not+ what a user assumes they set. Read-only and side-effect free.++ Exposed via a `current` action rather than `list` for the same reason as+ `SignalProjectProfileViewSet`: a bare `list` action types the response as a paginated+ collection downstream (drf-spectacular / Orval), and this is a singleton.+ """++ serializer_class = ScoutMetadataSerializer+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]+ permission_classes = [IsAuthenticated, APIScopePermission]+ scope_object = "signal_scout"+ # No model backs this endpoint — metadata is computed from the flag payload. A real queryset is+ # still required to satisfy the team/org viewset mixin; the `current` action never reads it.+ queryset = SignalScoutConfig.objects.unscoped()+ pagination_class = None++ @extend_schema(+ responses={+ 200: OpenApiResponse(+ response=ScoutMetadataSerializer,+ description="This project's scout enrollment, announcement banner, and enforced run limits.",+ ),+ },+ summary="Get scout metadata",+ description=(+ "Return the project's scout metadata: whether it is enrolled, the current announcement "+ "banner (e.g. an alpha run-limit notice, or null when unset), and the enforced run "+ "limits with current usage. Limits reflect what the coordinator actually applies at "+ "dispatch, so a user can see the real throttle rather than what they assume they set. "+ "All values come from the `signals-scout` flag payload, so the banner and caps can "+ "change with no deploy."+ ),+ operation_id="signals_scout_metadata_get",+ )+ @action(+ detail=False,+ methods=["get"],+ url_path="current",+ url_name="current",+ pagination_class=None,+ # `signal_scout:read` is the public, user-grantable read scope used across this surface;+ # without explicit `required_scopes` APIScopePermission rejects the request outright.+ required_scopes=["signal_scout:read"],+ )+ def current(self, request: Request, *args, **kwargs) -> Response:+ metadata = resolve_team_metadata(_canonical_team_id(self))+ return Response(ScoutMetadataSerializer(metadata.as_dict()).data)++def _reject_if_enabled_cap_reached(team_id: int, skill_name: str) -> None:"""Raise when enabling this scout would push the team past the per-team enabled cap.diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex 123c98621a30..7c91f0bce36d 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -5,86 +5,46 @@ import asynciofrom dataclasses import dataclassfrom datetime import datetime, timedelta-from django.conf import settings-from django.db.models import Count, Q+from django.db.models import Qfrom django.utils import timezoneimport structlog-import posthoganalyticsfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy, WorkflowIDReusePolicyfrom temporalio.exceptions import WorkflowAlreadyStartedError-from posthog.cloud_utils import is_cloud-from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeater-from products.signals.backend.models import SignalScoutConfig, SignalScoutRun+from products.signals.backend.models import SignalScoutConfigfrom products.signals.backend.scout_harness.config_registry import register_missing_configsfrom products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills++# Per-team cap resolution + the flag-payload read live in the temporalio-free `team_limits` module+# so the HTTP metadata surface can share them. Imported by name so the planning code below calls+# them unqualified and tests can patch them on this module.+from products.signals.backend.scout_harness.team_limits import (+ DAILY_BUDGET_WINDOW,+ _canonicalize_team_config_keys,+ _default_team_config,+ _enrolled_team_ids,+ _read_flag_payload,+ _resolve_max_runs_per_day,+ _resolve_max_runs_per_tick,+ _runs_today_by_team,+ _team_configs,+)from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, RunSignalsScoutWorkflowlogger = structlog.get_logger(__name__)-# Team-level dogfood gate. The single team gate (no per-team model boolean): the flag's JSON-# payload picks which teams run scouts; per-scout SignalScoutConfig rows pick which-# scouts/schedules.-SIGNALS_SCOUT_DOGFOOD_FLAG = "signals-scout"--# Fixed distinct_id for the payload read — enrollment is team-list-in-payload, not per-user.-SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID = "internal_signals_scout_team_discovery"--# Fail-safe allowlist used when the flag payload is missing/invalid — but only on PostHog-# Cloud or local dev (see `_fallback_team_ids`). 1 (local dev), 2 (internal), 148051 (dev).-DEFAULT_ENROLLED_TEAM_IDS: list[int] = [1, 2, 148051]-# Hard cap on dispatches per tick. The cost bound: when more scouts are due than this,# we run the most-overdue first and the rest catch up next tick (a poor-man's queue).# Set generously for now while scouts roll out to more teams — the per-team tick cap and# round-robin allocation do the day-to-day fairness work; this is the global ceiling.MAX_RUNS_PER_TICK = 1000-# Per-team slice of the tick budget. Bounds what one team can consume per tick (and thus-# per day: cap × ticks/day), so a team registering many scouts degrades its own cadence,-# not everyone else's. Sized well above the canonical fleet (~16 scouts) so a fully-enrolled-# team is never trimmed; round-robin allocation still keeps any one team from starving the-# others even when this is close to the global cap.-#-# This is the LAST-RESORT default. Effective per-team cap resolves through three layers,-# most specific first (see `_resolve_max_runs_per_tick`): a team's own `team_configs` entry →-# the fleet-wide `default_team_config` → this code constant. The two flag layers are read-# fresh each tick, so the launch posture (e.g. cap every enrolled team at 1 run/tick via-# `default_team_config`, then hand a close partner more headroom via `team_configs`) is-# tunable in the flag UI with no deploy.-MAX_RUNS_PER_TEAM_PER_TICK = 50--# Key inside a `team_configs` entry (or the `default_team_config` blob) that overrides-# `MAX_RUNS_PER_TEAM_PER_TICK`. Both blobs share the same inner shape — a forward-looking-# override bag — so add more per-team-tunable settings here and each consumer reads + validates-# the key it cares about.-TEAM_CONFIG_MAX_RUNS_PER_TICK = "max_runs_per_tick"--# Per-team DAILY run budget — the cost guarantee the per-tick cap can't express. The tick cap-# bounds bursts (≤ cap per 30-min tick → ≤ cap × 48/day); this bounds the day directly, so a-# launch team that enables many scouts (or cranks their intervals down) still runs at most N-# times a day. Counted over a rolling 24h window of dispatched runs and folded into the per-team-# tick cap (the tighter of the two binds each tick — see `_allocate_tick_budget`).-#-# `None` = no daily cap (the historical behaviour; the per-tick cap stays the only bound). Like-# the tick cap, the effective value resolves most-specific-first (see `_resolve_max_runs_per_day`):-# a team's `team_configs` entry → the fleet-wide `default_team_config` → this code constant. Left-# `None` so existing teams are unchanged; the launch posture sets a small N on-# `default_team_config` in the flag, no deploy.-MAX_RUNS_PER_TEAM_PER_DAY: int | None = None--# Key inside `team_configs` / `default_team_config` that overrides `MAX_RUNS_PER_TEAM_PER_DAY`.-TEAM_CONFIG_MAX_RUNS_PER_DAY = "max_runs_per_day"--# Rolling window the per-team daily budget is counted over.-DAILY_BUDGET_WINDOW = timedelta(hours=24)-# Coordinator tick cadence. Per-scout schedules are enforced via the due-check, so this is# just the polling granularity — the floor on how often any scout can run.COORDINATOR_INTERVAL_MINUTES = 30@@ -349,55 +309,6 @@ def _allocate_tick_budget(return selected-def _resolve_max_runs_per_tick(team_id: int, team_configs: dict[int, dict], default_team_config: dict) -> int:- """Effective per-tick cap for a team, most-specific layer first.-- `team_configs[team_id]` (per-team override) → `default_team_config` (fleet-wide default) →- `MAX_RUNS_PER_TEAM_PER_TICK` (code constant). Both flag blobs are arbitrary JSON, so the- `max_runs_per_tick` value is validated at each layer (positive int, not bool); an absent or- malformed value falls through to the next layer rather than failing the tick.- """- for source in ((team_configs.get(team_id) or {}), default_team_config):- override = source.get(TEAM_CONFIG_MAX_RUNS_PER_TICK)- if isinstance(override, int) and not isinstance(override, bool) and override > 0:- return override- return MAX_RUNS_PER_TEAM_PER_TICK---def _resolve_max_runs_per_day(team_id: int, team_configs: dict[int, dict], default_team_config: dict) -> int | None:- """Effective per-team daily run budget, most-specific layer first.-- `team_configs[team_id]` (per-team override) → `default_team_config` (fleet-wide default) →- `MAX_RUNS_PER_TEAM_PER_DAY` (code constant, `None` = unbounded). Same per-layer fallback and- validation (positive int, not bool) as `_resolve_max_runs_per_tick`: a malformed value at one- layer falls through to the next rather than failing the tick. `None` means no daily cap — only- the per-tick cap binds, the historical behaviour.- """- for source in ((team_configs.get(team_id) or {}), default_team_config):- override = source.get(TEAM_CONFIG_MAX_RUNS_PER_DAY)- if isinstance(override, int) and not isinstance(override, bool) and override > 0:- return override- return MAX_RUNS_PER_TEAM_PER_DAY---def _runs_today_by_team(team_ids: set[int], window_start: datetime) -> dict[int, int]:- """Scout runs dispatched per team within the trailing daily-budget window.-- Counts `SignalScoutRun` bridge rows (created at run start), so the budget tracks runs that- actually happened — the durable, cost-relevant signal. Uses the unscoped `all_teams` manager,- matching the coordinator's other cross-team reads. A run dispatched this tick but not yet- started isn't counted until its row lands; the per-tick cap bounds that brief window.- """- if not team_ids:- return {}- rows = (- SignalScoutRun.all_teams.filter(team_id__in=team_ids, created_at__gte=window_start)- .values("team_id")- .annotate(n=Count("id"))- )- return {row["team_id"]: row["n"] for row in rows}--def _participating_teams(enrolled: set[int]) -> list[Team]:"""Resolve enrolled team ids to canonical `Team`s to run scouts on.@@ -415,135 +326,6 @@ def _participating_teams(enrolled: set[int]) -> list[Team]:return list(Team.objects.filter(id__in=canonical_ids).order_by("id"))-def _canonicalize_team_config_keys(team_configs: dict[int, dict]) -> dict[int, dict]:- """Remap child-env config keys to their parent project id so per-team overrides line up with- the canonical team ids planning uses — `_participating_teams` canonicalizes enrollment the- same way, so an operator listing a child env id in both `guaranteed_team_ids` and- `team_configs` keeps its override. If both a parent and one of its child envs are keyed, the- explicit parent-keyed config wins regardless of dict order."""- if not team_configs:- return team_configs- parent_of = {- team_id: (parent_id or team_id)- for team_id, parent_id in Team.objects.filter(id__in=team_configs.keys()).values_list("id", "parent_team_id")- }- canonical: dict[int, dict] = {}- for team_id, config in team_configs.items():- canonical_id = parent_of.get(team_id, team_id)- # A parent/standalone key (team_id == canonical_id) always wins; a child remap only- # fills in when no parent-keyed config is present for that project.- if team_id == canonical_id or canonical_id not in canonical:- canonical[canonical_id] = config- return canonical---def _fallback_team_ids() -> list[int]:- """Default allowlist when the flag payload is absent/unreadable — gated to PostHog Cloud- and local dev. A self-hosted instance (where teams 1/2 exist but no one opted into scouts)- fails closed instead, so the coordinator never starts LLM scout runs for an unintended- tenant; a self-hoster opts in by setting the payload explicitly."""- return list(DEFAULT_ENROLLED_TEAM_IDS) if (is_cloud() or settings.DEBUG) else []---def _read_flag_payload() -> dict | None:- """Read + parse the `signals-scout` flag's JSON payload once.-- The flag must stay 100%-on so the payload is served for the synthetic discovery- distinct_id — `match_value=True` additionally forces the true-variant payload under local- evaluation. Returns the parsed dict, or `None` when the payload is absent / not an object /- unreadable. A read error never breaks dispatch: callers apply their own fallback to `None`.- Enrollment and per-team configs both derive from a single call to this so they always see- the same snapshot. Mirrors `posthog/temporal/ai_observability/team_discovery.py`.- """- try:- payload = posthoganalytics.get_feature_flag_payload(- SIGNALS_SCOUT_DOGFOOD_FLAG, SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID, match_value=True- )- if isinstance(payload, str):- payload = json.loads(payload)- return payload if isinstance(payload, dict) else None- except Exception as error:- capture_exception(error)- return None---def _enrolled_team_ids(payload: dict | None) -> set[int]:- """Project ids enrolled in scouts, parsed from the `signals-scout` flag payload.-- Flag-driven enrollment, no deploy: edit `guaranteed_team_ids` in the flag UI to enroll (or- drain) a team on the next tick; `skip_team_ids` is an override kill-switch.- Fail-safe: a missing/invalid payload (`None`) or malformed value falls back to- `_fallback_team_ids`.- """- fallback = _fallback_team_ids()- if payload is None:- return set(fallback)-- # Absent key or malformed value → fallback. An explicit empty list is honored as an- # intentional "drain all teams" — not coerced to the fallback.- guaranteed = payload.get("guaranteed_team_ids", fallback)- if not isinstance(guaranteed, list) or not all(isinstance(t, int) for t in guaranteed):- guaranteed = fallback-- skip = payload.get("skip_team_ids", [])- if not isinstance(skip, list) or not all(isinstance(t, int) for t in skip):- skip = []-- return set(guaranteed) - set(skip)---def _team_configs(payload: dict | None) -> dict[int, dict]:- """Optional per-team config overrides, parsed from the same `signals-scout` flag payload as- enrollment. Returns `{team_id: config_dict}`.-- Payload key `team_configs` is a `{team_id: {…}}` map — a forward-looking per-team override- bag. Today the only honored key is `max_runs_per_tick` (overrides `MAX_RUNS_PER_TEAM_PER_TICK`- for that team — give an important dogfooder more headroom or hold a noisy one lower, no- deploy); add more per-team settings under the same blob later. The override takes precedence- over the global default for its team; teams not listed keep the global default.-- Absent/malformed (`None` payload included) → `{}` (everyone on the defaults). Defensive- parse: JSON object keys arrive as strings so they're coerced to int; entries whose value- isn't a dict are dropped. Each consumer validates the specific key it reads (see- `_allocate_tick_budget._team_cap`). Keys are canonicalized to parent projects at planning- time (see `_canonicalize_team_config_keys`).- """- if payload is None:- return {}-- raw = payload.get("team_configs", {})- if not isinstance(raw, dict):- return {}-- configs: dict[int, dict] = {}- for key, value in raw.items():- if not isinstance(value, dict):- continue- try:- team_id = int(key)- except (TypeError, ValueError):- continue- configs[team_id] = value- return configs---def _default_team_config(payload: dict | None) -> dict:- """Fleet-wide default config applied to every enrolled team, parsed from the `signals-scout`- flag payload key `default_team_config`.-- Same inner shape as a `team_configs` entry (today: `max_runs_per_tick`). It sits between a- per-team `team_configs` override and the code constant in `_resolve_max_runs_per_tick`, so a- single fleet-wide cost guardrail (e.g. cap every enrolled team at 1 run/tick for launch) can- be set in the flag UI with no deploy, while specific teams still get more headroom via- `team_configs`. Absent/malformed (`None` payload included) → `{}` (everyone falls back to the- code constants — unchanged behaviour).- """- if payload is None:- return {}- raw = payload.get("default_team_config", {})- return raw if isinstance(raw, dict) else {}--def _overdue_seconds(config: SignalScoutConfig, now: datetime) -> float | None:"""Seconds past due (down to `-DUE_GRACE_SECONDS`), or None if not yet due. Never-run rows are maximally overdue."""if config.last_run_at is None:diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex 1afd3c89b6a8..281c493b952c 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -22,9 +22,19 @@ from posthog.sync import database_sync_to_asyncfrom products.signals.backend.models import SignalScoutConfigfrom products.signals.backend.scout_harness.config_registry import register_missing_configsfrom products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, sync_canonical_skills-from products.signals.backend.temporal.agentic.scout_coordinator import (++# The flag-payload read + per-team cap resolution live in `scout_harness/team_limits.py`; helpers+# defined there are imported and patched there (see `_PAYLOAD_PATH` / `_IS_CLOUD_PATH`).+from products.signals.backend.scout_harness.team_limits import (DEFAULT_ENROLLED_TEAM_IDS,SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID,+ _default_team_config,+ _enrolled_team_ids,+ _read_flag_payload,+ _resolve_max_runs_per_day,+ _team_configs,+)+from products.signals.backend.temporal.agentic.scout_coordinator import (CoordinatorWorkflowInput,CoordinatorWorkflowOutput,FetchEnabledRunsInput,@@ -32,19 +42,14 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (SignalsScoutCoordinatorWorkflow,StampDispatchedRunsInput,_allocate_tick_budget,- _default_team_config,_DueRun,- _enrolled_team_ids,- _read_flag_payload,- _resolve_max_runs_per_day,- _team_configs,fetch_enabled_signals_scout_runs_activity,stamp_dispatched_signals_scout_runs_activity,)from products.skills.backend.models.skills import LLMSkill-_PAYLOAD_PATH = "products.signals.backend.temporal.agentic.scout_coordinator.posthoganalytics.get_feature_flag_payload"-_IS_CLOUD_PATH = "products.signals.backend.temporal.agentic.scout_coordinator.is_cloud"+_PAYLOAD_PATH = "products.signals.backend.scout_harness.team_limits.posthoganalytics.get_feature_flag_payload"+_IS_CLOUD_PATH = "products.signals.backend.scout_harness.team_limits.is_cloud"# Enrollment is driven by the `signals-scout` flag payload allowlist. These async tests commit# (no transaction rollback across the worker thread), so leftover teams from other modules can@@ -419,7 +424,7 @@ async def test_per_team_tick_cap_defers_overflow(ateam):ateam, name, enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=hours))- with patch("products.signals.backend.temporal.agentic.scout_coordinator.MAX_RUNS_PER_TEAM_PER_TICK", 2):+ with patch("products.signals.backend.scout_harness.team_limits.MAX_RUNS_PER_TEAM_PER_TICK", 2):planned = await _run_activity()assert sorted(p.skill_name for p in planned) == ["signals-scout-mid", "signals-scout-most"]diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 2bea6a119683..1818b2ae601e 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -28,6 +28,7 @@ from products.signals.backend.models import (SignalScratchpad,)from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, discover_canonical_skills+from products.signals.backend.scout_harness.team_limits import MAX_RUNS_PER_TEAM_PER_TICKfrom products.signals.backend.scout_harness.tools.profile import compute_project_profilefrom products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_idsfrom products.skills.backend.models.skills import LLMSkill@@ -1110,3 +1111,106 @@ class TestScoutHarnessConfigAPI(APIBaseTest):self._list_url(), data={"skill_name": "signals-scout-fresh", "run_interval_minutes": 5}, format="json")assert response.status_code == status.HTTP_400_BAD_REQUEST+++_METADATA_PAYLOAD_PATH = "products.signals.backend.scout_harness.team_limits.posthoganalytics.get_feature_flag_payload"+++class TestScoutHarnessMetadataAPI(APIBaseTest):+ def _url(self) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/metadata/current/"++ def _get(self, payload: dict | None):+ # The endpoint reads the flag payload via team_limits; stub it so enrollment + caps are+ # deterministic without depending on the live flag.+ with patch(_METADATA_PAYLOAD_PATH, return_value=payload):+ return self.client.get(self._url())++ def test_returns_metadata_shape(self) -> None:+ response = self._get({"guaranteed_team_ids": [self.team.id]})+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert set(body.keys()) == {"enrolled", "banner_message", "limits"}+ assert set(body["limits"].keys()) == {+ "max_runs_per_tick",+ "max_runs_per_day",+ "runs_today",+ "runs_remaining_today",+ }++ @parameterized.expand([("listed", True), ("not_listed", False)])+ def test_enrolled_reflects_guaranteed_team_ids(self, _name: str, listed: bool) -> None:+ team_id = self.team.id if listed else self.team.id + 1+ assert self._get({"guaranteed_team_ids": [team_id]}).json()["enrolled"] is listed++ def test_falls_back_to_suppressed_metadata_when_flag_unavailable(self) -> None:+ # Flag service down → `_read_flag_payload` returns None: enrollment falls back to the+ # gated allowlist (which this fresh team isn't on), the banner is suppressed, and the caps+ # default to the code constants. The endpoint must stay up and fail closed, not error.+ body = self._get(None).json()+ assert body["enrolled"] is False+ assert body["banner_message"] is None+ assert body["limits"]["max_runs_per_tick"] == MAX_RUNS_PER_TEAM_PER_TICK+ assert body["limits"]["max_runs_per_day"] is None++ def test_banner_message_surfaced_from_payload(self) -> None:+ body = self._get(+ {"guaranteed_team_ids": [self.team.id], "scouts_banner_message": "Alpha: daily runs limited"}+ ).json()+ assert body["banner_message"] == "Alpha: daily runs limited"++ @parameterized.expand(+ [("unset", {}), ("blank", {"scouts_banner_message": " "}), ("non_string", {"scouts_banner_message": 123})]+ )+ def test_banner_message_null_when_unset_blank_or_non_string(self, _name: str, extra: dict) -> None:+ body = self._get({"guaranteed_team_ids": [self.team.id], **extra}).json()+ assert body["banner_message"] is None++ def test_limits_unbounded_by_default(self) -> None:+ # No caps configured anywhere → day is uncapped and the per-tick cap falls back to the+ # code default; the UI should show "no daily limit" rather than a fabricated number.+ body = self._get({"guaranteed_team_ids": [self.team.id]}).json()+ assert body["limits"]["max_runs_per_day"] is None+ assert body["limits"]["runs_remaining_today"] is None+ assert body["limits"]["max_runs_per_tick"] == MAX_RUNS_PER_TEAM_PER_TICK++ def test_limits_resolved_from_default_team_config(self) -> None:+ body = self._get(+ {+ "guaranteed_team_ids": [self.team.id],+ "default_team_config": {"max_runs_per_day": 3, "max_runs_per_tick": 1},+ }+ ).json()+ assert body["limits"]["max_runs_per_day"] == 3+ assert body["limits"]["max_runs_per_tick"] == 1++ def test_per_team_config_overrides_default(self) -> None:+ body = self._get(+ {+ "guaranteed_team_ids": [self.team.id],+ "default_team_config": {"max_runs_per_day": 3},+ "team_configs": {str(self.team.id): {"max_runs_per_day": 50}},+ }+ ).json()+ assert body["limits"]["max_runs_per_day"] == 50++ def test_runs_today_and_remaining_count_recent_runs(self) -> None:+ _make_run(self.team)+ _make_run(self.team)+ body = self._get({"guaranteed_team_ids": [self.team.id], "default_team_config": {"max_runs_per_day": 5}}).json()+ assert body["limits"]["runs_today"] == 2+ assert body["limits"]["runs_remaining_today"] == 3++ def test_remaining_floors_at_zero_when_budget_spent(self) -> None:+ for _ in range(3):+ _make_run(self.team)+ body = self._get({"guaranteed_team_ids": [self.team.id], "default_team_config": {"max_runs_per_day": 1}}).json()+ assert body["limits"]["runs_today"] == 3+ assert body["limits"]["runs_remaining_today"] == 0++ def test_runs_today_does_not_count_other_teams(self) -> None:+ other = Team.objects.create(organization=self.organization, name="Other")+ _make_run(other)+ _make_run(self.team)+ body = self._get({"guaranteed_team_ids": [self.team.id], "default_team_config": {"max_runs_per_day": 5}}).json()+ assert body["limits"]["runs_today"] == 1diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 1525dea14e96..4cee42756121 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -334,6 +334,47 @@ export interface PatchedSignalScoutConfigApi {readonly created_at?: string}+/**+ * A team's enforced scout run caps and current usage.+ *+ * These are the values the coordinator actually applies at dispatch (resolved per-team override →+ * fleet-wide default → code constant), so the UI can show the real throttle rather than what a+ * user thinks they configured.+ */+export interface ScoutLimitsApi {+ /** Most scout runs the team can start in a single 30-minute coordinator tick. */+ max_runs_per_tick: number+ /**+ * Most scout runs the team can start per rolling 24 hours, or null when uncapped.+ * @nullable+ */+ max_runs_per_day: number | null+ /** Scout runs the team has started in the trailing 24 hours. */+ runs_today: number+ /**+ * Runs still allowed in the trailing 24h window (max_runs_per_day − runs_today), or null when uncapped.+ * @nullable+ */+ runs_remaining_today: number | null+}++/**+ * Team-scoped scout metadata for the inbox / Code-app UIs: enrollment, the alpha banner, and+ * the enforced limits. Sourced from the `signals-scout` flag payload so the banner and caps can+ * change without a deploy to either app.+ */+export interface ScoutMetadataApi {+ /** Whether this project is enrolled to run scouts (set via the signals-scout flag allowlist). */+ enrolled: boolean+ /**+ * Free-form announcement banner to show above the scout UI (e.g. alpha run-limit notice), or null when unset.+ * @nullable+ */+ banner_message: string | null+ /** The team's enforced scout run caps and current usage. */+ limits: ScoutLimitsApi+}+/*** `inventory.project_context` — free-form orientation about the project's product.*/diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex d9fae2c36d2f..4fb09f635e87 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -23,6 +23,7 @@ import type {ProjectProfileApi,RememberRequestApi,ScoutEmissionReportLinkApi,+ ScoutMetadataApi,ScratchpadEntryApi,SignalReportApi,SignalReportBulkStateRequestApi,@@ -309,6 +310,21 @@ export const signalsScoutConfigSync = async (})}+export const getSignalsScoutMetadataGetUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/metadata/current/`+}++/**+ * Return the project's scout metadata: whether it is enrolled, the current announcement banner (e.g. an alpha run-limit notice, or null when unset), and the enforced run limits with current usage. Limits reflect what the coordinator actually applies at dispatch, so a user can see the real throttle rather than what they assume they set. All values come from the `signals-scout` flag payload, so the banner and caps can change with no deploy.+ * @summary Get scout metadata+ */+export const signalsScoutMetadataGet = async (projectId: string, options?: RequestInit): Promise<ScoutMetadataApi> => {+ return apiMutator<ScoutMetadataApi>(getSignalsScoutMetadataGetUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsScoutProjectProfileGetUrl = (projectId: string,params?: SignalsScoutProjectProfileGetParamsdiff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex cc8a73423c2f..e4a9d33d923d 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -285,6 +285,9 @@ tools:`Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call withthe same `finding_id` emits a second signal, so emit each finding exactly once and never retry an emit.Findings should carry `tags` — see the `tags` param for the slug and taxonomy convention.+ signals-scout-metadata-get:+ operation: signals_scout_metadata_get+ enabled: falsesignals-scout-project-profile-get:operation: signals_scout_project_profile_getenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3809a149df65..87ea97f525bc 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -45052,6 +45052,47 @@ export namespace Schemas {report: LinkedSignalReport | null;}+ /**+ * A team's enforced scout run caps and current usage.+ *+ * These are the values the coordinator actually applies at dispatch (resolved per-team override →+ * fleet-wide default → code constant), so the UI can show the real throttle rather than what a+ * user thinks they configured.+ */+ export interface ScoutLimits {+ /** Most scout runs the team can start in a single 30-minute coordinator tick. */+ max_runs_per_tick: number;+ /**+ * Most scout runs the team can start per rolling 24 hours, or null when uncapped.+ * @nullable+ */+ max_runs_per_day: number | null;+ /** Scout runs the team has started in the trailing 24 hours. */+ runs_today: number;+ /**+ * Runs still allowed in the trailing 24h window (max_runs_per_day − runs_today), or null when uncapped.+ * @nullable+ */+ runs_remaining_today: number | null;+ }++ /**+ * Team-scoped scout metadata for the inbox / Code-app UIs: enrollment, the alpha banner, and+ * the enforced limits. Sourced from the `signals-scout` flag payload so the banner and caps can+ * change without a deploy to either app.+ */+ export interface ScoutMetadata {+ /** Whether this project is enrolled to run scouts (set via the signals-scout flag allowlist). */+ enrolled: boolean;+ /**+ * Free-form announcement banner to show above the scout UI (e.g. alpha run-limit notice), or null when unset.+ * @nullable+ */+ banner_message: string | null;+ /** The team's enforced scout run caps and current usage. */+ limits: ScoutLimits;+ }+/*** `SignalScratchpad` projection used by `search-memory` and `remember`.*/