: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): persist scout emissions as queryable per-run records (#62354)
Andrew Maguire009a0b4e9650
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 929028a6cb8c..36e61f448501 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -209,6 +209,7 @@ rules:|SignalSourceConfig|SignalScoutConfig|SignalScoutRun+ |SignalScoutEmission|SignalScratchpad|SignalProjectProfile|SingleSessionSummary@@ -447,6 +448,7 @@ rules:|SignalSourceConfig|SignalScoutConfig|SignalScoutRun+ |SignalScoutEmission|SignalScratchpad|SignalProjectProfile|SingleSessionSummarydiff --git a/products/signals/backend/migrations/0034_signalscoutemission.py b/products/signals/backend/migrations/0034_signalscoutemission.pynew file mode 100644index 000000000000..2525aea8d9ea--- /dev/null+++ b/products/signals/backend/migrations/0034_signalscoutemission.py@@ -0,0 +1,68 @@+# Generated by Django 5.2.14 on 2026-06-09 09:51++import django.db.models.manager+import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1216_migrate_cohorts_models"),+ ("signals", "0033_signalscoutrun_emitted_count_and_more"),+ ]++ operations = [+ migrations.CreateModel(+ name="SignalScoutEmission",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("finding_id", models.CharField(max_length=200)),+ ("description", models.TextField()),+ ("weight", models.FloatField()),+ ("confidence", models.FloatField()),+ ("severity", models.CharField(blank=True, max_length=20, null=True)),+ ("source_id", models.CharField(max_length=200)),+ ("emitted_at", models.DateTimeField(auto_now_add=True)),+ (+ "scout_run",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="emissions",+ to="signals.signalscoutrun",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="signal_scout_emissions",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "verbose_name": "Signal scout emission",+ "verbose_name_plural": "Signal scout emissions",+ "default_manager_name": "all_teams",+ "indexes": [+ models.Index(+ fields=["team", "scout_run"],+ name="signal_scout_emission_run_idx",+ )+ ],+ },+ managers=[+ ("all_teams", django.db.models.manager.Manager()),+ ],+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex 30a023988d7e..9c2fc26ec2c1 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0033_signalscoutrun_emitted_count_and_more+0034_signalscoutemissiondiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex d77275373ce3..8da54109e151 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -543,6 +543,64 @@ class SignalScoutRun(TeamScopedRootMixin, UUIDModel):]+class SignalScoutEmission(TeamScopedRootMixin, UUIDModel):+ """One persisted row per finding a scout run emitted to the inbox.++ The durable, queryable record of *what* a scout surfaced — written at emit time by+ `emit_finding`, in the same transaction as the run's `emitted_count` tally bump. It lets a+ team (and its MCP agents) read a run's findings directly via API/MCP without scanning the+ ClickHouse signal store or parsing `source_id`. It complements, not replaces, that store:+ ClickHouse is keyed for embedding/grouping, lags emit by the fire-and-forget Temporal+ pipeline, and can drop under buffer backpressure — this row reflects the emit+ deterministically at the moment it fired.++ Parallel to `SignalScoutRun.emitted_finding_ids` (one row per emit, in emit order) and, like+ that tally, NOT an idempotency barrier: re-emitting the same `finding_id` writes a second+ row, mirroring the second signal it produces downstream.+ """++ # See SignalScoutConfig.all_teams for rationale: emit can run with no team scope set+ # (Temporal activity), so the write path needs the unscoped manager.+ all_teams = models.Manager() # noqa: DJ012++ # Denormalised tenant boundary, matching `SignalScoutRun`. Canonical via `scout_run.team`,+ # kept on this row so the `TeamScopedRootMixin` fail-closed manager has a column to filter on.+ team = models.ForeignKey(+ "posthog.Team",+ on_delete=models.CASCADE,+ related_name="signal_scout_emissions",+ )+ # CASCADE: an emission is meaningless without its run; purging the run (or the TaskRun it+ # bridges, via that row's own CASCADE) takes the per-finding rows with it.+ scout_run = models.ForeignKey(+ SignalScoutRun,+ on_delete=models.CASCADE,+ related_name="emissions",+ )+ # Stable finding id the agent emitted under — baked into `source_id` below and present in the+ # run's `emitted_finding_ids`.+ finding_id = models.CharField(max_length=200)+ # The emitted signal's `description` (the finding prose surfaced to the inbox). Bounded+ # upstream by `MAX_FINDING_DESCRIPTION_LENGTH` on the emit serializer and the emit_signal+ # token cap, so it stays well clear of row-size concerns.+ description = models.TextField()+ weight = models.FloatField()+ confidence = models.FloatField()+ severity = models.CharField(max_length=20, null=True, blank=True)+ # Deterministic `run:<run_id>:finding:<finding_id>` — the join key back into the signal store+ # for the full embedding/grouping view of this finding.+ source_id = models.CharField(max_length=200)+ emitted_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ verbose_name = "Signal scout emission"+ verbose_name_plural = "Signal scout emissions"+ default_manager_name = "all_teams"+ indexes = [+ models.Index(fields=["team", "scout_run"], name="signal_scout_emission_run_idx"),+ ]++class SignalScratchpad(TeamScopedRootMixin, UUIDModel):"""Narrow per-team memory surface for the Signals scout fleet — MCP-readable across agents.diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 0bc5658e985b..717290d37843 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -12,7 +12,8 @@ from rest_framework import serializersfrom posthog.schema import Severity-from products.signals.backend.models import SignalScoutConfig+from products.signals.backend.models import SignalScoutConfig, SignalScoutEmission+from products.signals.backend.scout_harness.tools.emit import MAX_FINDING_ID_LENGTHfrom products.signals.backend.scout_harness.tools.scratchpad import MAX_SCRATCHPAD_CONTENT_LENGTH# --- Run history -----------------------------------------------------------@@ -82,6 +83,58 @@ class SignalScoutRunDetailSerializer(SignalScoutRunSummarySerializer):LLMA token-cost join) can land here without bloating the list response."""+class SignalScoutEmissionSerializer(serializers.ModelSerializer):+ """One finding a scout run emitted to the inbox — the persisted, queryable record of+ *what* the run surfaced, returned by `signals-scout-runs-emissions-list`. The emitted text+ lives in `description`; `source_id` is the join key (`run:<run_id>:finding:<finding_id>`)+ back into the underlying signal store."""++ run_id = serializers.CharField(+ source="scout_run_id",+ help_text="UUID of the `SignalScoutRun` that emitted this finding.",+ )+ finding_id = serializers.CharField(+ help_text="Stable id the finding was emitted under; matches an entry in the run's `emitted_finding_ids`.",+ )+ description = serializers.CharField(+ help_text="The emitted finding prose — the signal's `description` as surfaced to the inbox.",+ )+ weight = serializers.FloatField(+ min_value=0.0,+ max_value=1.0,+ help_text="Agent's weight for the signal in [0, 1]. Drives ranking in the inbox.",+ )+ confidence = serializers.FloatField(+ min_value=0.0,+ max_value=1.0,+ help_text="Agent's confidence the finding is real in [0, 1].",+ )+ severity = serializers.ChoiceField(+ choices=[(s.value, s.value) for s in Severity],+ allow_null=True,+ help_text="Optional severity tag — one of P0, P1, P2, P3, P4 — or null if the run didn't set one.",+ )+ source_id = serializers.CharField(+ help_text="Deterministic `run:<run_id>:finding:<finding_id>` — the join key into the underlying signal store.",+ )+ emitted_at = serializers.DateTimeField(help_text="ISO-8601 timestamp the finding was emitted.")++ class Meta:+ model = SignalScoutEmission+ fields = [+ "id",+ "run_id",+ "finding_id",+ "description",+ "weight",+ "confidence",+ "severity",+ "source_id",+ "emitted_at",+ ]+ read_only_fields = fields++class SearchRecentRunsQuerySerializer(serializers.Serializer):"""Query parameters for `search-recent-runs`."""@@ -258,6 +311,7 @@ class EmitFindingRequestSerializer(serializers.Serializer):finding_id = serializers.CharField(required=False,allow_null=True,+ max_length=MAX_FINDING_ID_LENGTH,help_text="Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal.",)diff --git a/products/signals/backend/scout_harness/tools/emit.py b/products/signals/backend/scout_harness/tools/emit.pyindex 75c0d47b6d53..2a03a6f23d16 100644--- a/products/signals/backend/scout_harness/tools/emit.py+++ b/products/signals/backend/scout_harness/tools/emit.py@@ -35,7 +35,7 @@ from django.db import transactionfrom posthog.models import Teamfrom posthog.sync import database_sync_to_async-from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalSourceConfig+from products.signals.backend.models import SignalScoutConfig, SignalScoutEmission, SignalScoutRun, SignalSourceConfiglogger = logging.getLogger(__name__)@@ -47,6 +47,15 @@ SOURCE_TYPE = SignalSourceConfig.SourceType.CROSS_SOURCE_ISSUE.value# circuit breaker.MAX_EVIDENCE_ENTRIES = 20+# Cap on a caller-supplied `finding_id`. The deterministic `source_id` is+# `run:<uuid>:finding:<finding_id>` (~49 fixed chars), and both `finding_id` and `source_id`+# persist in 200-char columns — so an unbounded id would overflow them, fail the emission insert+# inside the (best-effort, exception-swallowing) tally transaction, and silently drop the emission+# *and* the run tally. Rejecting an overlong id at the boundary keeps the write within bounds;+# trimming is not an option here (an id is a join/dedupe key, and truncation could collide). The+# auto-generated id is a 36-char uuid, so this only ever rejects pathological caller input.+MAX_FINDING_ID_LENGTH = 100+class InvalidEmitError(ValueError):"""The agent tried to emit with an invalid shape (empty description, bad weight, etc)."""@@ -103,7 +112,7 @@ async def emit_finding(Same (non-idempotent) emit behavior as `emit_finding_sync`."""_assert_team_owns_run(team, run)- _validate_inputs(description, weight, confidence, evidence)+ _validate_inputs(description, weight, confidence, evidence, finding_id)finding_id = finding_id or _new_finding_id()extra = _build_extra(run_id=str(run.id),@@ -154,7 +163,15 @@ async def emit_finding(weight=weight,extra=extra,)- await database_sync_to_async(_record_emit, thread_sensitive=False)(run_id=run.id, finding_id=finding_id)+ await database_sync_to_async(_record_emit, thread_sensitive=False)(+ run_id=run.id,+ finding_id=finding_id,+ description=description,+ weight=weight,+ confidence=confidence,+ severity=severity,+ source_id=source_id,+ )logger.info("signals_scout.emit: emitted",extra={**attempt_extra, "source_id": source_id},@@ -185,7 +202,7 @@ def emit_finding_sync(from asgiref.sync import async_to_sync_assert_team_owns_run(team, run)- _validate_inputs(description, weight, confidence, evidence)+ _validate_inputs(description, weight, confidence, evidence, finding_id)finding_id = finding_id or _new_finding_id()extra = _build_extra(run_id=str(run.id),@@ -235,7 +252,15 @@ def emit_finding_sync(weight=weight,extra=extra,)- _record_emit(run_id=run.id, finding_id=finding_id)+ _record_emit(+ run_id=run.id,+ finding_id=finding_id,+ description=description,+ weight=weight,+ confidence=confidence,+ severity=severity,+ source_id=source_id,+ )logger.info("signals_scout.emit: emitted",extra={**attempt_extra, "source_id": source_id},@@ -265,6 +290,7 @@ def _validate_inputs(weight: float,confidence: float,evidence: list[EvidenceEntry],+ finding_id: str | None,) -> None:if not description or not description.strip():raise InvalidEmitError("description must not be empty")@@ -274,6 +300,10 @@ def _validate_inputs(raise InvalidEmitError(f"confidence must be in [0.0, 1.0], got {confidence}")if len(evidence) > MAX_EVIDENCE_ENTRIES:raise InvalidEmitError(f"evidence has {len(evidence)} entries, max is {MAX_EVIDENCE_ENTRIES}")+ # Reject before defaulting — a generated id is a safe 36-char uuid; only a caller-supplied+ # id can overflow `source_id` and silently drop the emission + tally (see MAX_FINDING_ID_LENGTH).+ if finding_id is not None and len(finding_id) > MAX_FINDING_ID_LENGTH:+ raise InvalidEmitError(f"finding_id exceeds {MAX_FINDING_ID_LENGTH} chars ({len(finding_id)})")def _build_extra(@@ -320,8 +350,18 @@ def _new_finding_id() -> str:return str(uuid.uuid4())-def _record_emit(*, run_id: Any, finding_id: str) -> None:- """Bump the run's post-success emit tally: append `finding_id` and recount.+def _record_emit(+ *,+ run_id: Any,+ finding_id: str,+ description: str,+ weight: float,+ confidence: float,+ severity: str | None,+ source_id: str,+) -> None:+ """Persist the emit: bump the run's tally (`emitted_finding_ids` + `emitted_count`) and+ write a `SignalScoutEmission` row carrying the finding's content, in one transaction.Best-effort and observability only — not a dedupe barrier (see the module docstring).The emit has already fired by the time this runs, so **any** failure here (row gone,@@ -329,9 +369,10 @@ def _record_emit(*, run_id: Any, finding_id: str) -> None:emit look failed and invite a double-emitting retry. Runs under `select_for_update` sothe read-modify-write on `emitted_finding_ids` is safe even though emits within a singlerun are sequential today, and keeps `emitted_count` exactly `len(emitted_finding_ids)`- so the two never drift. Uses the unscoped `all_teams` manager because the caller already- validated `team`/`run` ownership and emit can run with no team scope set (Temporal- activity)."""+ so the two never drift. The emission row is written in the same atomic block so the tally+ and the per-finding record never diverge — one row per appended `finding_id`. Uses the+ unscoped `all_teams` manager because the caller already validated `team`/`run` ownership+ and emit can run with no team scope set (Temporal activity)."""try:with transaction.atomic():run = SignalScoutRun.all_teams.select_for_update().filter(pk=run_id).first()@@ -342,10 +383,20 @@ def _record_emit(*, run_id: Any, finding_id: str) -> None:run.emitted_finding_ids = finding_idsrun.emitted_count = len(finding_ids)run.save(update_fields=["emitted_finding_ids", "emitted_count"])+ SignalScoutEmission.all_teams.create(+ team_id=run.team_id,+ scout_run=run,+ finding_id=finding_id,+ description=description,+ weight=weight,+ confidence=confidence,+ severity=severity,+ source_id=source_id,+ )except Exception:- # Tally is best-effort; the signal already emitted. Log and move on so the emit- # call returns success rather than a false failure the caller might retry.- logger.exception("signals_scout.emit: failed to record emit tally for run %s", run_id)+ # Tally and emission row are best-effort; the signal already emitted. Log and move on+ # so the emit call returns success rather than a false failure the caller might retry.+ logger.exception("signals_scout.emit: failed to record emit for run %s", run_id)def _log_extra(diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex c42410e193e0..85f0fa948bb1 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -39,7 +39,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.permissions import APIScopePermission-from products.signals.backend.models import SignalProjectProfile, SignalScoutConfig, SignalScoutRun+from products.signals.backend.models import SignalProjectProfile, SignalScoutConfig, SignalScoutEmission, SignalScoutRunfrom products.signals.backend.scout_harness.serializers import (EmitFindingRequestSerializer,EmitFindingResponseSerializer,@@ -53,6 +53,7 @@ from products.signals.backend.scout_harness.serializers import (SearchMemoryQuerySerializer,SearchRecentRunsQuerySerializer,SignalScoutConfigSerializer,+ SignalScoutEmissionSerializer,SignalScoutRunDetailSerializer,SignalScoutRunSummarySerializer,)@@ -66,6 +67,11 @@ from products.signals.backend.scout_harness.tools.scratchpad import (search_scratchpad,)+# Hard cap on the per-run emissions response. Far above any realistic run (a scout emits a+# handful of findings), so it never truncates in practice — it just bounds a pathological+# retry-heavy run rather than leaving the payload unbounded.+MAX_EMISSIONS_PER_RUN = 1000+def _caller_carries_scout_internal_scope(request: Request) -> bool:"""True only when the request authenticates with the sandbox-internal scout scope.@@ -201,6 +207,46 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise exceptions.NotFound()return Response(SignalScoutRunDetailSerializer(detail.as_dict()).data)+ @extend_schema(+ responses={+ 200: OpenApiResponse(+ response=SignalScoutEmissionSerializer(many=True),+ description="Findings this run emitted to the inbox, newest first.",+ ),+ 404: OpenApiResponse(description="Run not found or not visible to this project."),+ },+ summary="List a run's emitted findings",+ description=(+ "Return the findings a `SignalScoutRun` emitted to the inbox, newest first — one row per emit "+ "with its `description` (the finding text as surfaced), `weight`, `confidence`, `severity`, and "+ "the deterministic `source_id` that joins back to the underlying signal. Lets a team and its "+ "agents see *what* a run surfaced without parsing `emitted_finding_ids` or scanning the signal "+ "store. Strictly team-scoped — a run UUID belonging to another team returns 404."+ ),+ operation_id="signals_scout_runs_emissions",+ )+ @action(+ detail=True,+ methods=["get"],+ url_path="emissions",+ required_scopes=["signal_scout:read"],+ pagination_class=None,+ )+ def emissions(self, request: Request, **kwargs) -> Response:+ run_id = _parse_run_id_or_404(kwargs)+ team_id = _canonical_team_id(self)+ # Team-scope the run lookup first so a foreign-team UUID is a clean 404, not an empty list.+ if not SignalScoutRun.objects.filter(id=run_id, team_id=team_id).exists():+ raise exceptions.NotFound()+ # `-id` is the tie-breaker for rows sharing an `emitted_at` (the PK is a time-ordered+ # uuid7, so it sorts consistently with creation order). The hard cap bounds the response:+ # emissions per run are small in practice but nothing in the schema enforces that, so a+ # retry-heavy run shouldn't be able to produce an unbounded payload.+ emissions = SignalScoutEmission.objects.filter(scout_run_id=run_id, team_id=team_id).order_by(+ "-emitted_at", "-id"+ )[:MAX_EMISSIONS_PER_RUN]+ return Response(SignalScoutEmissionSerializer(emissions, many=True).data)+@validated_request(request_serializer=EmitFindingRequestSerializer,responses={diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 2270569a2aec..d348131f230e 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -19,7 +19,13 @@ from posthog.temporal.oauth import (create_oauth_access_token_for_user,)-from products.signals.backend.models import SignalProjectProfile, SignalScoutConfig, SignalScoutRun, SignalScratchpad+from products.signals.backend.models import (+ SignalProjectProfile,+ SignalScoutConfig,+ SignalScoutEmission,+ SignalScoutRun,+ SignalScratchpad,+)from products.signals.backend.scout_harness.tools.profile import compute_project_profilefrom products.tasks.backend.models import Task, TaskRun@@ -181,6 +187,65 @@ class TestScoutHarnessRunsAPI(APIBaseTest):)+def _make_emission(team: Team, run: SignalScoutRun, *, finding_id: str, **overrides) -> SignalScoutEmission:+ defaults: dict = {+ "description": "Checkout 500s post-deploy",+ "weight": 0.7,+ "confidence": 0.85,+ "severity": "P1",+ "source_id": f"run:{run.id}:finding:{finding_id}",+ }+ defaults.update(overrides)+ return SignalScoutEmission.objects.create(team=team, scout_run=run, finding_id=finding_id, **defaults)+++class TestScoutHarnessRunEmissionsAPI(APIBaseTest):+ def _emissions_url(self, run_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/runs/{run_id}/emissions/"++ def test_returns_emissions_for_run_newest_first(self) -> None:+ run = _make_run(self.team, emitted_count=2, emitted_finding_ids=["f-a", "f-b"])+ _make_emission(self.team, run, finding_id="f-a")+ newer = _make_emission(self.team, run, finding_id="f-b")+ response = self.client.get(self._emissions_url(str(run.id)))+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert [row["finding_id"] for row in body] == ["f-b", "f-a"]+ first = body[0]+ assert first["run_id"] == str(run.id)+ assert first["description"] == "Checkout 500s post-deploy"+ assert first["weight"] == 0.7+ assert first["confidence"] == 0.85+ assert first["severity"] == "P1"+ assert first["source_id"] == f"run:{run.id}:finding:{newer.finding_id}"++ def test_emissions_scoped_to_the_requested_run(self) -> None:+ run_a = _make_run(self.team)+ run_b = _make_run(self.team)+ _make_emission(self.team, run_a, finding_id="f-a")+ _make_emission(self.team, run_b, finding_id="f-b")+ response = self.client.get(self._emissions_url(str(run_a.id)))+ assert response.status_code == status.HTTP_200_OK+ assert [row["finding_id"] for row in response.json()] == ["f-a"]++ def test_emissions_empty_for_run_that_emitted_nothing(self) -> None:+ run = _make_run(self.team)+ response = self.client.get(self._emissions_url(str(run.id)))+ assert response.status_code == status.HTTP_200_OK+ assert response.json() == []++ def test_emissions_unknown_run_returns_404(self) -> None:+ response = self.client.get(self._emissions_url("00000000-0000-0000-0000-000000000000"))+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_emissions_other_teams_run_returns_404(self) -> None:+ other = Team.objects.create(organization=self.organization, name="Other")+ run = _make_run(other)+ _make_emission(other, run, finding_id="f-a")+ response = self.client.get(self._emissions_url(str(run.id)))+ assert response.status_code == status.HTTP_404_NOT_FOUND++@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _OIDC_RSA_KEY})class TestScoutHarnessEmitFindingAPI(APIBaseTest):def setUp(self) -> None:diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.pyindex c5aefa750e2c..579046bf38b2 100644--- a/products/signals/backend/test/test_scout_harness_tools.py+++ b/products/signals/backend/test/test_scout_harness_tools.py@@ -14,7 +14,7 @@ from parameterized import parameterizedfrom posthog.models.scoping import team_scopefrom posthog.sync import database_sync_to_async-from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalScratchpad+from products.signals.backend.models import SignalScoutConfig, SignalScoutEmission, SignalScoutRun, SignalScratchpadfrom products.signals.backend.scout_harness.tools import (MAX_EVIDENCE_ENTRIES,EvidenceEntry,@@ -28,6 +28,7 @@ from products.signals.backend.scout_harness.tools import (search_scratchpad,)from products.signals.backend.scout_harness.tools.emit import (+ MAX_FINDING_ID_LENGTH,SOURCE_PRODUCT,SOURCE_TYPE,_build_extra,@@ -345,31 +346,39 @@ class TestValidateEmitInputs:def test_empty_description_raises(self) -> None:with pytest.raises(InvalidEmitError, match="description"):- _validate_inputs("", 0.5, 0.5, [])+ _validate_inputs("", 0.5, 0.5, [], None)def test_whitespace_only_description_raises(self) -> None:with pytest.raises(InvalidEmitError, match="description"):- _validate_inputs(" \n\t", 0.5, 0.5, [])+ _validate_inputs(" \n\t", 0.5, 0.5, [], None)@pytest.mark.parametrize("weight", [-0.1, 1.1, 2.0])def test_weight_out_of_range_raises(self, weight: float) -> None:with pytest.raises(InvalidEmitError, match="weight"):- _validate_inputs("ok", weight, 0.5, [])+ _validate_inputs("ok", weight, 0.5, [], None)@pytest.mark.parametrize("confidence", [-0.1, 1.1])def test_confidence_out_of_range_raises(self, confidence: float) -> None:with pytest.raises(InvalidEmitError, match="confidence"):- _validate_inputs("ok", 0.5, confidence, [])+ _validate_inputs("ok", 0.5, confidence, [], None)def test_too_many_evidence_entries_raises(self) -> None:many = [EvidenceEntry(source_product="logs", summary=f"e{i}") for i in range(MAX_EVIDENCE_ENTRIES + 1)]with pytest.raises(InvalidEmitError, match="evidence"):- _validate_inputs("ok", 0.5, 0.5, many)+ _validate_inputs("ok", 0.5, 0.5, many, None)def test_at_capacity_evidence_passes(self) -> None:many = [EvidenceEntry(source_product="logs", summary=f"e{i}") for i in range(MAX_EVIDENCE_ENTRIES)]# Should not raise.- _validate_inputs("ok", 0.5, 0.5, many)+ _validate_inputs("ok", 0.5, 0.5, many, None)++ def test_overlong_finding_id_raises(self) -> None:+ with pytest.raises(InvalidEmitError, match="finding_id"):+ _validate_inputs("ok", 0.5, 0.5, [], "x" * (MAX_FINDING_ID_LENGTH + 1))++ def test_finding_id_at_capacity_passes(self) -> None:+ # Should not raise — and a generated 36-char uuid is always well under the cap.+ _validate_inputs("ok", 0.5, 0.5, [], "x" * MAX_FINDING_ID_LENGTH)class TestBuildEmitExtra:@@ -721,6 +730,35 @@ async def test_emit_finding_records_tally_on_run(ateam_emit, arun_emit):assert arun_emit.emitted_finding_ids == ["f-one", "f-two"]+async def test_emit_finding_persists_emission_rows(ateam_emit, arun_emit):+ # Each successful emit writes a SignalScoutEmission row carrying the finding's content,+ # so a team can read *what* a run surfaced without scanning the signal store.+ with patch("products.signals.backend.facade.api.emit_signal", new=AsyncMock()):+ await emit_finding(+ team=ateam_emit,+ run=arun_emit,+ description="Checkout 500s post-deploy",+ weight=0.7,+ confidence=0.85,+ evidence=[EvidenceEntry(source_product="error_tracking", summary="500s on /checkout")],+ severity="P1",+ finding_id="f-emit",+ )++ rows = await database_sync_to_async(lambda: list(SignalScoutEmission.all_teams.filter(scout_run=arun_emit)))()+ assert len(rows) == 1+ emission = rows[0]+ assert emission.team_id == ateam_emit.id+ assert emission.finding_id == "f-emit"+ assert emission.description == "Checkout 500s post-deploy"+ assert emission.weight == 0.7+ assert emission.confidence == 0.85+ assert emission.severity == "P1"+ assert emission.source_id == f"run:{arun_emit.id}:finding:f-emit"++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_emit_finding_skip_does_not_record_tally(arun_emit, ateam_emit):diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 6ff83ee02000..971d88c6a84c 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -834,21 +834,6 @@ export interface SignalScoutRunDetailApi {emitted_finding_ids: string[]}-/**- * One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.- */-export interface EvidenceEntryApi {- /** Source the citation came from (`error_tracking`, `session_replay`, `logs`, ...). */- source_product: string- /** One-sentence prose about why this evidence supports the finding. */- summary: string- /**- * Optional ID of the cited entity (issue id, recording id, log query id).- * @nullable- */- entity_id?: string | null-}-/*** * `P0` - P0* `P1` - P1@@ -866,6 +851,61 @@ export const AutonomyPriorityEnumApi = {P4: 'P4',} as const+/**+ * One finding a scout run emitted to the inbox — the persisted, queryable record of+*what* the run surfaced, returned by `signals-scout-runs-emissions-list`. The emitted text+lives in `description`; `source_id` is the join key (`run:<run_id>:finding:<finding_id>`)+back into the underlying signal store.+ */+export interface SignalScoutEmissionApi {+ readonly id: string+ /** UUID of the `SignalScoutRun` that emitted this finding. */+ run_id: string+ /** Stable id the finding was emitted under; matches an entry in the run's `emitted_finding_ids`. */+ finding_id: string+ /** The emitted finding prose — the signal's `description` as surfaced to the inbox. */+ description: string+ /**+ * Agent's weight for the signal in [0, 1]. Drives ranking in the inbox.+ * @minimum 0+ * @maximum 1+ */+ weight: number+ /**+ * Agent's confidence the finding is real in [0, 1].+ * @minimum 0+ * @maximum 1+ */+ confidence: number+ /** Optional severity tag — one of P0, P1, P2, P3, P4 — or null if the run didn't set one.++ * `P0` - P0+ * `P1` - P1+ * `P2` - P2+ * `P3` - P3+ * `P4` - P4 */+ severity: AutonomyPriorityEnumApi | null+ /** Deterministic `run:<run_id>:finding:<finding_id>` — the join key into the underlying signal store. */+ source_id: string+ /** ISO-8601 timestamp the finding was emitted. */+ emitted_at: string+}++/**+ * One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.+ */+export interface EvidenceEntryApi {+ /** Source the citation came from (`error_tracking`, `session_replay`, `logs`, ...). */+ source_product: string+ /** One-sentence prose about why this evidence supports the finding. */+ summary: string+ /**+ * Optional ID of the cited entity (issue id, recording id, log query id).+ * @nullable+ */+ entity_id?: string | null+}+export interface TimeRangeApi {/** ISO-8601 inclusive lower bound for the finding's window. */date_from: string@@ -923,6 +963,7 @@ export interface EmitFindingRequestApi {mcp_trace_id?: string | null/*** Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal.+ * @maxLength 100* @nullable*/finding_id?: string | nulldiff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 03ed5e385c6c..32fca2089707 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -26,6 +26,7 @@ import type {SignalReportApi,SignalReportStateRequestApi,SignalScoutConfigApi,+ SignalScoutEmissionApi,SignalScoutRunDetailApi,SignalScoutRunSummaryApi,SignalSourceConfigApi,@@ -323,6 +324,25 @@ export const signalsScoutRunsRetrieve = async (})}+export const getSignalsScoutRunsEmissionsUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/scout/runs/${id}/emissions/`+}++/**+ * Return the findings a `SignalScoutRun` emitted to the inbox, newest first — one row per emit with its `description` (the finding text as surfaced), `weight`, `confidence`, `severity`, and the deterministic `source_id` that joins back to the underlying signal. Lets a team and its agents see *what* a run surfaced without parsing `emitted_finding_ids` or scanning the signal store. Strictly team-scoped — a run UUID belonging to another team returns 404.+ * @summary List a run's emitted findings+ */+export const signalsScoutRunsEmissions = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<SignalScoutEmissionApi[]> => {+ return apiMutator<SignalScoutEmissionApi[]>(getSignalsScoutRunsEmissionsUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsScoutEmitSignalUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/signals/scout/runs/${id}/emit-signal/`}diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex a52efff1542c..149a0f304445 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -113,6 +113,8 @@ export const signalsScoutEmitSignalBodyConfidenceMax = 1export const signalsScoutEmitSignalBodyEvidenceMax = 20+export const signalsScoutEmitSignalBodyFindingIdMax = 100+export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zod.object({description: zod@@ -179,6 +181,7 @@ export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zodmcp_trace_id: zod.string().nullish().describe('Optional MCP trace id for cross-system debugging.'),finding_id: zod.string()+ .max(signalsScoutEmitSignalBodyFindingIdMax).nullish().describe("Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal."diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex c8d40e219883..3459e9bd5f3f 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -243,6 +243,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-runs-emissions-list:+ operation: signals_scout_runs_emissions+ enabled: true+ scopes:+ - signal_scout:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List a scout run's emitted findings+ description: >+ Return the findings a `SignalScoutRun` emitted to the inbox, newest first — one row per emit with its+ `description` (the finding text as surfaced), `weight`, `confidence`, `severity`, and the deterministic+ `source_id` (`run:<run_id>:finding:<finding_id>`) that joins back to the underlying signal. Use this to see+ *what* a run actually surfaced, not just how many (`emitted_count`) or which ids (`emitted_finding_ids`).+ Strictly team-scoped — a run UUID belonging to another team returns 404.signals-scout-runs-list:operation: signals_scout_runs_listenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex efa19392ebc1..e57117a83785 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5033,6 +5033,20 @@"readOnlyHint": true}},+ "signals-scout-runs-emissions-list": {+ "description": "Return the findings a `SignalScoutRun` emitted to the inbox, newest first — one row per emit with its `description` (the finding text as surfaced), `weight`, `confidence`, `severity`, and the deterministic `source_id` (`run:<run_id>:finding:<finding_id>`) that joins back to the underlying signal. Use this to see *what* a run actually surfaced, not just how many (`emitted_count`) or which ids (`emitted_finding_ids`). Strictly team-scoped — a run UUID belonging to another team returns 404.",+ "category": "Signals",+ "feature": "signals",+ "summary": "List a scout run's emitted findings",+ "title": "List a scout run's emitted findings",+ "required_scopes": ["signal_scout:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"signals-scout-runs-list": {"description": "Return the most recent `SignalScoutRun` summaries for this project, newest first. Used by the headless scout to dedupe against work other runs already covered. Each row carries `emitted_count` (how many findings the run surfaced to the inbox) and `emitted_finding_ids`. Pass `emitted=true` to return only runs that emitted at least one finding (or `emitted=false` for runs that surfaced nothing). Pass `text` for a case-insensitive substring match on the run's `summary` (the primary dedupe key for runs that didn't emit findings). Pass `date_from` / `date_to` (ISO-8601, inclusive lower / exclusive upper bound on `created_at`) to scope to a window. Results capped at 100.","category": "Signals",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 12708237a662..1fe126c5060d 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5374,6 +5374,20 @@"readOnlyHint": true}},+ "signals-scout-runs-emissions-list": {+ "description": "Return the findings a `SignalScoutRun` emitted to the inbox, newest first — one row per emit with its `description` (the finding text as surfaced), `weight`, `confidence`, `severity`, and the deterministic `source_id` (`run:<run_id>:finding:<finding_id>`) that joins back to the underlying signal. Use this to see *what* a run actually surfaced, not just how many (`emitted_count`) or which ids (`emitted_finding_ids`). Strictly team-scoped — a run UUID belonging to another team returns 404.",+ "category": "Signals",+ "feature": "signals",+ "summary": "List a scout run's emitted findings",+ "title": "List a scout run's emitted findings",+ "required_scopes": ["signal_scout:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"signals-scout-runs-list": {"description": "Return the most recent `SignalScoutRun` summaries for this project, newest first. Used by the headless scout to dedupe against work other runs already covered. Each row carries `emitted_count` (how many findings the run surfaced to the inbox) and `emitted_finding_ids`. Pass `emitted=true` to return only runs that emitted at least one finding (or `emitted=false` for runs that surfaced nothing). Pass `text` for a case-insensitive substring match on the run's `summary` (the primary dedupe key for runs that didn't emit findings). Pass `date_from` / `date_to` (ISO-8601, inclusive lower / exclusive upper bound on `created_at`) to scope to a window. Results capped at 100.","category": "Signals",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ac8590315ed4..869b4fd7d248 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14436,6 +14436,7 @@ export namespace Schemas {mcp_trace_id?: string | null;/*** Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal.+ * @maxLength 100* @nullable*/finding_id?: string | null;@@ -38889,6 +38890,46 @@ export namespace Schemas {readonly created_at: string;}+ /**+ * One finding a scout run emitted to the inbox — the persisted, queryable record of+ *what* the run surfaced, returned by `signals-scout-runs-emissions-list`. The emitted text+ lives in `description`; `source_id` is the join key (`run:<run_id>:finding:<finding_id>`)+ back into the underlying signal store.+ */+ export interface SignalScoutEmission {+ readonly id: string;+ /** UUID of the `SignalScoutRun` that emitted this finding. */+ run_id: string;+ /** Stable id the finding was emitted under; matches an entry in the run's `emitted_finding_ids`. */+ finding_id: string;+ /** The emitted finding prose — the signal's `description` as surfaced to the inbox. */+ description: string;+ /**+ * Agent's weight for the signal in [0, 1]. Drives ranking in the inbox.+ * @minimum 0+ * @maximum 1+ */+ weight: number;+ /**+ * Agent's confidence the finding is real in [0, 1].+ * @minimum 0+ * @maximum 1+ */+ confidence: number;+ /** Optional severity tag — one of P0, P1, P2, P3, P4 — or null if the run didn't set one.++ * `P0` - P0+ * `P1` - P1+ * `P2` - P2+ * `P3` - P3+ * `P4` - P4 */+ severity: AutonomyPriorityEnum | null;+ /** Deterministic `run:<run_id>:finding:<finding_id>` — the join key into the underlying signal store. */+ source_id: string;+ /** ISO-8601 timestamp the finding was emitted. */+ emitted_at: string;+ }+/*** Full `SignalScoutRun` projection used by `get-run`. Same shape as the summarytoday; 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 685671f6fa4c..8519457ca06f 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 17 enabled ops+ * PostHog API - MCP 18 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -252,6 +252,19 @@ export const SignalsScoutRunsRetrieveParams = /* @__PURE__ */ zod.object({),})+/**+ * Return the findings a `SignalScoutRun` emitted to the inbox, newest first — one row per emit with its `description` (the finding text as surfaced), `weight`, `confidence`, `severity`, and the deterministic `source_id` that joins back to the underlying signal. Lets a team and its agents see *what* a run surfaced without parsing `emitted_finding_ids` or scanning the signal store. Strictly team-scoped — a run UUID belonging to another team returns 404.+ * @summary List a run's emitted findings+ */+export const SignalsScoutRunsEmissionsParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this Signal scout run.'),+ 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/."+ ),+})+/*** Fire `emit_signal` with `source_product = signals_scout`. The `finding_id` is baked into the deterministic `Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call with the same `finding_id` emits a second signal, so do not retry an emit that may have already succeeded.* @summary Emit a finding for a run@@ -275,6 +288,8 @@ export const signalsScoutEmitSignalBodyConfidenceMax = 1export const signalsScoutEmitSignalBodyEvidenceMax = 20+export const signalsScoutEmitSignalBodyFindingIdMax = 100+export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zod.object({description: zod@@ -341,6 +356,7 @@ export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zodmcp_trace_id: zod.string().nullish().describe('Optional MCP trace id for cross-system debugging.'),finding_id: zod.string()+ .max(signalsScoutEmitSignalBodyFindingIdMax).nullish().describe("Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal."diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex 23d301dc5382..85d3c6c8789b 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -12,6 +12,7 @@ import {SignalsScoutEmitSignalBody,SignalsScoutEmitSignalParams,SignalsScoutProjectProfileGetQueryParams,+ SignalsScoutRunsEmissionsParams,SignalsScoutRunsListQueryParams,SignalsScoutRunsRetrieveParams,SignalsScoutScratchpadForgetBody,@@ -400,6 +401,24 @@ const signalsScoutProjectProfileGet = (): ToolBase<},})+const SignalsScoutRunsEmissionsListSchema = SignalsScoutRunsEmissionsParams.omit({ project_id: true })++const signalsScoutRunsEmissionsList = (): ToolBase<+ typeof SignalsScoutRunsEmissionsListSchema,+ WithPostHogUrl<Schemas.SignalScoutEmission[]>+> => ({+ name: 'signals-scout-runs-emissions-list',+ schema: SignalsScoutRunsEmissionsListSchema,+ handler: async (context: Context, params: z.infer<typeof SignalsScoutRunsEmissionsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SignalScoutEmission[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.id))}/emissions/`,+ })+ return await withPostHogUrl(context, result, '/inbox')+ },+})+const SignalsScoutRunsListSchema = SignalsScoutRunsListQueryParamsconst signalsScoutRunsList = (): ToolBase<@@ -527,6 +546,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'signals-scout-config-update': signalsScoutConfigUpdate,'signals-scout-emit-signal': signalsScoutEmitSignal,'signals-scout-project-profile-get': signalsScoutProjectProfileGet,+ 'signals-scout-runs-emissions-list': signalsScoutRunsEmissionsList,'signals-scout-runs-list': signalsScoutRunsList,'signals-scout-runs-retrieve': signalsScoutRunsRetrieve,'signals-scout-scratchpad-forget': signalsScoutScratchpadForget,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-emit-signal.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-emit-signal.jsonindex 3cbff0731c88..aedbf1ffbac9 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-emit-signal.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-emit-signal.json@@ -53,6 +53,7 @@"finding_id": {"anyOf": [{+ "maxLength": 100,"type": "string"},{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-runs-emissions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-runs-emissions-list.jsonnew file mode 100644index 000000000000..6bf8266d32be--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-runs-emissions-list.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this Signal scout run.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}