: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): catalog-first steering for scout runs (#78927)
Thiago Salvatore1ef89476f42b
diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex b73f06dae1bc..1013167cfa54 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -117,6 +117,18 @@ _HOW_A_RUN_WORKS_HEAD = """# How a run works2. **Check what the rest of the fleet has seen.** Call `scout-runs-list` again without `skill_name`, passing `text=<the entity or topic>` once per thing you're about to investigate. That filter is load-bearing: the call returns 20 rows by default, so on a full fleet an unfiltered page covers barely a day and a relevant sibling sorts out of view before you read it. Nothing matches? Move on, rather than reading the fleet's whole recent output. On a match, follow that run's `emitted_report_ids` / `edited_report_ids` into `inbox-reports-retrieve`, or its `emitted_finding_ids` via `scout-runs-emissions-list` for a sibling still on the signal channel, and read the evidence rather than the prose summary. This read is context-gathering only: ignore the tool output's guidance about associating your task with a report (`task_run` artefacts), which applies to a run actually working a report and would staple your run onto a sibling's.3. **Investigate.** Use the PostHog MCP read tools to gather evidence, discovering what's available at run time. Your skill body tells you *what* to look at."""+# Rendered into the head's investigate step only when the team's data catalog is enabled, because+# `system.information_schema.metrics` and `data-catalog-metric-run` don't exist for flag-off teams+# and unconditioned steering would burn those runs' budget on failing queries.+_METRICS_CATALOG_RULE = """ When a hypothesis rests on a business measure (revenue, MRR, churn, activation), check the governed metrics catalog first – `SELECT name, description, status, is_drifted FROM system.information_schema.metrics` via `execute-sql` – and run an approved, non-drifted match with `data-catalog-metric-run` rather than hand-deriving it, even when your skill body ships its own SQL for that measure: a governed definition outranks a playbook query, and a number derived outside it must be labeled noncanonical. Schema, availability, and freshness checks stay schema-first; no catalog detour for those."""+++def _how_a_run_works_head(*, data_catalog_enabled: bool) -> str:+ if not data_catalog_enabled:+ return _HOW_A_RUN_WORKS_HEAD+ return _HOW_A_RUN_WORKS_HEAD + _METRICS_CATALOG_RULE++# The close-out step is identical on every channel bar the word for what the run produces, and it is# numbered differently (the report channel has an extra search step), so both are rendered from here._CLOSE_OUT_STEP_TEMPLATE = """{number}. **Close out.** End your turn with a JSON object matching the schema in *Output format* below. Its `summary` field is your run close-out; see *Writing the summary* for how to structure it. A quiet day is a real outcome: "looked, found nothing meaningful" is a genuine, useful summary, not a failure, so don't manufacture {output} to fill space. The harness parses the JSON and writes `summary` to the run row as searchable prose."""@@ -148,8 +160,6 @@ _REPORT_STEPS_EDIT_ONLY = """4. **Find the report to update.** Locate the report- **Remember** a learning so you don't redo this work next run (call `scout-scratchpad-remember`).- **Skip** with a one-line note in your final summary, including when nothing in the inbox matches and there's therefore nothing to update."""-_HOW_A_RUN_WORKS_SIGNAL = f"{_HOW_A_RUN_WORKS_HEAD}\n{_HOW_A_RUN_WORKS_SIGNAL_STEPS}"-_SCRATCHPAD_KEYS = """# Scratchpad keysThese rules govern **every** key you write, including the `followup:`, `report:`, `improve:`, and `tags:` keys other sections ask for.@@ -662,12 +672,14 @@ Respond at end_turn with a single JSON object matching this schema:</jsonschema>"""-def _signal_tail_sections(*, followup_section: str, structured_output_section: str = "") -> list[str]:+def _signal_tail_sections(+ *, followup_section: str, structured_output_section: str = "", data_catalog_enabled: bool = False+) -> list[str]:"""Signal-channel tail. `followup_section` is the per-run composed self-validation section —channel-matched, so it can't live in a static list; `structured_output_section` is likewiseper-run composed (empty when the config carries no schema)."""return [- _HOW_A_RUN_WORKS_SIGNAL,+ f"{_how_a_run_works_head(data_catalog_enabled=data_catalog_enabled)}\n{_HOW_A_RUN_WORKS_SIGNAL_STEPS}",# Ground rules lead the tail: the untrusted-input rule is stated once there, and the sections# that read an untrusted source point back at it rather than restating the reasoning._GROUND_RULES,@@ -696,6 +708,7 @@ def _report_tail_sections(followup_section: str,github_read_access: bool = False,structured_output_section: str = "",+ data_catalog_enabled: bool = False,) -> list[str]:"""Report-channel tail, tailored to the report tools the scout actually opted into.@@ -709,8 +722,9 @@ def _report_tail_sections(`github_read_access` appends the `gh` evidence section only when the sandbox actually got aread-only GitHub token — every persona here can set reviewers (edit-only routes unroutedreports), so it slots in wherever reviewer guidance lives."""+ head = _how_a_run_works_head(data_catalog_enabled=data_catalog_enabled)if can_emit and can_edit:- how_a_run_works = f"{_HOW_A_RUN_WORKS_HEAD}\n{_REPORT_STEPS_BOTH}\n{_REPORT_CLOSE_OUT_STEP}"+ how_a_run_works = f"{head}\n{_REPORT_STEPS_BOTH}\n{_REPORT_CLOSE_OUT_STEP}"channel_sections = [_AUTHORING_VS_EDITING_REPORT_BOTH,_REPORT_SCRATCHPAD_POINTER,@@ -720,7 +734,7 @@ def _report_tail_sections(_REPORT_CHARTS,]elif can_emit:- how_a_run_works = f"{_HOW_A_RUN_WORKS_HEAD}\n{_REPORT_STEPS_EMIT_ONLY}\n{_REPORT_CLOSE_OUT_STEP}"+ how_a_run_works = f"{head}\n{_REPORT_STEPS_EMIT_ONLY}\n{_REPORT_CLOSE_OUT_STEP}"channel_sections = [_AUTHORING_REPORT_EMIT_ONLY,_REPORT_SCRATCHPAD_POINTER,@@ -730,7 +744,7 @@ def _report_tail_sections(_REPORT_CHARTS,]else: # edit-only — no authoring, so no suggested-reviewers / writing-a-report sections- how_a_run_works = f"{_HOW_A_RUN_WORKS_HEAD}\n{_REPORT_STEPS_EDIT_ONLY}\n{_REPORT_CLOSE_OUT_STEP}"+ how_a_run_works = f"{head}\n{_REPORT_STEPS_EDIT_ONLY}\n{_REPORT_CLOSE_OUT_STEP}"channel_sections = [_EDITING_REPORT_EDIT_ONLY,_REPORT_SCRATCHPAD_POINTER,@@ -811,6 +825,7 @@ def build_run_prompt(started_at: datetime,github_read_access: bool = False,structured_output_schema: dict | None = None,+ data_catalog_enabled: bool = False,) -> str:"""Render the opening prompt for one scout run.@@ -847,6 +862,10 @@ def build_run_prompt(GitHub token: it appends the `gh` reviewer-evidence section (report channel only), and naming`gh` in a tokenless run would just burn budget on 401s.+ `data_catalog_enabled` must mirror the team's `product-data-catalog` flag: it renders the+ governed-metrics catalog-first rule, and the catalog surfaces it names don't exist for+ flag-off teams (see the note on `_METRICS_CATALOG_RULE`).+Every prompt carries the self-validation follow-ups section: the scout keeps a `followup:`scratchpad queue and decides for itself, run by run, whether to spend the run validating it —there is no harness-side cadence or trigger. The section's re-surface guidance is@@ -872,6 +891,7 @@ def build_run_prompt(followup_section=followup_section,github_read_access=github_read_access,structured_output_section=structured_output_section,+ data_catalog_enabled=data_catalog_enabled,)# Point the run-identity line at a report tool the scout can actually call — prefer authoring,# fall back to editing for an edit-only scout. Never name a tool that would fail closed.@@ -879,7 +899,9 @@ def build_run_prompt(else:intro = _BASE_PROMPT_INTROsections = _signal_tail_sections(- followup_section=followup_section, structured_output_section=structured_output_section+ followup_section=followup_section,+ structured_output_section=structured_output_section,+ data_catalog_enabled=data_catalog_enabled,)emit_tool = "scout-emit-signal"# Slot the origin-matched improvement channel between friction reporting and the output formatdiff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex 085188f0ec6f..76c7ec84c529 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -13,10 +13,12 @@ from django.utils import timezoneimport posthoganalyticsfrom posthog.event_usage import groups+from posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Teamfrom posthog.models.utils import uuid7from posthog.sync import database_sync_to_async+from products.data_catalog.backend.facade.flags import is_data_catalog_enabledfrom products.signals.backend.agent_runtime import STEP_SCOUT, resolve_agent_runtimefrom products.signals.backend.models import SignalScoutConfig, SignalScoutRunfrom products.signals.backend.scout_harness.derived_metadata import stamp_derived_metadata@@ -440,6 +442,23 @@ async def arun_signals_scout(raise+def _data_catalog_enabled_for_team(team: Team) -> bool:+ """Whether this team's scouts get the governed-metrics catalog steering.++ A flag-read error falls back to off rather than propagating: this resolves inside the+ `_spawn_and_run` call the outer handler treats as a failed run, so a transient SDK or+ cache error would book a failure and advance the streak toward pausing the lane, over a+ prompt section the run does not need. Mirrors `team_limits._read_flag_payload`, where a+ read error never breaks dispatch either. Off is also the pre-catalog behaviour, so the+ fallback can only cost steering, never mis-steer a team at a table it cannot query.+ """+ try:+ return is_data_catalog_enabled(team)+ except Exception as error:+ capture_exception(error)+ return False++async def _spawn_and_run(*,team: Team,@@ -524,12 +543,14 @@ async def _spawn_and_run(runtime_adapter=runtime_adapter,reasoning_effort=reasoning_effort,)+ data_catalog_enabled = await database_sync_to_async(_data_catalog_enabled_for_team, thread_sensitive=False)(team)prompt = build_run_prompt(skill,run_id=str(run_id),team_id=team.id,started_at=started_at,github_read_access=github_guidance,+ data_catalog_enabled=data_catalog_enabled,# Renders the structured-output section (schema + `scout-record-output` contract) only# when the config carries a schema AND emit is on — records land solely as project# events, so a dry-run scout must not be steered at a tool that fails closed.diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 68a098fa57af..66b2391342f8 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -524,6 +524,40 @@ class TestPromptBuilder(BaseTest):)assert "Code-derived reviewer evidence" not in signal_prompt+ # The rule lives in the shared run-works head, and each channel assembles its own tail from+ # that head, so a channel can lose it independently.+ @parameterized.expand(+ [+ ("signal_channel", []),+ ("report_channel", ["emit_report", "edit_report"]),+ ]+ )+ def test_catalog_rule_gated_on_data_catalog_flag(self, name: str, allowed_tools: list[str]) -> None:+ skill_name = f"signals-scout-catalog-{name}"+ LLMSkill.objects.create(+ team=self.team,+ name=skill_name,+ description="Catalog scout",+ body="watch",+ allowed_tools=allowed_tools,+ )+ loaded = load_skill_for_run(self.team, skill_name)+ kwargs: dict = {+ "run_id": "00000000-0000-0000-0000-000000000abc",+ "team_id": self.team.id,+ "started_at": datetime(2026, 5, 1, 12, 34, 56, tzinfo=UTC),+ }++ enabled = build_run_prompt(loaded, **kwargs, data_catalog_enabled=True)+ assert "system.information_schema.metrics" in enabled+ assert "data-catalog-metric-run" in enabled++ # Default (flag off): the metrics table isn't registered for the team, so steering+ # at it would burn the run's budget on failing queries.+ disabled = build_run_prompt(loaded, **kwargs)+ assert "information_schema.metrics" not in disabled+ assert "data-catalog-metric-run" not in disabled+def test_report_channel_renders_report_persona_and_guidance(self) -> None:LLMSkill.objects.create(team=self.team,@@ -954,6 +988,50 @@ async def test_run_tags_session_with_scout_ai_stage(ateam, aerrors_skill):assert captured["ai_stage"] == "scout:custom"+ "flag,expect_rule",+ [+ pytest.param(True, True, id="enabled"),+ pytest.param(False, False, id="disabled"),+ # A flag-read error resolves off and the run still completes: failing here would book a+ # failed run and advance the streak toward pausing the lane, over a prompt section the+ # run does not need.+ pytest.param(RuntimeError("flag backend down"), False, id="flag_read_error"),+ ],+)+async def test_catalog_steering_reaches_the_prompt_from_the_team_flag(ateam, aerrors_skill, flag, expect_rule):+ # The prompt-builder tests take `data_catalog_enabled` directly, so they stay green if the+ # runner stops resolving or forwarding the flag — this covers that wiring end to end.+ session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)+ captured: dict = {}++ async def _capture_start(*args, on_task_run_created=None, **kwargs):+ captured.update(kwargs)+ if on_task_run_created is not None:+ await on_task_run_created(session.task_run)+ return session, result++ flag_mock = MagicMock(side_effect=flag) if isinstance(flag, Exception) else MagicMock(return_value=flag)+ with (+ patch("products.signals.backend.scout_harness.runner.MultiTurnSession.start", new=_capture_start),+ patch("products.signals.backend.scout_harness.runner.is_data_catalog_enabled", flag_mock),+ patch(+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",+ return_value="env-id",+ ),+ patch(+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ return_value=42,+ ),+ ):+ run_result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")++ assert run_result.status == apps.get_model("tasks", "TaskRun").Status.COMPLETED.value+ assert ("information_schema.metrics" in captured["prompt"]) is expect_rule++@pytest.mark.asyncio@pytest.mark.django_db@pytest.mark.parametrize(diff --git a/products/signals/skills/authoring-scouts/SKILL.md b/products/signals/skills/authoring-scouts/SKILL.mdindex 519b6adf477f..a18ef0ff0a14 100644--- a/products/signals/skills/authoring-scouts/SKILL.md+++ b/products/signals/skills/authoring-scouts/SKILL.md@@ -95,6 +95,11 @@ For error tracking it's the `count` vs `distinct_users` ratio; for CSP it's reacYour new scout needs its own.Name it explicitly near the top of the body so every run anchors on it.+A second design rule binds any **metric-shaped scout** — one that scores, ranks, or reports a business measure (MRR, churn risk, usage revenue, activation).+When the project's metrics catalog is enabled, it may hold a governed definition of that measure in `system.information_schema.metrics`, and the harness tells every run to prefer it — so write the body to cooperate rather than compete: have the run check the catalog for an approved, non-drifted metric before its own derivation, and run a match through `data-catalog-metric-run`.+Where a governed metric exists, reference it by name in any `references/queries.md` you ship, and label every hand-written derivation there a noncanonical fallback — an unlabeled "validated query" outranks the harness's catalog-first rule at run time, which is exactly how a scout ends up re-deriving a number the team already governs.+Freshness, availability, and schema checks are exempt: they stay schema-first, with no catalog detour.+## Run posture (config)A scout's schedule and emit behavior live on its `SignalScoutConfig`, separate from the skill body.diff --git a/tach.toml b/tach.tomlindex 8b92f2d26640..a21af558e06a 100644--- a/tach.toml+++ b/tach.toml@@ -690,6 +690,9 @@ depends_on = ["products.cdp","products.conversations","products.dashboards",+ # Facade-only (enforced by data_catalog's [[interfaces]] block): the scout harness gates+ # its catalog-first prompt rule on the data catalog flag.+ "products.data_catalog","products.data_warehouse","products.error_tracking","products.experiments",