Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): classify scout report lifecycle events by report kind (#70224)

Andrew Maguire44a25c8d1016
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index dc0620c36cb6..eaa7e4f054bd 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -177,6 +177,14 @@ one sandbox session → zero or more emitted signals.
`_self_heal_stale_runs`). They join on `run_id`/`task_run_id` and are the event-derived
(no-warehouse-lag) basis for throughput, stall, and worker-death alerting — a `started`
with no `finished` is a run that died before finalize; a reaped run emits no `finished`.
+ The report channel adds `signals_scout_report_emitted` / `signals_scout_report_edited`
+ (plus customer-facing `$scout_report_*` copies), stamped with derived classification
+ properties (`report_kind` = `finding`/`self_improvement`, `is_self_improvement_report`)
+ via `_report_classification_props` in `tools/report.py` — classified server-side off the
+ prompt's mandated title prefix (`prompt.SELF_IMPROVEMENT_REPORT_TITLE_PREFIX`), so
+ self-improvement reports are separable without downstream title heuristics. That helper
+ is the single extension point for future derived telemetry dimensions on these events —
+ add new flags there (both events pick them up), not as model columns.
- Emit happens via the harness's `emit_signal_*` tools, which call `emit_signal()`
with `source_product="signals_scout"` and `source_type="cross_source_issue"`.
From there the signal flows through the same emitter → buffer → grouping v2 path
diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.py
index 0be5983fe25b..82c84244bfd2 100644
--- a/products/signals/backend/scout_harness/prompt.py
+++ b/products/signals/backend/scout_harness/prompt.py
@@ -246,13 +246,19 @@ This scout's skill was authored by your team, and you are the only one who sees
- Write a scratchpad entry keyed `improve:<your-skill-name>:<topic>` — use your skill name from *Your run identity*, not a bare domain: scratchpad keys are shared team-wide, and a domain-only key would let two scouts overwrite each other's suggestions. Stable key, no dates — same rules as your other keys. In the content: the specific skill change you'd suggest, the evidence from this run, and a dated observed line. Hit the same issue on a later run? Rewrite the same key with a fresh dated line appended — recurrence across runs is the strongest review signal the owner gets."""
+# The exact title prefix the escalation guidance below mandates for scout self-improvement reports.
+# The report-channel telemetry (`tools/report.py` `_report_classification_props`) classifies emitted /
+# edited reports off this prefix, so the prompt wording and the event classification share one
+# definition and can't silently drift apart.
+SELF_IMPROVEMENT_REPORT_TITLE_PREFIX = "Scout self-improvement:"
+
# Report-channel custom scouts additionally escalate strong suggestions to the inbox with the report
# tools they already hold. Two variants because an emit-only scout must never be pointed at
# `edit_report` (the endpoint fails closed on the exact tool); a signal-channel custom scout gets
# neither — it has no report tools at all, so the scratchpad stays its only self-improvement record.
-_SELF_IMPROVEMENT_ESCALATE_BOTH = """- **Recurring or material? File an inbox report too.** A scratchpad entry is only seen when the owner goes looking; a report is routed to them. When a suggestion re-confirms across runs (your `improve:` entry has accumulated several dated lines), or this run's failure was material (it wasted most of your budget, or steered you into emitting something wrong), surface it with the same report tools you use for findings. If the `improve:` entry already carries a `report_id`, `append_note` the fresh evidence onto that report with `signals-scout-edit-report`; otherwise author one with `signals-scout-emit-report` — title `Scout self-improvement: <your-skill-name> – <topic>`, the suggested skill change plus the evidence in the summary, `actionability` = `requires_human_input` (applying it is a skill edit by your team), `repository` = the `NO_REPO` sentinel (the fix is a skill edit, not code), `suggested_reviewers` = whoever owns this scout when you know — and stash the returned `report_id` in the `improve:` entry so later runs update that report instead of authoring a duplicate. It lands in the inbox like any other report; your team decides whether to apply it."""
+_SELF_IMPROVEMENT_ESCALATE_BOTH = f"""- **Recurring or material? File an inbox report too.** A scratchpad entry is only seen when the owner goes looking; a report is routed to them. When a suggestion re-confirms across runs (your `improve:` entry has accumulated several dated lines), or this run's failure was material (it wasted most of your budget, or steered you into emitting something wrong), surface it with the same report tools you use for findings. If the `improve:` entry already carries a `report_id`, `append_note` the fresh evidence onto that report with `signals-scout-edit-report`; otherwise author one with `signals-scout-emit-report` — title `{SELF_IMPROVEMENT_REPORT_TITLE_PREFIX} <your-skill-name> – <topic>`, the suggested skill change plus the evidence in the summary, `actionability` = `requires_human_input` (applying it is a skill edit by your team), `repository` = the `NO_REPO` sentinel (the fix is a skill edit, not code), `suggested_reviewers` = whoever owns this scout when you know — and stash the returned `report_id` in the `improve:` entry so later runs update that report instead of authoring a duplicate. It lands in the inbox like any other report; your team decides whether to apply it."""
-_SELF_IMPROVEMENT_ESCALATE_EMIT_ONLY = """- **Recurring or material? File an inbox report too.** A scratchpad entry is only seen when the owner goes looking; a report is routed to them. When a suggestion re-confirms across runs (your `improve:` entry has accumulated several dated lines), or this run's failure was material (it wasted most of your budget, or steered you into emitting something wrong), surface it with `signals-scout-emit-report` — title `Scout self-improvement: <your-skill-name> – <topic>`, the suggested skill change plus the evidence in the summary, `actionability` = `requires_human_input` (applying it is a skill edit by your team), `repository` = the `NO_REPO` sentinel (the fix is a skill edit, not code), `suggested_reviewers` = whoever owns this scout when you know. Stash the returned `report_id` in the `improve:` entry — this run can't edit reports, so once the entry carries a `report_id` the report exists: keep fresh evidence in the entry rather than authoring a duplicate. It lands in the inbox like any other report; your team decides whether to apply it."""
+_SELF_IMPROVEMENT_ESCALATE_EMIT_ONLY = f"""- **Recurring or material? File an inbox report too.** A scratchpad entry is only seen when the owner goes looking; a report is routed to them. When a suggestion re-confirms across runs (your `improve:` entry has accumulated several dated lines), or this run's failure was material (it wasted most of your budget, or steered you into emitting something wrong), surface it with `signals-scout-emit-report` — title `{SELF_IMPROVEMENT_REPORT_TITLE_PREFIX} <your-skill-name> – <topic>`, the suggested skill change plus the evidence in the summary, `actionability` = `requires_human_input` (applying it is a skill edit by your team), `repository` = the `NO_REPO` sentinel (the fix is a skill edit, not code), `suggested_reviewers` = whoever owns this scout when you know. Stash the returned `report_id` in the `improve:` entry — this run can't edit reports, so once the entry carries a `report_id` the report exists: keep fresh evidence in the entry rather than authoring a duplicate. It lands in the inbox like any other report; your team decides whether to apply it."""
_SELF_IMPROVEMENT_TAIL = """- The bar is a concrete failure or waste observed this run. Generic polish ("the wording could be clearer") is noise — don't write it.
- Routing: a problem with the tools, the harness, or these shared instructions still goes to `agent-feedback` (it reaches the PostHog team, not your team). An `improve:` entry is only for changes to your own skill body — your team reviews it and decides whether to apply it.
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index 5870eb048b9b..d517dc9afe12 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -18,6 +18,7 @@ that may have succeeded.
from __future__ import annotations
+import re
import uuid
import asyncio
import logging
@@ -45,6 +46,7 @@ from products.signals.backend.artefact_schemas import (
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalScoutRun
from products.signals.backend.report_generation.resolve_reviewers import get_org_member_github_logins_by_user_uuid
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
+from products.signals.backend.scout_harness.prompt import SELF_IMPROVEMENT_REPORT_TITLE_PREFIX
from products.signals.backend.scout_harness.tools.emit import (
SCOUT_SIGNAL_WEIGHT,
# Shared harness gates/attribution — the report channel applies the same preflight as emit.
@@ -59,6 +61,7 @@ from products.signals.backend.scout_report import (
ScoutReportSignal,
append_report_note,
create_scout_report,
+ get_scout_report_title,
record_report_edit,
set_scout_report_reviewers,
update_scout_report,
@@ -131,6 +134,10 @@ class EditReportResult:
updated_fields: list[str]
note_appended: bool
reviewers_set: bool = False
+ # The report's effective title after the edit (the rewritten title, or the stored one for a
+ # note/reviewer-only edit) — telemetry-only, so the edited lifecycle event can classify the report
+ # (`_report_classification_props`) even when the edit didn't touch the title.
+ report_title: str | None = None
def _surfaced(status: SignalReport.Status) -> bool:
@@ -404,6 +411,35 @@ def _clip(value: str | None, limit: int) -> str | None:
return value[:limit] if value is not None else None
+# Values of the `report_kind` classification property on the report-channel lifecycle events.
+REPORT_KIND_SELF_IMPROVEMENT = "self_improvement"
+REPORT_KIND_FINDING = "finding"
+
+# Tolerant matcher for `SELF_IMPROVEMENT_REPORT_TITLE_PREFIX` ("Scout self-improvement:"): anchored at
+# the start of the title, but forgiving of the case, spacing, and hyphen drift LLM-authored titles show
+# ("scout self improvement :", " Scout Self-Improvement:"). A missed match silently undercounts the
+# self-improvement funnel, so lenient-but-anchored beats exact. Keep in sync with the prompt constant.
+_SELF_IMPROVEMENT_TITLE_RE = re.compile(r"^\s*scout\s+self[\s-]?improvement\s*:", re.IGNORECASE)
+# Import-time guard: if the prompt's mandated prefix ever changes shape, classification must be
+# updated with it — fail loudly here rather than silently undercounting.
+assert _SELF_IMPROVEMENT_TITLE_RE.match(SELF_IMPROVEMENT_REPORT_TITLE_PREFIX)
+
+
+def _report_classification_props(effective_title: str | None) -> dict[str, Any]:
+ """Derived classification dimensions stamped on both report-channel lifecycle events (and their
+ customer-facing copies): `report_kind` (enum, breakdown-friendly) + `is_self_improvement_report`
+ (bool, filter-friendly). Classified server-side off the title contract the prompt mandates
+ (`SELF_IMPROVEMENT_REPORT_TITLE_PREFIX`, matched leniently via `_SELF_IMPROVEMENT_TITLE_RE`) rather
+ than scout-declared, so the flag can't be omitted by the model and needs no tool-schema change.
+ This helper is the single extension point for future derived telemetry dimensions — add them here
+ so the emit and edit events never drift apart."""
+ is_self_improvement = _SELF_IMPROVEMENT_TITLE_RE.match(effective_title or "") is not None
+ return {
+ "report_kind": REPORT_KIND_SELF_IMPROVEMENT if is_self_improvement else REPORT_KIND_FINDING,
+ "is_self_improvement_report": is_self_improvement,
+ }
+
+
def _report_event_base(run: SignalScoutRun) -> dict[str, Any]:
"""Shared dimensions for the report-channel lifecycle events, mirroring the `signals_scout_run_*`
events so the two join on `run_id` / `task_run_id` — a report event sits under the run that authored
@@ -523,7 +559,9 @@ def _capture_report_emitted(
carries the report's content (`title` / `summary` / `actionability` / `priority` / `repository` /
`safety_explanation`) — parity with the signal channel's `signal_emitted`, so internal consumers
(dashboards, alerts, CDP forwards) can act on a report's substance, not just its ids. Content rides
- every outcome, including `gate_skipped` (it records what would have been authored). Keyed on the team
+ every outcome, including `gate_skipped` (it records what would have been authored). Also stamped
+ with the derived classification dimensions (`_report_classification_props`) so e.g. self-improvement
+ reports are separable from findings without title heuristics downstream. Keyed on the team
and carrying the run / task ids so it joins to the run lifecycle events. Best-effort: a capture failure
must never fail or mask the emit. Accesses `team.organization` — call on a sync thread.
@@ -538,6 +576,7 @@ def _capture_report_emitted(
outcome = "suppressed"
properties = {
**_report_event_base(run),
+ **_report_classification_props(title),
"report_id": result.report_id,
"status": result.status,
"outcome": outcome,
@@ -589,10 +628,13 @@ def _capture_report_edited(
`note_appended` / `reviewers_set` distinguish a title/summary rewrite from a note-only append from a
reviewer (re-routing) change; `title` / `summary` / `note` carry the content the edit applied (each None
when that field wasn't touched) — parity with the emit event so a consumer sees *what* changed, not just
- that something did. Best-effort; never fails the edit. Accesses `team.organization` — call on a sync
+ that something did. Classification (`_report_classification_props`) reads `result.report_title` — the
+ report's effective title after the edit — so a note-only append to a self-improvement report still
+ classifies correctly. Best-effort; never fails the edit. Accesses `team.organization` — call on a sync
thread. Returns the customer-facing fan-out payload for the caller to forward."""
properties = {
**_report_event_base(run),
+ **_report_classification_props(result.report_title),
"report_id": result.report_id,
"updated_fields": result.updated_fields,
"note_appended": result.note_appended,
@@ -906,8 +948,26 @@ def _do_edit_report(
"reviewers_set": reviewers_set,
},
)
+ # Resolve the report's effective title for the edited event's classification — the rewritten title
+ # when this edit set one, else the stored title (one indexed read; the edits above already proved
+ # the report exists for this team). Telemetry-only and best-effort: the edit has already committed,
+ # so a transient read failure here must not fail the call (or skip the tally below) — degrade to an
+ # unclassified event instead.
+ report_title: str | None = title
+ if report_title is None:
+ try:
+ report_title = get_scout_report_title(team_id=team.id, report_id=report_id)
+ except Exception:
+ logger.warning(
+ "signals_scout.edit_report: failed to resolve report title for telemetry",
+ extra={"team_id": team.id, "report_id": report_id},
+ )
result = EditReportResult(
- report_id=report_id, updated_fields=updated_fields, note_appended=note_appended, reviewers_set=reviewers_set
+ report_id=report_id,
+ updated_fields=updated_fields,
+ note_appended=note_appended,
+ reviewers_set=reviewers_set,
+ report_title=report_title,
)
# Record the edit on the run tally only when something actually changed — a no-op edit (e.g. a
# title rewrite to its current value) must not claim the run touched the report.
diff --git a/products/signals/backend/scout_report/__init__.py b/products/signals/backend/scout_report/__init__.py
index 33b80149b0e3..c7332ef3728a 100644
--- a/products/signals/backend/scout_report/__init__.py
+++ b/products/signals/backend/scout_report/__init__.py
@@ -13,6 +13,7 @@ from products.signals.backend.scout_report.persistence import (
ScoutReportSignal,
append_report_note,
create_scout_report,
+ get_scout_report_title,
record_report_edit,
set_scout_report_reviewers,
soft_delete_scout_signal,
@@ -26,6 +27,7 @@ __all__ = [
"ScoutReportSignal",
"append_report_note",
"create_scout_report",
+ "get_scout_report_title",
"record_report_edit",
"set_scout_report_reviewers",
"soft_delete_scout_signal",
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index 70abbb9baf37..656e748d6293 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -229,6 +229,14 @@ def create_scout_report(
)
+def get_scout_report_title(*, team_id: int, report_id: str) -> str | None:
+ """Team-scoped title lookup, for the edit-path event telemetry: an edit that doesn't rewrite the
+ title still needs the report's effective title to classify the lifecycle event (self-improvement
+ vs finding). Returns None when the report doesn't exist for the team — telemetry is best-effort,
+ so this never raises."""
+ return SignalReport.objects.filter(team_id=team_id, id=report_id).values_list("title", flat=True).first()
+
+
def update_scout_report(
*,
team_id: int,
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index 5cbbbf46ab70..f4962fd6174a 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -5,6 +5,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, patch
from django.apps import apps
+from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
@@ -16,11 +17,14 @@ from posthog.models.organization import OrganizationMembership
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalSourceConfig
from products.signals.backend.scout_harness.tools.report import (
MAX_SUGGESTED_REVIEWERS,
+ REPORT_KIND_FINDING,
+ REPORT_KIND_SELF_IMPROVEMENT,
EditReportResult,
InvalidScoutReportError,
ReviewerInput,
_build_suggested_reviewers,
_capture_report_edited,
+ _report_classification_props,
)
from products.signals.backend.temporal.report_safety_judge import SafetyJudgeResponse
from products.signals.backend.test.test_scout_harness_api import _authenticate_as_scout, _make_run
@@ -329,6 +333,9 @@ class TestScoutReportAPI(APIBaseTest):
assert props["title"] == "Checkout p99 regressed after 4.2"
assert props["summary"] == "The /checkout endpoint p99 doubled after the 4.2 deploy."
assert props["actionability"] == "immediately_actionable"
+ # A regular finding classifies as such (the self-improvement path has its own test below).
+ assert props["report_kind"] == REPORT_KIND_FINDING
+ assert props["is_self_improvement_report"] is False
# The customer-facing copy must land in the team's *own* project (their token), never create a
# person (it's the scout's output, not a user action), and carry a report deep link when a report
# exists — that link is what a CDP Slack destination templates the message from.
@@ -361,6 +368,7 @@ class TestScoutReportAPI(APIBaseTest):
assert props["title"] == "new title"
assert props["note"] == "re-validated"
assert props["summary"] is None
+ assert props["is_self_improvement_report"] is False
# The edit also fans out to the team's own project, deep-linking the edited report.
forward = next(
c for c in self.capture_internal_mock.call_args_list if c.kwargs["event_name"] == "$scout_report_edited"
@@ -369,6 +377,25 @@ class TestScoutReportAPI(APIBaseTest):
assert forward.kwargs["process_person_profile"] is False
assert forward.kwargs["properties"]["report_url"].endswith(f"/inbox/reports/{created['report_id']}")
+ def test_self_improvement_report_classified_on_emit_and_edit(self) -> None:
+ # Classification must ride both lifecycle events: stamped from the authored title on emit, and
+ # resolved from the *stored* report title on a note-only edit (the payload carries no title) —
+ # the path that breaks if `_do_edit_report` stops resolving the report's effective title.
+ run = _make_run(self.team)
+ title = "Scout self-improvement: signals-scout-general – dead quick-close trigger"
+ with _safe_judge(), patch(EMBED_PATH), patch(CAPTURE_PATH) as capture:
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(title=title), format="json")
+ self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": created.json()["report_id"], "append_note": "re-confirmed on this run"},
+ format="json",
+ )
+ emitted = next(c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_report_emitted")
+ edited = next(c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_report_edited")
+ for props in (emitted.kwargs["properties"], edited.kwargs["properties"]):
+ assert props["report_kind"] == REPORT_KIND_SELF_IMPROVEMENT
+ assert props["is_self_improvement_report"] is True
+
def test_reviewer_edit_event_uuid_keys_on_reviewers(self) -> None:
# A reviewer-only edit carries no `updated_fields` and no title/summary/note, so two distinct
# reviewer corrections to the same report in one run would hash to one `event_uuid` and ingestion
@@ -515,3 +542,24 @@ class TestBuildSuggestedReviewers(APIBaseTest):
with patch(resolver) as resolve_mock, pytest.raises(InvalidScoutReportError):
_build_suggested_reviewers(self.team.id, entries)
resolve_mock.assert_not_called()
+
+
+class TestReportClassificationProps(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("exact_prefix", "Scout self-improvement: my-scout – dead trigger", True),
+ # LLM-authored titles drift in case/whitespace; the classifier must tolerate that.
+ ("case_and_whitespace_drift", " scout SELF-improvement: my-scout – topic", True),
+ ("space_before_colon", "Scout self-improvement : my-scout – topic", True),
+ ("hyphen_dropped", "Scout self improvement: my-scout – topic", True),
+ ("finding_title", "Checkout p99 regressed after 4.2", False),
+ # The phrase mid-title (e.g. a finding *about* the escalation flow) is not a prefix match.
+ ("prefix_mid_title", "Fix the Scout self-improvement: escalation flow", False),
+ ("no_title", None, False),
+ ]
+ )
+ def test_classifies_by_title_prefix(self, _name: str, title: str | None, is_self_improvement: bool) -> None:
+ props = _report_classification_props(title)
+ assert props["is_self_improvement_report"] is is_self_improvement
+ expected_kind = REPORT_KIND_SELF_IMPROVEMENT if is_self_improvement else REPORT_KIND_FINDING
+ assert props["report_kind"] == expected_kind