: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 on-demand scout run endpoint and MCP tool (#66996)
Andrew Maguiref02c8e16a7ba
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 9d7815dcc02d..70fc341efc54 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -1451,6 +1451,26 @@ class SignalScoutConfigCreateSerializer(serializers.Serializer):return value+class SignalScoutManualRunSerializer(serializers.Serializer):+ """Response for an on-demand (`run now`) scout dispatch.++ The run executes asynchronously on the Temporal worker, so there is no `SignalScoutRun`+ row yet at response time — the bridge row is created once the run's first turn starts.+ Poll the scout's runs (`signals-scout-runs-list`) to see the resulting run and its findings.+ """++ skill_name = serializers.CharField(help_text="The `signals-scout-*` skill that was dispatched.")+ workflow_id = serializers.CharField(+ help_text=(+ "Temporal workflow id for the dispatched run. The run executes asynchronously; poll the "+ "scout's runs to see the resulting run row, its status, and any emitted findings."+ )+ )+ started = serializers.BooleanField(+ help_text="True when a new run was dispatched. The endpoint returns 409 instead when a run for this scout is already in progress."+ )++# --- Team metadata ---------------------------------------------------------diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 9c4ac3e650ed..a2096ae22a30 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -22,6 +22,9 @@ from __future__ import annotationsimport uuidimport dataclassesfrom dataclasses import dataclass+from datetime import timedelta++from django.utils import timezoneimport structlogfrom drf_spectacular.types import OpenApiTypes@@ -31,6 +34,7 @@ from rest_framework.decorators import actionfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.api.mixins import validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin@@ -43,6 +47,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.models.team.team import Teamfrom posthog.permissions import APIScopePermission+from posthog.temporal.common.client import sync_connectfrom products.signals.backend.models import (SignalProjectProfile,@@ -51,6 +56,7 @@ from products.signals.backend.models import (SignalScoutEmission,SignalScoutRun,)+from products.signals.backend.quota import is_team_signals_quota_limitedfrom products.signals.backend.report_generation.resolve_reviewers import MAX_PROJECT_MEMBERS, list_project_membersfrom products.signals.backend.scout_harness.config_registry import (enabled_scout_count,@@ -62,7 +68,7 @@ from products.signals.backend.scout_harness.lazy_seed import (canonical_skill_names,sync_canonical_skills,)-from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM+from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM, STALE_RUN_CUTOFF_Sfrom products.signals.backend.scout_harness.serializers import (EditReportRequestSerializer,EditReportResponseSerializer,@@ -90,11 +96,21 @@ from products.signals.backend.scout_harness.serializers import (SignalScoutConfigCreateSerializer,SignalScoutConfigSerializer,SignalScoutEmissionSerializer,+ SignalScoutManualRunSerializer,SignalScoutRunDetailSerializer,SignalScoutRunSummarySerializer,)from products.signals.backend.scout_harness.skill_loader import SkillNotFoundError, load_skill_for_runfrom products.signals.backend.scout_harness.team_limits import (+ DAILY_BUDGET_WINDOW,+ _canonicalize_team_config_keys,+ _default_team_config,+ _parse_enrollment,+ _read_flag_payload,+ _resolve_enrolled,+ _resolve_max_runs_per_day,+ _runs_today_by_team,+ _team_configs,resolve_sync_seed_inputs,resolve_team_metadata,withheld_skills_for_team,@@ -120,8 +136,8 @@ from products.signals.backend.scout_harness.tools.scratchpad import (search_scratchpad,)from products.signals.backend.scout_report import InvalidScoutReportError-from products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_idsfrom products.skills.backend.models.skills import LLMSkill+from products.tasks.backend.facade import api as tasks_facadelogger = structlog.get_logger(__name__)@@ -177,6 +193,71 @@ def _caller_carries_scout_internal_scope(request: Request) -> bool:return "signal_scout_internal:write" in scopes+class Conflict(exceptions.APIException):+ status_code = status.HTTP_409_CONFLICT+ default_detail = "A run for this scout is already in progress."+ default_code = "conflict"+++def _scout_run_in_flight(team_id: int, skill_name: str) -> bool:+ """Whether a *live* run for this `(canonical team, skill)` is already QUEUED or IN_PROGRESS.++ Mirrors the runner's authoritative single-flight (`scout_harness/runner._has_running_run`)+ so the manual-trigger endpoint can fail fast with a 409 instead of dispatching a workflow+ that the runner would only skip. Status flows from the linked `TaskRun`; covers a run+ started by either the coordinator or a prior manual trigger.++ A run older than `STALE_RUN_CUTOFF_S` is an orphan left by a crashed worker (Temporal kills+ the activity at the hard ceiling, so it cannot still be executing) — it is deliberately NOT+ counted as in-flight here. Otherwise this fail-fast 409 would short-circuit before the+ workflow's runner reaches its `_self_heal_stale_runs` reap, wedging the lane until a+ scheduled tick happens to reap it — which never comes for a disabled scout, whose only run+ path is this endpoint. Treating the orphan as free lets the dispatched run reap it and proceed.+ """+ live_cutoff = timezone.now() - timedelta(seconds=STALE_RUN_CUTOFF_S)+ return (+ SignalScoutRun.objects.unscoped()+ .filter(+ team_id=team_id,+ skill_name=skill_name,+ task_run__status__in=(tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS),+ task_run__created_at__gte=live_cutoff,+ )+ .exists()+ )+++def _reject_if_manual_run_suppressed(team_id: int) -> None:+ """Apply the fleet-level gates the scheduled coordinator enforces, so a manual trigger can't+ run a scout the scheduled path would deliberately suppress.++ Reads the `signals-scout` flag payload once (the same snapshot the coordinator plans off):++ - **Enrollment kill switch.** A project in `skip_team_ids`, or one not enrolled at all, never+ runs scheduled scouts — so its manual trigger is forbidden too (403). Without this, any+ caller with `signal_scout:write` could run a scout on a project an operator has explicitly+ drained or held back via the flag.+ - **Daily run budget.** `max_runs_per_day` (per-team override → fleet default → code constant)+ bounds dispatches per rolling 24h. Manual runs land the same `SignalScoutRun` rows the+ coordinator counts, so they share the tally: once the budget is spent the trigger is+ throttled (429) until the window rolls, instead of letting repeated manual runs blow past+ the per-team daily cap the scheduled path enforces.++ `team_id` is the canonical (parent) project id, matching how the coordinator plans; team+ config keys are canonicalized the same way so a child-env override still lines up.+ """+ payload = _read_flag_payload()+ if not _resolve_enrolled(team_id, _parse_enrollment(payload)):+ raise exceptions.PermissionDenied(detail="Signals scouts are not enabled for this project.")++ team_configs = _canonicalize_team_config_keys(_team_configs(payload))+ per_day = _resolve_max_runs_per_day(team_id, team_configs, _default_team_config(payload))+ if per_day is not None:+ runs_today = _runs_today_by_team({team_id}, timezone.now() - DAILY_BUDGET_WINDOW).get(team_id, 0)+ if runs_today >= per_day:+ raise exceptions.Throttled(detail="This project has reached its daily scout run budget. Try again later.")++def _parse_run_id_or_404(kwargs: dict) -> uuid.UUID:"""Parse the run-id URL kwarg as a UUID; raise 404 on missing or malformed.@@ -248,6 +329,13 @@ def _resolve_emission_report_links(source_id_to_report_id: dict[str, str] = {}if source_ids:try:+ # Deferred: keeps the heavy Signals Temporal workflow/activity graph (dragged in by the+ # `products.signals.backend.temporal` package aggregator) off the route-load path — this+ # viewset is imported by routes.py just to register routes.+ from products.signals.backend.temporal.signal_queries import (+ fetch_report_ids_for_source_ids, # noqa: PLC0415+ )+source_id_to_report_id = fetch_report_ids_for_source_ids(canonical_team, source_ids)except Exception:logger.exception("scout_emission_reports_lookup_failed", team_id=team_id, **log_context)@@ -1424,6 +1512,107 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):skill_info = _skill_info_for(team_id, [instance.skill_name])return Response(SignalScoutConfigSerializer(instance, context={"skill_info": skill_info}).data)+ @extend_schema(+ request=None,+ responses={+ 202: OpenApiResponse(+ response=SignalScoutManualRunSerializer,+ description="A run was dispatched. It executes asynchronously; poll the scout's runs for the result.",+ ),+ 403: OpenApiResponse(description="Signals scouts are not enabled for this project."),+ 404: OpenApiResponse(description="Config not found for this project (or the scout is withheld)."),+ 409: OpenApiResponse(description="A run for this scout is already in progress."),+ 429: OpenApiResponse(+ description="The project is over its Signals credits quota or daily scout run budget; try again later."+ ),+ },+ summary="Run a scout now",+ description=(+ "Dispatch one on-demand run of this scout immediately, regardless of its schedule. "+ "Useful to test a scout right after authoring it, or to refresh its findings on demand. "+ "The run executes asynchronously on the worker and inherits every guard the scheduled "+ "path has: it is forbidden if scouts are not enabled for the project (403), and skipped "+ "if the project is over its Signals credits quota or daily run budget (429) or a run for "+ "this scout is already in progress (409). A manual run does not change the scout's "+ "schedule or `last_run_at`. A disabled scout can still be run this way (to test before "+ "enabling). Returns immediately with the workflow id — poll the scout's runs for the result."+ ),+ operation_id="signals_scout_config_run",+ )+ @action(+ detail=True,+ methods=["post"],+ url_path="run",+ # Running a scout drives spend, so this is a write — same scope as enabling a config.+ required_scopes=["signal_scout:write"],+ )+ def run(self, request: Request, *args, **kwargs) -> Response:+ team_id = _canonical_team_id(self)+ config_id = _parse_run_id_or_404(kwargs)+ config = SignalScoutConfig.objects.unscoped().filter(team_id=team_id, id=config_id).first()+ if config is None:+ raise exceptions.NotFound()+ skill_name = config.skill_name+ # A withheld scout is invisible across the whole config API (it's excluded from list), so a+ # run request for one is a 404 here too — and the runner would refuse it anyway. Resolved+ # against the canonical team, matching `list`/`sync`.+ if skill_name in withheld_skills_for_team(team_id):+ raise exceptions.NotFound()++ # A config can outlive its skill (the list serializer tolerates a missing skill). Dispatching+ # for one would 202 + hand back a workflow id, but the runner's `load_skill_for_run` raises+ # `SkillNotFoundError` before any run row exists — so polling never shows a result. Reject up+ # front, mirroring `create`'s latest-non-deleted-skill check. The config is effectively dead+ # without its skill, so this is a 404 alongside the withheld branch above.+ if not LLMSkill.objects.filter(team_id=team_id, name=skill_name, is_latest=True, deleted=False).exists():+ raise exceptions.NotFound()++ # Honor the fleet-level controls the scheduled coordinator enforces before it would ever+ # dispatch this scout: the enrollment kill switch (`skip_team_ids` / not-enrolled → 403) and+ # the per-team daily run budget (`max_runs_per_day` → 429). Without these, a manual trigger+ # would bypass a rollout/kill-switch the operator set in the flag, and let repeated runs+ # exceed the daily cap the scheduled path respects.+ _reject_if_manual_run_suppressed(team_id)++ # Fail-fast guards so the trigger can't be gamed into churning workflows or spend. Both are+ # re-checked authoritatively downstream (quota in the run activity, single-flight in the+ # runner and at the Temporal server), but rejecting here avoids dispatching a workflow that+ # would only be skipped, and turns the common cases into clean 429/409 responses.+ api_token = Team.objects.only("api_token").get(pk=team_id).api_token+ if is_team_signals_quota_limited(api_token):+ raise exceptions.Throttled(detail="This project is over its Signals credits quota. Try again later.")+ if _scout_run_in_flight(team_id, skill_name):+ raise Conflict()++ # Deferred: keeps the heavy Signals Temporal workflow/activity graph (dragged in by the+ # `products.signals.backend.temporal` package aggregator) off the route-load path — this viewset+ # is imported by routes.py just to register routes, so a module-level import would make every+ # API/schema route load pay the full graph.+ from products.signals.backend.temporal.agentic.scout_scheduler import (+ start_manual_signals_scout_run, # noqa: PLC0415+ )++ try:+ workflow_id = start_manual_signals_scout_run(sync_connect(), team_id=team_id, skill_name=skill_name)+ except WorkflowAlreadyStartedError:+ # A run for this scout was dispatched between the in-flight check and the start call —+ # the Temporal server's id-conflict policy single-flights it. Surface the same 409.+ raise Conflict()++ logger.info(+ "signals_scout: manual run dispatched",+ team_id=team_id,+ skill_name=skill_name,+ workflow_id=workflow_id,+ user_id=request.user.pk,+ )+ return Response(+ SignalScoutManualRunSerializer(+ {"skill_name": skill_name, "workflow_id": workflow_id, "started": True}+ ).data,+ status=status.HTTP_202_ACCEPTED,+ )+@extend_schema(request=None,responses={diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.pyindex 058d6bc3db18..9e2cb9a0c631 100644--- a/products/signals/backend/temporal/agentic/scout_scheduler.py+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py@@ -1,14 +1,18 @@from __future__ import annotations+import hashlibfrom dataclasses import dataclassfrom datetime import timedeltafrom typing import TYPE_CHECKING+from django.conf import settingsfrom django.db import InterfaceError, OperationalErrorimport structlogimport temporalio-from temporalio.common import RetryPolicy+from asgiref.sync import async_to_sync+from temporalio.client import Client+from temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom posthog.models import Teamfrom posthog.sync import database_sync_to_async@@ -165,3 +169,48 @@ class RunSignalsScoutWorkflow:# tick will try again.retry_policy=RetryPolicy(maximum_attempts=1),)+++def manual_run_workflow_id(team_id: int, skill_name: str) -> str:+ """Deterministic workflow id for an on-demand (`run now`) scout run.++ Distinct namespace from the coordinator's per-tick child ids (`signals-scout-run-…`)+ so a manual run can't collide with a scheduled one. Stable per `(team, skill)` so the+ id-conflict policy in `start_manual_signals_scout_run` can single-flight against it.++ The readable skill fragment is truncated for legibility, but a digest of the *full*+ skill name is appended so two custom scouts sharing the first 60 chars still map to+ distinct ids — otherwise `WorkflowIDConflictPolicy.FAIL` would 409 one scout while the+ other (truncation-twin) is running, even though it has no in-flight run of its own.+ """+ safe_skill = skill_name.replace(" ", "_")[:60]+ digest = hashlib.sha256(skill_name.encode("utf-8"), usedforsecurity=False).hexdigest()[:12]+ return f"signals-scout-manual-run-{team_id}-{safe_skill}-{digest}"+++@async_to_sync+async def start_manual_signals_scout_run(client: Client, *, team_id: int, skill_name: str) -> str:+ """Dispatch one on-demand scout run on the signals task queue; return its workflow id.++ Reuses `RunSignalsScoutWorkflow`, so a manual run inherits every guard the scheduled+ path has — the activity's Signals-credits quota check, and the runner's withheld-skill+ denylist, stale-run self-heal, and single-flight. It does NOT honor the per-scout+ schedule or `last_run_at`: a manual run is off-schedule and deliberately leaves the+ cadence untouched.++ Single-flight is enforced at the Temporal server, so the trigger can't be gamed into+ stacking concurrent runs of the same scout: `ALLOW_DUPLICATE` lets the stable id be+ reused once the prior manual run has closed, while `FAIL` rejects a second trigger+ while one is still running — raising `WorkflowAlreadyStartedError` for the caller to+ map to a 409.+ """+ workflow_id = manual_run_workflow_id(team_id, skill_name)+ await client.start_workflow(+ RunSignalsScoutWorkflow.run,+ RunSignalsScoutInput(team_id=team_id, skill_name=skill_name),+ id=workflow_id,+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ id_conflict_policy=WorkflowIDConflictPolicy.FAIL,+ )+ return workflow_iddiff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex fa44dafa3344..209ae42d5ec7 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -12,6 +12,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import statusfrom social_django.models import UserSocialAuth+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.models import OAuthApplicationfrom posthog.models.organization import Organization@@ -34,6 +35,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.limits import STALE_RUN_CUTOFF_Sfrom 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_ids@@ -295,7 +297,7 @@ class TestScoutHarnessRunEmissionsAPI(APIBaseTest):# Patch target: the helper is hot-imported into the view module, so patch it there, not at source.-_FETCH_REPORT_IDS = "products.signals.backend.scout_harness.views.fetch_report_ids_for_source_ids"+_FETCH_REPORT_IDS = "products.signals.backend.temporal.signal_queries.fetch_report_ids_for_source_ids"class TestScoutHarnessEmissionReportsAPI(APIBaseTest):@@ -1488,6 +1490,153 @@ class TestScoutHarnessMetadataAPI(APIBaseTest):assert body["limits"]["runs_today"] == 1+_QUOTA = "products.signals.backend.scout_harness.views.is_team_signals_quota_limited"+_START = "products.signals.backend.temporal.agentic.scout_scheduler.start_manual_signals_scout_run"+_CONNECT = "products.signals.backend.scout_harness.views.sync_connect"+_WITHHELD = "products.signals.backend.scout_harness.views.withheld_skills_for_team"+_FLAG = "products.signals.backend.scout_harness.views._read_flag_payload"+++class TestScoutHarnessConfigRunAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # The run action requires a live backing skill; every dispatch case needs one present.+ LLMSkill.objects.create(team=self.team, name="signals-scout-foo", description="Foo scout.", body="...")+ # The manual run honors the same enrollment + daily-budget gates as the coordinator. Enroll+ # this team by default (no daily cap) so the dispatch cases reach the run path; the+ # enrollment/budget regression cases override this payload.+ flag = patch(_FLAG, return_value={"guaranteed_team_ids": [self.team.id]})+ flag.start()+ self.addCleanup(flag.stop)++ def _run_url(self, config_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/configs/{config_id}/run/"++ @parameterized.expand([("enabled", True), ("disabled", False)])+ def test_run_dispatches_and_returns_workflow_id(self, _name: str, enabled: bool) -> None:+ # Disabled scouts are dispatchable too (run-to-test before enabling) — that's the regression+ # guard for the "allow disabled" decision; a stray `enabled` gate would fail the disabled case.+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo", enabled=enabled)+ with (+ patch(_QUOTA, return_value=False),+ patch(_CONNECT) as connect,+ patch(_START, return_value="wf-123") as start,+ ):+ response = self.client.post(self._run_url(str(config.id)))++ assert response.status_code == status.HTTP_202_ACCEPTED+ assert response.json() == {"skill_name": "signals-scout-foo", "workflow_id": "wf-123", "started": True}+ start.assert_called_once_with(connect.return_value, team_id=self.team.id, skill_name="signals-scout-foo")++ def test_run_over_quota_returns_429_without_dispatching(self) -> None:+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")+ with patch(_QUOTA, return_value=True), patch(_START) as start:+ response = self.client.post(self._run_url(str(config.id)))++ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ start.assert_not_called()++ def test_run_with_in_flight_run_returns_409_without_dispatching(self) -> None:+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")+ _make_run(self.team, skill_name="signals-scout-foo") # TaskRun IN_PROGRESS by default+ with patch(_QUOTA, return_value=False), patch(_START) as start:+ response = self.client.post(self._run_url(str(config.id)))++ assert response.status_code == status.HTTP_409_CONFLICT+ start.assert_not_called()++ def test_run_maps_workflow_already_started_race_to_409(self) -> None:+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")+ race = WorkflowAlreadyStartedError("wf", "RunSignalsScoutWorkflow")+ with patch(_QUOTA, return_value=False), patch(_CONNECT), patch(_START, side_effect=race):+ response = self.client.post(self._run_url(str(config.id)))++ assert response.status_code == status.HTTP_409_CONFLICT++ def test_run_unknown_config_returns_404_without_dispatching(self) -> None:+ with patch(_QUOTA, return_value=False), patch(_START) as start:+ response = self.client.post(self._run_url("00000000-0000-0000-0000-000000000000"))++ assert response.status_code == status.HTTP_404_NOT_FOUND+ start.assert_not_called()++ def test_run_withheld_scout_returns_404_without_dispatching(self) -> None:+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")+ with (+ patch(_WITHHELD, return_value={"signals-scout-foo"}),+ patch(_QUOTA, return_value=False),+ patch(_START) as start,+ ):+ response = self.client.post(self._run_url(str(config.id)))++ assert response.status_code == status.HTTP_404_NOT_FOUND+ start.assert_not_called()++ def test_run_config_without_backing_skill_returns_404_without_dispatching(self) -> None:+ # A config can outlive its skill; dispatching would 202 then fail in the runner with no run+ # row to poll. Reject up front — guards the latest-non-deleted-skill check in `run`.+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-orphan")+ with patch(_QUOTA, return_value=False), patch(_START) as start:+ response = self.client.post(self._run_url(str(config.id)))++ assert response.status_code == status.HTTP_404_NOT_FOUND+ start.assert_not_called()++ def test_run_dispatches_when_only_in_flight_run_is_stale(self) -> None:+ # An orphan past the stale cutoff (crashed worker, never wrote a terminal status) must not+ # wedge the 409 fail-fast — otherwise a disabled scout, whose only run path is this endpoint,+ # could never recover. The dispatched run's own self-heal reaps it; the view must let it through.+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")+ stale = _make_run(self.team, skill_name="signals-scout-foo") # TaskRun IN_PROGRESS by default+ old = timezone.now() - timedelta(seconds=STALE_RUN_CUTOFF_S + 60)+ TaskRun = apps.get_model("tasks", "TaskRun")+ TaskRun.objects.filter(id=stale.task_run_id).update(created_at=old)+ with (+ patch(_QUOTA, return_value=False),+ patch(_CONNECT),+ patch(_START, return_value="wf-123") as start,+ ):+ response = self.client.post(self._run_url(str(config.id)))++ assert response.status_code == status.HTTP_202_ACCEPTED+ start.assert_called_once()++ def test_run_on_skipped_team_returns_403_without_dispatching(self) -> None:+ # `skip_team_ids` is the operator kill switch: the coordinator never schedules a skipped+ # team, so the manual trigger must refuse it too — otherwise any `signal_scout:write` caller+ # could run a scout an operator deliberately suppressed. Guards the enrollment check in `run`.+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")+ with (+ patch(_FLAG, return_value={"guaranteed_team_ids": [self.team.id], "skip_team_ids": [self.team.id]}),+ patch(_QUOTA, return_value=False),+ patch(_START) as start,+ ):+ response = self.client.post(self._run_url(str(config.id)))++ assert response.status_code == status.HTTP_403_FORBIDDEN+ start.assert_not_called()++ def test_run_over_daily_budget_returns_429_without_dispatching(self) -> None:+ # Manual runs count against the same per-team daily budget the coordinator enforces, so once+ # `max_runs_per_day` is spent the trigger is throttled instead of letting repeated manual runs+ # blow past the cap. One run already landed today and the cap is 1 → the next is refused.+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")+ TaskRun = apps.get_model("tasks", "TaskRun")+ _make_run(self.team, skill_name="signals-scout-foo", task_run_status=TaskRun.Status.COMPLETED)+ with (+ patch(+ _FLAG,+ return_value={"guaranteed_team_ids": [self.team.id], "default_team_config": {"max_runs_per_day": 1}},+ ),+ patch(_QUOTA, return_value=False),+ patch(_START) as start,+ ):+ response = self.client.post(self._run_url(str(config.id)))++ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ start.assert_not_called()++class TestScoutHarnessMembersAPI(APIBaseTest):def setUp(self) -> None:super().setUp()diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex c8936fd67ad2..459959bed9a6 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -488,6 +488,22 @@ export interface PatchedSignalScoutConfigApi {readonly created_at?: string}+/**+ * Response for an on-demand (`run now`) scout dispatch.+ *+ * The run executes asynchronously on the Temporal worker, so there is no `SignalScoutRun`+ * row yet at response time — the bridge row is created once the run's first turn starts.+ * Poll the scout's runs (`signals-scout-runs-list`) to see the resulting run and its findings.+ */+export interface SignalScoutManualRunApi {+ /** The `signals-scout-*` skill that was dispatched. */+ skill_name: string+ /** Temporal workflow id for the dispatched run. The run executes asynchronously; poll the scout's runs to see the resulting run row, its status, and any emitted findings. */+ workflow_id: string+ /** True when a new run was dispatched. The endpoint returns 409 instead when a run for this scout is already in progress. */+ started: boolean+}+/*** One project member's routing identity, for picking a `suggested_reviewers` entry on a report.*/diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex be8370bf31e2..fb466e3c6be2 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -46,6 +46,7 @@ import type {SignalScoutConfigApi,SignalScoutConfigCreateApi,SignalScoutEmissionApi,+ SignalScoutManualRunApi,SignalScoutRunDetailApi,SignalScoutRunSummaryApi,SignalSourceConfigApi,@@ -498,6 +499,25 @@ export const signalsScoutConfigDestroy = async (})}+export const getSignalsScoutConfigRunUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/scout/configs/${id}/run/`+}++/**+ * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if the project is over its Signals credits quota or daily run budget (429) or a run for this scout is already in progress (409). A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.+ * @summary Run a scout now+ */+export const signalsScoutConfigRun = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<SignalScoutManualRunApi> => {+ return apiMutator<SignalScoutManualRunApi>(getSignalsScoutConfigRunUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getSignalsScoutConfigSyncUrl = (projectId: string) => {return `/api/projects/${projectId}/signals/scout/configs/sync/`}diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex cf92ef708be0..f0cf7e9acd35 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -523,6 +523,23 @@ tools:`inbox-source-configs-list` / `inbox-reports-list` / `read-data-schema` / `activity-log-list`. Distinct from`signals-scout-scratchpad-list`: profile is ground truth from authoritative tables; scratchpad is thescout's inferred learnings.+ signals-scout-run-now:+ operation: signals_scout_config_run+ enabled: true+ scopes:+ - signal_scout:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Run a scout now+ description: >+ Dispatch one on-demand run of a scout by its config `id`, regardless of its schedule — useful to test a+ scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously and+ inherits the scheduled path's guards: it returns 429 if the project is over its Signals credits quota and+ 409 if a run for this scout is already in progress. A manual run does not change the scout's schedule, and a+ disabled scout can still be run this way (to test before enabling). Returns the workflow id immediately —+ poll `signals-scout-runs-list` for the resulting run and its findings.signals-scout-runs-emission-reports:operation: signals_scout_runs_emission_reportsenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 40a09acea922..696e396cf5b1 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6843,6 +6843,20 @@"readOnlyHint": true}},+ "signals-scout-run-now": {+ "description": "Dispatch one on-demand run of a scout by its config `id`, regardless of its schedule — useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously and inherits the scheduled path's guards: it returns 429 if the project is over its Signals credits quota and 409 if a run for this scout is already in progress. A manual run does not change the scout's schedule, and a disabled scout can still be run this way (to test before enabling). Returns the workflow id immediately — poll `signals-scout-runs-list` for the resulting run and its findings.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Run a scout now",+ "title": "Run a scout now",+ "required_scopes": ["signal_scout:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"signals-scout-runs-emission-reports": {"description": "For a `SignalScoutRun`, return each emitted finding paired with the inbox report its signal grouped into — the reverse lookup from a scout's emission to the `SignalReport` it actually produced. One row per emission with its `finding_id`, the deterministic `source_id` (`run:<run_id>:finding:<finding_id>`), and the linked `report` (`id`, `title`, `status`) or `null` when the finding never matched a report (or the report was deleted/suppressed). Use this to see *which* findings turned into actionable reports, not just what a run surfaced (`signals-scout-runs-emissions-list`). Requires `task:read` on top of `signal_scout:read` because it exposes report titles. Strictly team-scoped — a run UUID belonging to another team returns 404.","category": "Signals",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 97dd4aaea57d..d3763fcac3a7 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7354,6 +7354,20 @@"readOnlyHint": true}},+ "signals-scout-run-now": {+ "description": "Dispatch one on-demand run of a scout by its config `id`, regardless of its schedule — useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously and inherits the scheduled path's guards: it returns 429 if the project is over its Signals credits quota and 409 if a run for this scout is already in progress. A manual run does not change the scout's schedule, and a disabled scout can still be run this way (to test before enabling). Returns the workflow id immediately — poll `signals-scout-runs-list` for the resulting run and its findings.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Run a scout now",+ "title": "Run a scout now",+ "required_scopes": ["signal_scout:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"signals-scout-runs-emission-reports": {"description": "For a `SignalScoutRun`, return each emitted finding paired with the inbox report its signal grouped into — the reverse lookup from a scout's emission to the `SignalReport` it actually produced. One row per emission with its `finding_id`, the deterministic `source_id` (`run:<run_id>:finding:<finding_id>`), and the linked `report` (`id`, `title`, `status`) or `null` when the finding never matched a report (or the report was deleted/suppressed). Use this to see *which* findings turned into actionable reports, not just what a run surfaced (`signals-scout-runs-emissions-list`). Requires `task:read` on top of `signal_scout:read` because it exposes report titles. Strictly team-scoped — a run UUID belonging to another team returns 404.","category": "Signals",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 534f756560c0..108a5d52238f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -48164,6 +48164,22 @@ export namespace Schemas {emitted_at: string;}+ /**+ * Response for an on-demand (`run now`) scout dispatch.+ *+ * The run executes asynchronously on the Temporal worker, so there is no `SignalScoutRun`+ * row yet at response time — the bridge row is created once the run's first turn starts.+ * Poll the scout's runs (`signals-scout-runs-list`) to see the resulting run and its findings.+ */+ export interface SignalScoutManualRun {+ /** The `signals-scout-*` skill that was dispatched. */+ skill_name: string;+ /** Temporal workflow id for the dispatched run. The run executes asynchronously; poll the scout's runs to see the resulting run row, its status, and any emitted findings. */+ workflow_id: string;+ /** True when a new run was dispatched. The endpoint returns 409 instead when a run for this scout is already in progress. */+ started: boolean;+ }+/*** Full `SignalScoutRun` projection used by `get-run`. Same shape as the summary* today; kept distinct so future detail-only extensions (linked Signal rows,diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex bbe1a933cd3c..651a7696dcf8 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 33 enabled ops+ * PostHog API - MCP 34 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -463,6 +463,19 @@ export const SignalsScoutConfigDestroyParams = /* @__PURE__ */ zod.object({),})+/**+ * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if the project is over its Signals credits quota or daily run budget (429) or a run for this scout is already in progress (409). A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.+ * @summary Run a scout now+ */+export const SignalsScoutConfigRunParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this Signal scout config.'),+ 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/."+ ),+})+/*** Materialize the scout fleet for this project on demand (idempotent): seed the canonical `signals-scout-*` skills, create a default-schedule config for any scout lacking one, and return all scout configs. Normally the Temporal coordinator does this on its next tick; this action exists so setup flows (e.g. the wizard's self-driving program) can hand the user a tunable fleet immediately.* @summary Sync scout configsdiff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex ed4f7d48edd0..1475ec208718 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -20,6 +20,7 @@ import {SignalsReportsStateCreateParams,SignalsScoutConfigCreateBody,SignalsScoutConfigDestroyParams,+ SignalsScoutConfigRunParams,SignalsScoutConfigUpdateBody,SignalsScoutConfigUpdateParams,SignalsScoutEditReportBody,@@ -777,6 +778,21 @@ const signalsScoutProjectProfileGet = (): ToolBase<},})+const SignalsScoutRunNowSchema = SignalsScoutConfigRunParams.omit({ project_id: true })++const signalsScoutRunNow = (): ToolBase<typeof SignalsScoutRunNowSchema, unknown> => ({+ name: 'signals-scout-run-now',+ schema: SignalsScoutRunNowSchema,+ handler: async (context: Context, params: z.infer<typeof SignalsScoutRunNowSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<unknown>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/${encodeURIComponent(String(params.id))}/run/`,+ })+ return result+ },+})+const SignalsScoutRunsEmissionReportsSchema = SignalsScoutRunsEmissionReportsParams.omit({ project_id: true })const signalsScoutRunsEmissionReports = (): ToolBase<@@ -983,6 +999,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'signals-scout-emit-signal': signalsScoutEmitSignal,'signals-scout-members-list': signalsScoutMembersList,'signals-scout-project-profile-get': signalsScoutProjectProfileGet,+ 'signals-scout-run-now': signalsScoutRunNow,'signals-scout-runs-emission-reports': signalsScoutRunsEmissionReports,'signals-scout-runs-emissions-list': signalsScoutRunsEmissionsList,'signals-scout-runs-list': signalsScoutRunsList,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-run-now.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-run-now.jsonnew file mode 100644index 000000000000..e961e7ade226--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-run-now.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this Signal scout config.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}