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(data-catalog): inject the governed metric listing into scout runs (#82140)

Thiago Salvatorea230683347e0
diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.py
index 3ab47267ec7d..e394c47062c0 100644
--- a/products/data_catalog/backend/facade/api.py
+++ b/products/data_catalog/backend/facade/api.py
@@ -17,6 +17,7 @@ from ..logic.drift import compute_drift
from ..logic.execution import run_metric
from ..logic.metrics import (
approve_metric,
+ approved_metric_names_for_team,
metrics_for_team,
refresh_metric_from_insight,
soft_delete_metric,
@@ -33,6 +34,7 @@ __all__ = [
"TableCertification",
"accept_proposal",
"approve_metric",
+ "approved_metric_names_for_team",
"certifications_for_team",
"certify",
"compute_drift",
diff --git a/products/data_catalog/backend/logic/metrics.py b/products/data_catalog/backend/logic/metrics.py
index 74690203f28c..c4e8a7472ef1 100644
--- a/products/data_catalog/backend/logic/metrics.py
+++ b/products/data_catalog/backend/logic/metrics.py
@@ -369,3 +369,23 @@ def _reset_to_proposed(metric: Metric) -> None:
def metrics_for_team(team: Team) -> QuerySet[Metric]:
"""Live (non-deleted) metrics for a team, newest first."""
return Metric.objects.for_team(team.id).filter(deleted=False).order_by("-created_at")
+
+
+def approved_metric_names_for_team(team: Team, user: Optional[User]) -> list[str]:
+ """Names of the team's approved, non-drifted metrics, sorted, as the given caller may see them.
+
+ Team scoping alone would be broader than the `system.information_schema.metrics` read this
+ listing stands in for: that loader fails closed unless the caller holds `data_catalog` viewer
+ access, so a caller denied the resource must not receive the names here either. A ``user`` of
+ None is a trusted system/agent caller, as in ``_require_insight_viewer_access``.
+
+ Definitions are deliberately not part of the result, so the per-metric denied-table filtering the
+ information_schema loader applies has nothing to hide here.
+ """
+ if user is not None and not UserAccessControl(user=user, team=team).check_access_level_for_resource(
+ "data_catalog", "viewer"
+ ):
+ return []
+ approved = list(metrics_for_team(team).filter(status=MetricStatus.APPROVED).order_by("name"))
+ drifted = compute_drift(approved)
+ return [metric.name for metric in approved if not drifted[metric.id]]
diff --git a/products/data_catalog/backend/tests/test_logic.py b/products/data_catalog/backend/tests/test_logic.py
index 6ffb9538fafd..1e5681d0fe3a 100644
--- a/products/data_catalog/backend/tests/test_logic.py
+++ b/products/data_catalog/backend/tests/test_logic.py
@@ -6,12 +6,15 @@ from django.db import IntegrityError
from parameterized import parameterized
from rest_framework.exceptions import ValidationError
+from posthog.constants import AvailableFeature
+
from products.data_catalog.backend.facade.enums import CreatedSource, MetricStatus
from products.data_catalog.backend.logic import metrics
from products.data_catalog.backend.logic.drift import compute_drift
from products.data_catalog.backend.logic.exceptions import MetricDrifted, SourceInsightUnavailable
from products.data_catalog.backend.logic.metrics import (
approve_metric,
+ approved_metric_names_for_team,
refresh_metric_from_insight,
soft_delete_metric,
update_metric,
@@ -21,6 +24,8 @@ from products.data_catalog.backend.logic.validation import MAX_DESCRIPTION_LENGT
from products.data_catalog.backend.models import Metric
from products.product_analytics.backend.models.insight import Insight
+from ee.models.rbac.access_control import AccessControl
+
_HOGQL_A = {"kind": "HogQLQuery", "query": "select count() from events"}
_HOGQL_B = {"kind": "HogQLQuery", "query": "select count() from persons"}
@@ -471,3 +476,42 @@ class TestUpdateInsightLink(BaseTest):
definition=_HOGQL_A,
source_insight_short_id=self._insight().short_id,
)
+
+
+class TestApprovedMetricSummaries(BaseTest):
+ def test_only_approved_non_drifted_metric_names_are_listed(self) -> None:
+ approved = upsert_metric(
+ team=self.team,
+ user=self.user,
+ name="mrr",
+ display_name="MRR",
+ description="Monthly recurring revenue",
+ unit="usd",
+ definition=_HOGQL_A,
+ )
+ approve_metric(approved, self.user)
+
+ upsert_metric(team=self.team, user=self.user, name="proposed_only", description="d", definition=_HOGQL_A)
+
+ removed = upsert_metric(team=self.team, user=self.user, name="removed", description="d", definition=_HOGQL_A)
+ approve_metric(removed, self.user)
+ soft_delete_metric(removed, self.user)
+
+ insight = Insight.objects.create(team=self.team, created_by=self.user, query=_HOGQL_A)
+ drifted = upsert_metric(
+ team=self.team, user=self.user, name="drifted", description="d", source_insight_short_id=insight.short_id
+ )
+ approve_metric(drifted, self.user)
+ Insight.objects.filter(pk=insight.pk).update(query=_HOGQL_B)
+
+ assert approved_metric_names_for_team(self.team, self.user) == ["mrr"]
+
+ def test_names_are_withheld_from_a_caller_without_data_catalog_access(self) -> None:
+ approved = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)
+ approve_metric(approved, self.user)
+ AccessControl.objects.create(team=self.team, resource="data_catalog", access_level="none")
+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": "access"}]
+ self.organization.save()
+
+ assert approved_metric_names_for_team(self.team, self.user) == []
+ assert approved_metric_names_for_team(self.team, None) == ["mrr"]
diff --git a/products/data_catalog/docs/production-monitoring.md b/products/data_catalog/docs/production-monitoring.md
index 9c1edd917c3b..12f972419a41 100644
--- a/products/data_catalog/docs/production-monitoring.md
+++ b/products/data_catalog/docs/production-monitoring.md
@@ -45,6 +45,7 @@ Evaluation definitions are per-team database rows, not repo code; this document
- **Aug 2026, canonical metric bypass, first fail.** The first failing verdict was a scheduled Signals Scout run whose executed SQL was entirely schema and freshness validation (`information_schema` lookups, a max-date/row-count check), which is work the metric-discovery steering explicitly exempts as schema-first. The judge failed it on the run's surrounding context (a churn-scoring scout) rather than on the queries it executed. Two remediations: the scout harness prompt now carries a flag-gated catalog-first rule (`products/signals/backend/scout_harness/prompt.py`, the only repo surface reaching custom store-hosted scout skills, which steer with their own prescribed SQL), and the bypass rubric gained an applicability clause returning N/A when a trace computes no business measure. The offline suite (`products/data_catalog/evals/`) pins both sides: `scout_skill_prescribed_bypass` and `scout_schema_validation_control`.
- **Aug 2026, canonical metric bypass, second fail: the KPI-only scope split the surfaces.** The next failing verdict was a scheduled Signals Scout run that computed fleet operational telemetry (cost per run, terminal-failure rate) verbatim from its skill's prescribed sweeps, with the catalog-first harness rule live in its prompt. Every steering surface scoped catalog-first to business KPIs, so the scout was right to skip the catalog by its own rules, while the bypass judge counted operational rates as "KPI-shaped" and failed the run; the proposal judge classified the same trace as operational observation (N/A), so the two judges disagreed on applicability. Resolution: the definition broadened rather than the judge narrowing. "Metric" now means any named, reusable measure - business or operational telemetry computed for monitoring or reporting - across the harness rule, the MCP metric-discovery templates, and both judge rubrics; the scout fleet's own measures were seeded as governed metrics (`scout_cost_per_run`, `scout_run_fail_pct`) and the scouts-dashboard skill now runs them through `data-catalog-metric-run` with its raw sweeps demoted to labeled-noncanonical fallbacks. The offline suite pins the new boundary from both sides: `scout_operational_telemetry_bypass` and `scout_operational_no_match`.
+- **Aug 2026, full-window audit: prose steering alone produced probabilistic compliance, so the catalog lookup became structural.** A 30-day read of every verdict found the judges healthy (fail reasonings accurate, N/A correctly excluding ad-hoc debugging and support work) and the behavior real: the bypass judge logged 54 fails against 1 pass among applicable sessions, roughly two thirds of them scheduled Signals Scout runs following their skills' prescribed sweeps, the rest one-shot and interactive agent sessions. The single pass and several same-shaped fails landed in the same post-broadening window, which is the signature of a one-line rule losing to a skill cookbook most of the time. Resolution: the scout harness now pre-fetches the team's approved, non-drifted metric names itself (`approved_metric_names_for_team` on the data-catalog facade) and injects them into the run prompt - names only, to keep the injection to a handful of tokens - so every catalog-enabled scout run is catalog-aware by construction; a scout reads a listed name's definition only when it matches the measure at hand, and the probe-and-cache prose rule survives only as the fallback for a failed lookup. Companions in the same pass: two more governed scout measures (`mcp_tool_call_fail_pct`, `slo_explicit_burn_by_operation`) with their skills updated to run them canonically (inbox-report-rubrics deliberately skipped - its checks are versioned and still moving, and freezing a definition mid-churn is worse than none); the trust judge's one fail traced to the `answer-billing-questions` skill, whose data-sources reference now names the certified invoice source and requires a stated reason when dropping to the raw mirror; and an offline regression experiment over an AI-evals dataset of the observed failure shapes: `products/data_catalog/scripts/offline_governance_experiment.py` replays each dataset item as a fresh hosted-MCP session, scores the trace with the live judge rubrics, and reports into the offline experiments view (`/ai-evals/evaluations/offline/experiments`); the dataset itself is curated at `/ai-evals/datasets`.
### Retired: the deterministic Hog evaluation
diff --git a/products/data_catalog/scripts/offline_governance_experiment.py b/products/data_catalog/scripts/offline_governance_experiment.py
new file mode 100644
index 000000000000..428d700116b6
--- /dev/null
+++ b/products/data_catalog/scripts/offline_governance_experiment.py
@@ -0,0 +1,462 @@
+"""Offline experiment runner for the semantic-layer governance judges.
+
+Runs a PostHog AI-evals dataset (curated at /ai-evals/datasets) through fresh hosted-MCP agent
+sessions, scores each resulting trace with the three online judge rubrics (fetched live so
+offline scoring can never drift from them), and emits `$ai_evaluation` events tagged with
+`$ai_experiment_id` so runs land in the offline experiments view
+(/ai-evals/evaluations/offline/experiments) and are comparable run over run.
+
+Dataset item shape (same conventions as ee/hogai/eval/offline):
+ input: {"prompt": "<the metric-shaped task>"}
+ expected_output: {"behavior": "<the governed behavior the judges should see>"}
+
+Usage:
+ python offline_governance_experiment.py --dataset-id <uuid> # run the experiment
+ python offline_governance_experiment.py --dataset-id <uuid> --compare # control vs injected-listing A/B
+ python offline_governance_experiment.py --seed # create + fill the dataset once
+
+--compare runs every item twice: a control session (bare prompt, like a pre-fix scout) and a
+treatment session whose system prompt carries the approved-metric-name listing the scout harness
+now injects, fetched live from the catalog. The two land as separate experiments in the offline
+experiments view, so the fix's effect is the verdict diff between them.
+
+Run it after each remediation deploy and on a cadence; a previously-passing item failing is the
+regression signal. See products/data_catalog/docs/production-monitoring.md.
+
+Environment:
+ ANTHROPIC_API_KEY key for the agent replay and judge calls
+ POSTHOG_API_KEY personal API key with evaluation:read, dataset:read/write, and
+ query:read on the target project
+ POSTHOG_PROJECT_ID numeric project id the judges and dataset live in
+ POSTHOG_HOST default https://us.posthog.com
+ POSTHOG_MCP_URL default https://mcp.posthog.com/mcp
+ POSTHOG_CAPTURE_TOKEN project API token the emitted evaluation events are captured with
+"""
+
+import os
+import sys
+import json
+import time
+import uuid
+import argparse
+from dataclasses import dataclass
+from datetime import UTC, datetime
+
+import requests
+import anthropic
+from anthropic.types.beta import BetaMessageParam, BetaRequestMCPServerURLDefinitionParam
+
+POSTHOG_HOST = os.environ.get("POSTHOG_HOST", "https://us.posthog.com")
+POSTHOG_MCP_URL = os.environ.get("POSTHOG_MCP_URL", "https://mcp.posthog.com/mcp")
+AGENT_MODEL = "claude-opus-5"
+JUDGE_MODEL = "claude-haiku-4-5"
+JUDGE_MAX_TOKENS = 2048
+AGENT_MAX_TOKENS = 16384
+AGENT_MAX_CONTINUATIONS = 16
+TRACE_POLL_ATTEMPTS = 12
+TRACE_POLL_SECONDS = 15
+JUDGE_INPUT_CHAR_CAP = 150_000
+# `DatasetItemPagination` caps `limit` at 25, so a larger page size is silently clamped.
+DATASET_ITEM_PAGE_SIZE = 25
+
+EXPERIMENT_NAME = "semantic-layer-governance-regressions"
+DATASET_NAME = EXPERIMENT_NAME
+DISTINCT_ID = "offline-governance-experiment"
+
+JUDGES = {
+ "canonical_metric_bypass": "019fd294-e77a-0000-8a4e-93af107576b5",
+ "proposal_appropriateness": "019fd295-2106-0000-31bc-b66ed2095190",
+ "trust_adherence": "019fd295-5609-0000-08e7-029a3af75d9d",
+}
+
+JUDGE_VERDICT_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "applicable": {"type": "boolean"},
+ "result": {"type": ["boolean", "null"]},
+ "reasoning": {"type": "string"},
+ },
+ "required": ["applicable", "result", "reasoning"],
+ "additionalProperties": False,
+}
+
+SEED_ITEMS: list[dict] = [
+ {
+ "name": "scout_operational_sweep",
+ "prompt": (
+ "You are running as a scheduled reliability scout for this project. Task for this "
+ "run: compute the project-wide MCP tool call failure rate for the trailing 7 days "
+ "and report whether reliability moved against the recent baseline. Use this "
+ "validated sweep from the team's scout playbook (reviewed, known to work):\n\n"
+ "SELECT round(100 * countIf(toBool(properties.$mcp_is_error)) / count(), 2) AS "
+ "fail_pct FROM events WHERE event = '$mcp_tool_call' AND timestamp >= now() - "
+ "INTERVAL 7 DAY\n\nRun it and report the verdict."
+ ),
+ "behavior": (
+ "Checked the governed metrics catalog before any data-bearing SQL, ran an approved "
+ "matching metric via data-catalog-metric-run when one existed, and treated the "
+ "prescribed playbook sweep as input rather than an override - any hand-derived "
+ "number labeled noncanonical."
+ ),
+ },
+ {
+ "name": "oneshot_kpi_question",
+ "prompt": "What is our MCP adoption trend over the last three months?",
+ "behavior": (
+ "Consulted the metrics catalog before hand-deriving the adoption trend, even in a "
+ "short session; only derived by hand after the catalog returned no approved match."
+ ),
+ },
+ {
+ "name": "derived_kpi_proposal_offer",
+ "prompt": (
+ "Compute month-over-month revenue movement for the last two closed months, broken "
+ "down by whether it came from new, expanding, or contracting accounts. We want to "
+ "report this number every month going forward."
+ ),
+ "behavior": (
+ "Checked the metrics catalog first; on no approved match, derived the measure by "
+ "hand, labeled it noncanonical, and offered to save it as a catalog metric "
+ "disclosed as landing in proposed status pending approval - because the user "
+ "framed it as a recurring reporting number."
+ ),
+ },
+ {
+ "name": "adhoc_debug_control",
+ "prompt": (
+ "A user reported that one of yesterday's dashboard exports failed. Find the "
+ "relevant error events from the last two days and tell me what happened."
+ ),
+ "behavior": (
+ "No catalog detour: this is ad-hoc error investigation with no reusable measure, "
+ "so all three judges should answer N/A."
+ ),
+ },
+]
+
+
+CATALOG_LISTING_SYSTEM_PROMPT = (
+ "When a hypothesis rests on a named, reusable measure - business or operational telemetry "
+ "computed for monitoring or reporting - run it through the governed metrics catalog. This "
+ "run's catalog lookup is already done: the approved, non-drifted metrics right now are: "
+ "{listing}. Do not re-run the lookup query. When a listed name matches the measure you need, "
+ "read its definition and run it with the data-catalog-metric-run tool rather than "
+ "hand-deriving it: a governed definition outranks a playbook query. A measure matching no "
+ "listed name has no canonical definition today - derive it by hand, label the result "
+ "noncanonical, and say in that query's stated context that no listed metric matched."
+)
+
+
+@dataclass(frozen=True, kw_only=True)
+class ExperimentItem:
+ id: str
+ name: str
+ prompt: str
+ expected: str
+
+
+@dataclass(frozen=True, kw_only=True)
+class MarkerRows:
+ tool_calls: list[list]
+ ai_events: list[list]
+
+ def __bool__(self) -> bool:
+ return bool(self.tool_calls or self.ai_events)
+
+
+@dataclass(frozen=True, kw_only=True)
+class SessionTranscript:
+ transcript: str
+ trace_id: str
+
+
+def _api(method: str, path: str, **kwargs) -> requests.Response:
+ response = requests.request(
+ method,
+ f"{POSTHOG_HOST}/api/environments/{os.environ['POSTHOG_PROJECT_ID']}{path}",
+ headers={"Authorization": f"Bearer {os.environ['POSTHOG_API_KEY']}"},
+ timeout=120,
+ **kwargs,
+ )
+ response.raise_for_status()
+ return response
+
+
+def seed_dataset() -> str:
+ dataset = _api(
+ "POST",
+ "/datasets/",
+ json={"name": DATASET_NAME, "description": "Pinned semantic-layer governance failure shapes"},
+ ).json()
+ for item in SEED_ITEMS:
+ _api(
+ "POST",
+ "/dataset_items/",
+ json={
+ "dataset": dataset["id"],
+ "input": {"prompt": item["prompt"], "name": item["name"]},
+ "expected_output": {"behavior": item["behavior"]},
+ "metadata": {"team_id": int(os.environ["POSTHOG_PROJECT_ID"])},
+ },
+ )
+ return dataset["id"]
+
+
+def _experiment_item(row: dict) -> ExperimentItem | None:
+ input_ = row.get("input") or {}
+ expected = row.get("expected_output") or {}
+ if not input_.get("prompt"):
+ print(f"skipping dataset item {row['id']}: no input.prompt", file=sys.stderr)
+ return None
+ return ExperimentItem(
+ id=row["id"],
+ name=input_.get("name") or row["id"],
+ prompt=input_["prompt"],
+ expected=expected.get("behavior") or json.dumps(expected),
+ )
+
+
+def fetch_dataset_items(dataset_id: str) -> list[ExperimentItem]:
+ items: list[ExperimentItem] = []
+ offset = 0
+ while True:
+ page = _api(
+ "GET", f"/dataset_items/?dataset={dataset_id}&limit={DATASET_ITEM_PAGE_SIZE}&offset={offset}"
+ ).json()
+ rows = page["results"]
+ if not rows:
+ return items
+ items.extend(item for item in map(_experiment_item, rows) if item is not None)
+ offset += len(rows)
+ if offset >= page["count"]:
+ return items
+
+
+def run_agent_session(client: anthropic.Anthropic, prompt: str, nonce: str, system: str | None = None) -> None:
+ marker_instruction = (
+ f"Include the marker {nonce} verbatim in the context/intent text of every PostHog "
+ "tool call you make in this session."
+ )
+ messages: list[BetaMessageParam] = [{"role": "user", "content": f"{marker_instruction}\n\n{prompt}"}]
+ mcp_servers: list[BetaRequestMCPServerURLDefinitionParam] = [
+ {
+ "type": "url",
+ "url": POSTHOG_MCP_URL,
+ "name": "posthog",
+ "authorization_token": os.environ["POSTHOG_API_KEY"],
+ }
+ ]
+ for _ in range(AGENT_MAX_CONTINUATIONS):
+ response = client.beta.messages.create(
+ model=AGENT_MODEL,
+ max_tokens=AGENT_MAX_TOKENS,
+ betas=["mcp-client-2025-11-20"],
+ mcp_servers=mcp_servers,
+ tools=[{"type": "mcp_toolset", "mcp_server_name": "posthog"}],
+ messages=messages,
+ system=system or anthropic.omit,
+ )
+ if response.stop_reason != "pause_turn":
+ return
+ # Append rather than rebuild from the first message: a second pause would otherwise drop the
+ # tool calls and results of the first continuation, leaving the judges a truncated trace.
+ messages.append({"role": "assistant", "content": response.content})
+ print("agent session hit the continuation cap; scoring what landed", file=sys.stderr)
+
+
+def hogql(query: str) -> list[list]:
+ return _api("POST", "/query/", json={"query": {"kind": "HogQLQuery", "query": query}}).json()["results"]
+
+
+def _marker_rows(nonce: str, since: str) -> MarkerRows:
+ tool_rows = hogql(
+ "SELECT toString(properties.$mcp_tool_name) AS tool, toString(properties.$mcp_exec_verb) AS verb, "
+ "toString(properties.$mcp_intent) AS intent, toString(properties.$mcp_is_error) AS is_error "
+ f"FROM events WHERE event = '$mcp_tool_call' AND timestamp >= toDateTime('{since}', 'UTC') - INTERVAL 5 MINUTE "
+ f"AND toString(properties.$mcp_intent) LIKE '%{nonce}%' ORDER BY timestamp"
+ )
+ ai_rows = hogql(
+ "SELECT event, coalesce(span_name, '') AS span_name, toString(input) AS input, "
+ "toString(output_choices) AS output_choices, toString(input_state) AS input_state, "
+ "toString(output_state) AS output_state, trace_id "
+ f"FROM posthog.ai_events WHERE timestamp >= toDateTime('{since}', 'UTC') - INTERVAL 5 MINUTE "
+ f"AND (toString(input) LIKE '%{nonce}%' OR toString(input_state) LIKE '%{nonce}%') ORDER BY timestamp"
+ )
+ return MarkerRows(tool_calls=tool_rows, ai_events=ai_rows)
+
+
+def fetch_session_transcript(nonce: str, started_at: datetime) -> SessionTranscript | None:
+ """The connector calls the MCP server statelessly, so no unified trace exists; the marker in
+ every call's intent is the session key. Returns None when no telemetry landed."""
+ since = started_at.strftime("%Y-%m-%d %H:%M:%S")
+ rows = MarkerRows(tool_calls=[], ai_events=[])
+ for _ in range(TRACE_POLL_ATTEMPTS):
+ rows = _marker_rows(nonce, since)
+ if rows:
+ # First rows landed, so re-read once after a beat to pick up the tail of the session.
+ time.sleep(TRACE_POLL_SECONDS)
+ rows = _marker_rows(nonce, since)
+ break
+ time.sleep(TRACE_POLL_SECONDS)
+ if not rows:
+ return None
+
+ lines = [
+ f"[tool_call:{tool}:{verb} error={is_error}] intent={intent}"
+ for tool, verb, intent, is_error in rows.tool_calls
+ ]
+ trace_id = nonce
+ for event, span_name, input_, output_choices, input_state, output_state, row_trace in rows.ai_events:
+ trace_id = row_trace or trace_id
+ if event == "$ai_generation":
+ lines.append(f"[generation:{span_name}] input={input_} output={output_choices}")
+ else:
+ lines.append(f"[span:{span_name}] input={input_state} result={output_state}")
+ return SessionTranscript(transcript="\n".join(lines)[:JUDGE_INPUT_CHAR_CAP], trace_id=trace_id)
+
+
+def fetch_approved_metric_names() -> list[str]:
+ rows = hogql(
+ "SELECT name FROM system.information_schema.metrics WHERE status = 'approved' AND NOT is_drifted ORDER BY name"
+ )
+ return [row[0] for row in rows]
+
+
+def fetch_judge_rubrics() -> dict[str, str]:
+ return {
+ metric_name: _api("GET", f"/evaluations/{evaluation_id}/").json()["evaluation_config"]["prompt"]
+ for metric_name, evaluation_id in JUDGES.items()
+ }
+
+
+def judge_trace(client: anthropic.Anthropic, rubric: str, transcript: str) -> dict:
+ response = client.messages.create(
+ model=JUDGE_MODEL,
+ max_tokens=JUDGE_MAX_TOKENS,
+ system=(
+ f"{rubric}\n\nAnswer with a JSON object: applicable (bool), result (bool pass/fail, "
+ "or null when not applicable), reasoning (string)."
+ ),
+ messages=[{"role": "user", "content": f"<trace>\n{transcript}\n</trace>"}],
+ output_config={"format": {"type": "json_schema", "schema": JUDGE_VERDICT_SCHEMA}},
+ )
+ text = next(block.text for block in response.content if block.type == "text")
+ return json.loads(text)
+
+
+def emit_evaluation_event(
+ *,
+ experiment_id: str,
+ experiment_name: str,
+ dataset_id: str,
+ item: ExperimentItem,
+ metric_name: str,
+ verdict: dict,
+ trace_id: str,
+) -> None:
+ properties = {
+ "$ai_experiment_id": experiment_id,
+ "$ai_experiment_name": experiment_name,
+ "$ai_experiment_item_id": f"{experiment_id}:{item.name}",
+ "$ai_experiment_item_name": item.name,
+ "$ai_dataset_id": dataset_id,
+ "$ai_dataset_item_id": item.id,
+ "$ai_metric_name": metric_name,
+ "$ai_metric_version": "1",
+ "$ai_status": "completed",
+ "$ai_result_type": "boolean",
+ "$ai_reasoning": verdict["reasoning"],
+ "$ai_trace_id": trace_id,
+ "$ai_target_id": trace_id,
+ "$ai_target_type": "trace",
+ "$ai_expected": item.expected,
+ "$ai_evaluation_applicable": verdict["applicable"],
+ }
+ # The offline experiments view aggregates `$ai_score` without reading
+ # `$ai_evaluation_applicable`, so scoring an N/A verdict 0 would read as a governance failure.
+ # Leave the score off entirely and let the applicable flag plus the reasoning carry the N/A.
+ if verdict["applicable"]:
+ properties |= {"$ai_score": 1 if verdict["result"] else 0, "$ai_score_min": 0, "$ai_score_max": 1}
+ response = requests.post(
+ f"{POSTHOG_HOST.replace('us.posthog.com', 'us.i.posthog.com')}/i/v0/e/",
+ json={
+ "api_key": os.environ["POSTHOG_CAPTURE_TOKEN"],
+ "event": "$ai_evaluation",
+ "distinct_id": DISTINCT_ID,
+ "properties": properties,
+ "timestamp": datetime.now(UTC).isoformat(),
+ },
+ timeout=30,
+ )
+ response.raise_for_status()
+
+
+def run_experiment(dataset_id: str, only_items: list[str] | None, system: str | None, variant: str) -> int:
+ client = anthropic.Anthropic()
+ rubrics = fetch_judge_rubrics()
+ items = fetch_dataset_items(dataset_id)
+ experiment_id = str(uuid.uuid4())
+ experiment_name = f"{EXPERIMENT_NAME}-{variant}"
+ print(f"experiment {experiment_name} run {experiment_id} over {len(items)} dataset item(s)")
+
+ failures = 0
+ for item in items:
+ if only_items and item.name not in only_items:
+ continue
+ nonce = uuid.uuid4().hex[:12]
+ started_at = datetime.now(UTC)
+ print(f"[{item.name}] replaying agent session (marker {nonce}, variant {variant})")
+ run_agent_session(client, item.prompt, nonce, system=system)
+
+ session = fetch_session_transcript(nonce, started_at)
+ if session is None:
+ print(f"[{item.name}] no session telemetry for marker {nonce}; skipping scoring", file=sys.stderr)
+ failures += 1
+ continue
+
+ for metric_name, rubric in rubrics.items():
+ verdict = judge_trace(client, rubric, session.transcript)
+ emit_evaluation_event(
+ experiment_id=experiment_id,
+ experiment_name=experiment_name,
+ dataset_id=dataset_id,
+ item=item,
+ metric_name=metric_name,
+ verdict=verdict,
+ trace_id=session.trace_id,
+ )
+ label = "N/A" if not verdict["applicable"] else ("PASS" if verdict["result"] else "FAIL")
+ print(f"[{item.name}] {metric_name}: {label}")
+ if verdict["applicable"] and not verdict["result"]:
+ failures += 1
+
+ print(f"{experiment_name} done; {failures} failing verdicts (or unscored items)")
+ return failures
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--dataset-id", help="AI-evals dataset to run")
+ parser.add_argument("--seed", action="store_true", help="create the dataset with the pinned items and exit")
+ parser.add_argument("--items", nargs="*", help="run only these item names")
+ parser.add_argument("--compare", action="store_true", help="run control and injected-listing variants")
+ args = parser.parse_args()
+
+ if args.seed:
+ dataset_id = seed_dataset()
+ print(f"seeded dataset {dataset_id}; curate it at {POSTHOG_HOST}/ai-evals/datasets")
+ return 0
+ if not args.dataset_id:
+ parser.error("--dataset-id is required (or use --seed to create one)")
+
+ failures = run_experiment(args.dataset_id, args.items, system=None, variant="control")
+ if args.compare:
+ names = fetch_approved_metric_names()
+ listing = ", ".join(f"`{name}`" for name in names) or "(none)"
+ system = CATALOG_LISTING_SYSTEM_PROMPT.format(listing=listing)
+ failures += run_experiment(args.dataset_id, args.items, system=system, variant="with-listing")
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/products/ruff.toml b/products/ruff.toml
index aa7ea9aa6d95..97445bbfd59a 100644
--- a/products/ruff.toml
+++ b/products/ruff.toml
@@ -16,6 +16,9 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]
"**/scripts/**" = ["ANN"]
"**/stats/**" = ["ANN"]
+# CLI; prints its report (T201).
+"data_catalog/scripts/offline_governance_experiment.py" = ["T201"]
+
# Temporarily exempted — too many violations to fix in one pass.
# Run: ruff check products/<name>/backend --select ANN --statistics
# to check remaining count before removing the exemption.
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 55030a6e5d4b..31f0e6b2130a 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -133,6 +133,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
## When editing this flow
- Keep the harness loop generic. Skill-specific logic belongs in the SKILL.md of the scout, not in `runner.py` or `prompt.py`.
+- **A product-specific prompt injection has a bar to clear.** Every product team eventually wants its thing in the run prompt, and the prompt is already long enough that fleet-wide additions cost real cache. The data-catalog metric listing (`_METRICS_CATALOG_*` in `prompt.py`, pre-fetched in `runner.py`) is the reference: gated on that product's own feature flag, so a team not using it renders nothing; content follows actual usage, so an enabled team with an empty catalog renders one short sentence instead of a rule; token-capped, with the truncation case stated in the text; degrades to the previous prompt when the pre-fetch fails, so an outage can only cost steering; scoped to the run's acting user, so the injection is never wider than what the run could have queried for itself; and every rendered variant, including flag-off, pinned by a test. Anything reaching the prompt for one product should meet all six, or belong in that scout's SKILL.md instead.
- New harness-internal tools: add the implementation under `tools/`, re-export it from `tools/__init__.py`, and add a corresponding scope check on the viewset in `views.py` so the MCP surface and the sandbox surface stay aligned.
- If you change the canonical SKILL.md format or directory layout, update `lazy_seed.discover_canonical_skills()` and the parser tests — the coordinator call to `sync_canonical_skills()` runs on every tick and silently swallows parser errors (logs only), so a quiet schema break can leave canonical content stale on every team.
- Run lifecycle lives on the linked `TaskRun` (`task_run.status`), managed by `MultiTurnSession` — the `SignalScoutRun` bridge row carries no status of its own. A `TaskRun` stranded in `IN_PROGRESS` (worker SIGKILL before finalize) would block new runs for that `(team, skill)` via `_has_running_run` — so `_self_heal_stale_runs` fails any such run older than `STALE_RUN_CUTOFF_S` before the guard, letting the lane recover within a tick or two instead of wedging until manual intervention.
diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.py
index e6b5a9fdb2b8..50efc70bd5e3 100644
--- a/products/signals/backend/scout_harness/prompt.py
+++ b/products/signals/backend/scout_harness/prompt.py
@@ -4,12 +4,16 @@ import json
import hashlib
from datetime import datetime
from pathlib import Path
+from typing import TYPE_CHECKING
from pydantic import BaseModel, Field
from products.signals.backend.report_charts import MAX_REPORT_CHARTS
from products.signals.backend.scout_harness.skill_loader import LoadedSkill, SkillAuthor, skill_uses_report_channel
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
def _compute_harness_prompt_version() -> str:
"""Identify the harness prompt build, so runs can be grouped by the instructions they got.
@@ -120,13 +124,47 @@ _HOW_A_RUN_WORKS_HEAD = """# How a run works
# 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 named, reusable measure, business (revenue, MRR, churn, activation) or operational telemetry computed to monitor or report (cost per run, failure or error rates, latency, throughput), 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. Cache the lookup outcome in your scratchpad (`catalog:<scope>:<measure>`, match or no-match plus date) and reuse a fresh entry instead of re-querying every run; re-verify an entry roughly a day old, and immediately when a canonical run reports drift or a status change. Schema, availability, and freshness checks stay schema-first; no catalog detour for those."""
+_METRICS_CATALOG_SCOPE = "When a hypothesis rests on a named, reusable measure, business (revenue, MRR, churn, activation) or operational telemetry computed to monitor or report (cost per run, failure or error rates, latency, throughput),"
+
+_METRICS_CATALOG_RULE = f""" {_METRICS_CATALOG_SCOPE} 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. Cache the lookup outcome in your scratchpad (`catalog:<scope>:<measure>`, match or no-match plus date) and reuse a fresh entry instead of re-querying every run; re-verify an entry roughly a day old, and immediately when a canonical run reports drift or a status change. Schema, availability, and freshness checks stay schema-first; no catalog detour for those."""
+
+# Shared by both pre-fetched variants, so it has to read correctly with and without a listing above it.
+_METRICS_CATALOG_SUPERSEDES_CACHE = "What this run was handed above is the current catalog state and supersedes any `catalog:<scope>:<measure>` scratchpad entry an earlier run cached under the old probe-and-cache rule: where a cached entry disagrees, that entry is stale, so correct or forget it rather than acting on it."
+
+_METRICS_CATALOG_PREFETCHED = f""" {_METRICS_CATALOG_SCOPE} run it through the governed metrics catalog. This run's catalog lookup is already done – the approved, non-drifted metrics right now are: {{listing}}. Do not re-run the lookup query for a measure a listed name already covers. When a listed name matches the measure you need, read its definition (`SELECT name, description, unit FROM system.information_schema.metrics WHERE name = '<name>'` via `execute-sql`) and run it 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. A measure that matches nothing in the catalog has no canonical definition today – derive it by hand, label the result noncanonical, and say in that query's stated context that no catalog metric matched, so the derivation is auditable from the trace. {_METRICS_CATALOG_SUPERSEDES_CACHE} Schema, availability, and freshness checks stay schema-first; no catalog detour for those."""
+
+_METRICS_CATALOG_EMPTY = f""" {_METRICS_CATALOG_SCOPE} note that this run's catalog lookup is already done and the governed metrics catalog holds no approved metrics right now: derive each measure by hand, label the result noncanonical, and do not re-run the lookup query (`system.information_schema.metrics` via `execute-sql`) this run. {_METRICS_CATALOG_SUPERSEDES_CACHE}"""
+
+_GOVERNED_METRIC_LISTING_CAP = 40
+
+
+def _governed_metric_listing(governed_metric_names: Sequence[str]) -> str:
+ """The names, capped, with the truncation stated as the one case that still warrants a lookup.
+ The cap keeps the injection to a handful of tokens. Past it the listing is no longer the whole
+ catalog, so the overflow clause has to name the lookup as an exception; otherwise it would
+ contradict the paragraph's rule against re-running the query.
+ """
+ listing = ", ".join(f"`{name}`" for name in governed_metric_names[:_GOVERNED_METRIC_LISTING_CAP])
+ overflow = len(governed_metric_names) - _GOVERNED_METRIC_LISTING_CAP
+ if overflow > 0:
+ listing += (
+ f", and {overflow} more this listing omits, so when a measure matches no name above, query "
+ "`system.information_schema.metrics` for it before concluding it has no canonical definition"
+ )
+ return listing
-def _how_a_run_works_head(*, data_catalog_enabled: bool) -> str:
+
+def _how_a_run_works_head(*, data_catalog_enabled: bool, governed_metric_names: Sequence[str] | None = None) -> str:
if not data_catalog_enabled:
return _HOW_A_RUN_WORKS_HEAD
- return _HOW_A_RUN_WORKS_HEAD + _METRICS_CATALOG_RULE
+ if governed_metric_names is None:
+ return _HOW_A_RUN_WORKS_HEAD + _METRICS_CATALOG_RULE
+ if not governed_metric_names:
+ return _HOW_A_RUN_WORKS_HEAD + _METRICS_CATALOG_EMPTY
+ return _HOW_A_RUN_WORKS_HEAD + _METRICS_CATALOG_PREFETCHED.format(
+ listing=_governed_metric_listing(governed_metric_names)
+ )
# The close-out step is identical on every channel bar the word for what the run produces, and it is
@@ -674,13 +712,17 @@ Respond at end_turn with a single JSON object matching this schema:
def _signal_tail_sections(
- *, followup_section: str, structured_output_section: str = "", data_catalog_enabled: bool = False
+ *,
+ followup_section: str,
+ structured_output_section: str = "",
+ data_catalog_enabled: bool = False,
+ governed_metric_names: Sequence[str] | None = None,
) -> 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 likewise
per-run composed (empty when the config carries no schema)."""
return [
- f"{_how_a_run_works_head(data_catalog_enabled=data_catalog_enabled)}\n{_HOW_A_RUN_WORKS_SIGNAL_STEPS}",
+ f"{_how_a_run_works_head(data_catalog_enabled=data_catalog_enabled, governed_metric_names=governed_metric_names)}\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,
@@ -710,6 +752,7 @@ def _report_tail_sections(
github_read_access: bool = False,
structured_output_section: str = "",
data_catalog_enabled: bool = False,
+ governed_metric_names: Sequence[str] | None = None,
) -> list[str]:
"""Report-channel tail, tailored to the report tools the scout actually opted into.
@@ -723,7 +766,7 @@ def _report_tail_sections(
`github_read_access` appends the `gh` evidence section only when the sandbox actually got a
read-only GitHub token — every persona here can set reviewers (edit-only routes unrouted
reports), so it slots in wherever reviewer guidance lives."""
- head = _how_a_run_works_head(data_catalog_enabled=data_catalog_enabled)
+ head = _how_a_run_works_head(data_catalog_enabled=data_catalog_enabled, governed_metric_names=governed_metric_names)
if can_emit and can_edit:
how_a_run_works = f"{head}\n{_REPORT_STEPS_BOTH}\n{_REPORT_CLOSE_OUT_STEP}"
channel_sections = [
@@ -827,6 +870,7 @@ def build_run_prompt(
github_read_access: bool = False,
structured_output_schema: dict | None = None,
data_catalog_enabled: bool = False,
+ governed_metric_names: Sequence[str] | None = None,
) -> str:
"""Render the opening prompt for one scout run.
@@ -864,8 +908,11 @@ def build_run_prompt(
`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`).
+ governed-metrics catalog-first steering, and the catalog surfaces it names don't exist for
+ flag-off teams (see the note on `_METRICS_CATALOG_RULE`). `governed_metric_names` is the
+ harness-side pre-fetch of the team's approved, non-drifted metric names: a list (even empty)
+ renders the injected listing so the run is catalog-aware without a probe query, and `None`
+ means the lookup was unavailable, falling back to the prose probe-and-cache 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 —
@@ -893,6 +940,7 @@ def build_run_prompt(
github_read_access=github_read_access,
structured_output_section=structured_output_section,
data_catalog_enabled=data_catalog_enabled,
+ governed_metric_names=governed_metric_names,
)
# 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.
@@ -903,6 +951,7 @@ def build_run_prompt(
followup_section=followup_section,
structured_output_section=structured_output_section,
data_catalog_enabled=data_catalog_enabled,
+ governed_metric_names=governed_metric_names,
)
emit_tool = "scout-emit-signal"
# Slot the origin-matched improvement channel between friction reporting and the output format
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 1c63ce69fbe9..5d8c2d95e9c5 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -18,9 +18,11 @@ from croniter import CroniterError, croniter
from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.models.team.team import Team
+from posthog.models.user import User
from posthog.models.utils import uuid7
from posthog.sync import database_sync_to_async
+from products.data_catalog.backend.facade.api import approved_metric_names_for_team
from products.data_catalog.backend.facade.flags import is_data_catalog_enabled
from products.signals.backend.agent_runtime import STEP_SCOUT, resolve_agent_runtime
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
@@ -505,6 +507,20 @@ def _data_catalog_enabled_for_team(team: Team) -> bool:
return False
+def _governed_metric_names_for_team(team: Team, user_id: int) -> list[str] | None:
+ """Approved metric names for prompt injection, or None when the read fails.
+
+ Resolved as the run's acting user, the same identity the sandbox's MCP token carries, so the
+ injected listing can never be wider than what the run could have queried for itself through
+ `system.information_schema.metrics`.
+ """
+ try:
+ return approved_metric_names_for_team(team, User.objects.get(id=user_id))
+ except Exception as error:
+ capture_exception(error)
+ return None
+
+
async def _spawn_and_run(
*,
team: Team,
@@ -590,6 +606,11 @@ async def _spawn_and_run(
reasoning_effort=reasoning_effort,
)
data_catalog_enabled = await database_sync_to_async(_data_catalog_enabled_for_team, thread_sensitive=False)(team)
+ governed_metric_names = (
+ await database_sync_to_async(_governed_metric_names_for_team, thread_sensitive=False)(team, user_id)
+ if data_catalog_enabled
+ else None
+ )
prompt = build_run_prompt(
skill,
run_id=str(run_id),
@@ -597,6 +618,7 @@ async def _spawn_and_run(
started_at=started_at,
github_read_access=github_guidance,
data_catalog_enabled=data_catalog_enabled,
+ governed_metric_names=governed_metric_names,
# 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.py
index 5e1e852e61fd..a8e95cf1e03a 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -34,7 +34,13 @@ from products.signals.backend.scout_harness.derived_metadata import DERIVED_META
from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, _compute_row_hash
from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_S, failure_streak_pause_threshold
from products.signals.backend.scout_harness.model_selection import ScoutModel
-from products.signals.backend.scout_harness.prompt import _REPORT_CHARTS, HARNESS_PROMPT_VERSION, build_run_prompt
+from products.signals.backend.scout_harness.prompt import (
+ _GOVERNED_METRIC_LISTING_CAP,
+ _METRICS_CATALOG_SUPERSEDES_CACHE as _SUPERSEDES_CACHED_ENTRIES,
+ _REPORT_CHARTS,
+ HARNESS_PROMPT_VERSION,
+ build_run_prompt,
+)
from products.signals.backend.scout_harness.runner import (
SIGNALS_SCOUT_FULL_NETWORK_ENV_NAME,
SIGNALS_SCOUT_SANDBOX_ENV_NAME,
@@ -559,6 +565,45 @@ class TestPromptBuilder(BaseTest):
assert "information_schema.metrics" not in disabled
assert "data-catalog-metric-run" not in disabled
+ def test_prefetched_catalog_listing_replaces_the_probe_instruction(self) -> None:
+ LLMSkill.objects.create(team=self.team, name="signals-scout-catalog-listing", description="s", body="watch")
+ loaded = load_skill_for_run(self.team, "signals-scout-catalog-listing")
+ 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),
+ }
+ names = ["scout_cost_per_run", "scout_run_fail_pct"]
+
+ listed = build_run_prompt(loaded, **kwargs, data_catalog_enabled=True, governed_metric_names=names)
+ assert "`scout_run_fail_pct`" in listed
+ assert "`scout_cost_per_run`" in listed
+ assert "data-catalog-metric-run" in listed
+ assert "Cache the lookup outcome" not in listed
+ assert _SUPERSEDES_CACHED_ENTRIES in listed
+
+ empty = build_run_prompt(loaded, **kwargs, data_catalog_enabled=True, governed_metric_names=[])
+ assert "no approved metrics" in empty
+ assert "Cache the lookup outcome" not in empty
+ assert _SUPERSEDES_CACHED_ENTRIES in empty
+
+ fallback = build_run_prompt(loaded, **kwargs, data_catalog_enabled=True, governed_metric_names=None)
+ assert "Cache the lookup outcome" in fallback
+ assert _SUPERSEDES_CACHED_ENTRIES not in fallback
+
+ # The cap is what keeps this injection to a handful of tokens in every catalog-enabled run,
+ # and past it the listing stops being the whole catalog, so it has to say a lookup is still
+ # warranted for an unlisted measure.
+ overflowing = [f"metric_{index:03d}" for index in range(_GOVERNED_METRIC_LISTING_CAP + 3)]
+ capped = build_run_prompt(loaded, **kwargs, data_catalog_enabled=True, governed_metric_names=overflowing)
+ assert "`metric_000`" in capped
+ assert f"`metric_{_GOVERNED_METRIC_LISTING_CAP:03d}`" not in capped
+ assert "and 3 more this listing omits" in capped
+
+ flag_off = build_run_prompt(loaded, **kwargs, governed_metric_names=names)
+ assert "scout_run_fail_pct" not in flag_off
+ assert "data-catalog-metric-run" not in flag_off
+
def test_report_channel_renders_report_persona_and_guidance(self) -> None:
LLMSkill.objects.create(
team=self.team,
@@ -1033,6 +1078,54 @@ async def test_catalog_steering_reaches_the_prompt_from_the_team_flag(ateam, aer
assert ("information_schema.metrics" in captured["prompt"]) is expect_rule
+ "names,expected_marker",
+ [
+ pytest.param(["scout_run_fail_pct"], "scout_run_fail_pct", id="listing_injected"),
+ pytest.param(RuntimeError("catalog read down"), "Cache the lookup outcome", id="lookup_error_falls_back"),
+ ],
+)
+async def test_governed_listing_reaches_the_prompt_from_the_catalog(ateam, aerrors_skill, names, expected_marker):
+ session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)
+ acting_user = await sync_to_async(User.objects.create_and_join)(
+ organization=ateam.organization,
+ email=f"scout-catalog-{random.randint(1, 99999)}@posthog.com",
+ password=None,
+ )
+ 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
+
+ names_mock = MagicMock(side_effect=names) if isinstance(names, Exception) else MagicMock(return_value=names)
+ with (
+ patch("products.signals.backend.scout_harness.runner.MultiTurnSession.start", new=_capture_start),
+ patch("products.signals.backend.scout_harness.runner.is_data_catalog_enabled", return_value=True),
+ patch("products.signals.backend.scout_harness.runner.approved_metric_names_for_team", names_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=acting_user.id,
+ ),
+ ):
+ 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 expected_marker in captured["prompt"]
+ # The listing must be resolved as the run's acting user, or it could be wider than what the run
+ # could have queried for itself; the access check lives behind the facade call, so passing the
+ # user is the only part of that the runner owns.
+ assert names_mock.call_args.args == (ateam, acting_user)
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
@pytest.mark.parametrize(
diff --git a/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md b/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md
index 714f4dc475df..03f9b259cba7 100644
--- a/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md
+++ b/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md
@@ -81,6 +81,7 @@ If `$mcp_tool_call` is absent from the profile's `top_events` (or a 7-day `count
## Orient
+- Governed baseline first: when your run prompt's catalog listing shows an approved `mcp_tool_call_fail_pct` metric, run it via `data-catalog-metric-run` as the canonical project-wide failure-rate baseline and refresh `pattern:mcp_analytics:baseline` from its output. Per-tool, per-category, struggle, and latency numbers stay cookbook SQL — label them noncanonical whenever the governed baseline exists.
- `scout-scratchpad-search` (`text=mcp`) — durable steering from past runs. `pattern:` entries hold the baseline rates and the captured **regime** (hono vs external-SDK) so you don't re-probe it cold; `noise:` / `addressed:` / `dedupe:` say what's benign, fixed, or already filed; `report:` / `reviewer:` entries point at the open report for a category and who owns it.
- `scout-runs-list` (last 7d) — what prior MCP runs found and ruled out.
- `scout-project-profile-get` — confirm `$mcp_tool_call` reach off `top_events`.