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): autoresearch fix loop for MCP scout category reports (#72110)

Daniel Visca3545e4f57683
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index dff70a8d36cf..cfc5d02f25e7 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -84,6 +84,36 @@ def _report_meets_team_autostart_threshold(report_priority: Priority, team_defau
return _priority_rank(report_priority) <= _priority_rank(team_default_priority)
+# Reports (e.g. the MCP tool-calls scout's category reports) that define a measurable
+# optimization target end their summary with a "Fix loop metric" section; its presence flips the
+# implementation task from a one-shot fix into an iterate-until-the-metric-moves loop.
+FIX_LOOP_METRIC_MARKER = "fix loop metric"
+
+
+def _fix_loop_instructions(summary: str) -> str:
+ if FIX_LOOP_METRIC_MARKER not in summary.lower():
+ return ""
+ return (
+ "This report defines a fix-loop metric (its 'Fix loop metric' section above: the measurement "
+ "query or steps, the current baseline, and the goal direction). Treat that metric as an "
+ "autoresearch target rather than a one-shot fix: reproduce the baseline with the given "
+ "measurement steps before changing anything, then iterate — hypothesize, implement, validate "
+ "against the repo's tests and the failing examples the report cites — until the evidence says "
+ "the metric will move in the goal direction, not merely that a plausible change exists. If "
+ "validation shows the metric unmoved, try the next hypothesis instead of stopping at one "
+ "attempt. The metric must improve because the underlying behavior genuinely improves — never "
+ "by masking errors, swallowing exceptions, loosening validation, or changing how the metric is "
+ "measured. In the PR description record the baseline, the expected post-fix value, and how you "
+ "validated the change; include before/after evidence (screenshots, or a short recording where "
+ "the behavior is visual). Evidence must be safe for the target repository's visibility: show "
+ "only aggregate metric outputs (rates, counts, percentiles) or synthetic/local reproductions — "
+ "never raw telemetry rows, error messages, intent strings, or identifiers (distinct_id, "
+ "session id, email, account names), which can expose real users or customers. Images attached "
+ "to a PR are publicly and permanently readable when the repository is public, so when in "
+ "doubt, state the number instead of screenshotting the surface that produced it.\n\n"
+ )
+
+
def _build_autostart_task_description(
*, report_id: str, team_id: int, summary: str, repository: str, priority: PriorityAssessment | None
) -> str:
@@ -93,6 +123,7 @@ def _build_autostart_task_description(
f"{summary}\n\n"
f"{priority_line}"
f"Repository: {repository}\n\n"
+ f"{_fix_loop_instructions(summary)}"
"Address the symptom described above — not merely an adjacent issue you notice nearby. "
"Investigate the root cause, implement the fix, and open a PR if appropriate. "
"If your change fixes something related but does not change what the user actually observed, "
diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.py
index 63aae54fbbea..6be4e4e2b05a 100644
--- a/products/signals/backend/test/test_auto_start.py
+++ b/products/signals/backend/test/test_auto_start.py
@@ -15,6 +15,7 @@ from posthog.models.scoping import team_scope
from products.signals.backend.agent_runtime import AgentRuntime
from products.signals.backend.auto_start import (
ReviewerContent,
+ _build_autostart_task_description,
_create_implementation_task_if_absent,
_report_meets_team_autostart_threshold,
_resolve_autostart_assignee,
@@ -437,3 +438,37 @@ async def test_team_autostart_switch_gates_reviewerless_fallback(autostart_enabl
)
assert (mock_create.call_count == 1) is (autostart_enabled is not False)
+
+
+ ("summary", "expect_fix_loop"),
+ [
+ # Scout-authored metric block (the MCP scout's autoresearch handoff) → loop instructions present.
+ (
+ "MCP data-warehouse tools failing broadly.\n\n"
+ "## Fix loop metric\n\n"
+ "Metric: category error rate over the problem tools (trailing 7d).\n"
+ "Baseline: 41%. Goal: decrease.",
+ True,
+ ),
+ # Marker detection is case-insensitive — scouts write prose, not exact headings.
+ ("Tools failing.\n\nFIX LOOP METRIC: error rate 41% -> decrease via the query above.", True),
+ # No metric block → the generic one-shot prompt, no autoresearch instructions.
+ ("MCP data-warehouse tools failing broadly, fix the handler.", False),
+ ],
+)
+def test_autostart_description_appends_fix_loop_instructions_only_for_metric_reports(summary, expect_fix_loop):
+ description = _build_autostart_task_description(
+ report_id="0198c0de-0000-7000-8000-000000000001",
+ team_id=1,
+ summary=summary,
+ repository="PostHog/posthog",
+ priority=None,
+ )
+
+ assert summary in description
+ assert ("autoresearch target" in description) is expect_fix_loop
+ assert ("never by masking errors" in description) is expect_fix_loop
+ # Evidence-hygiene guardrail: fix-loop PRs may target public repos, so the prompt must forbid
+ # real telemetry (raw rows, error messages, identifiers) in before/after evidence.
+ assert ("never raw telemetry rows" in description) is expect_fix_loop
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 94b825a72367..54338f8fcaf1 100644
--- a/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md
+++ b/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md
@@ -6,8 +6,10 @@ description: >
schema, slow or context-bloating responses — groups problem tools by $mcp_tool_category (the
owning product team) and files one report per problem category listing that category's
problem tools each with a fix suggestion; falls back to one report per tool where category
- coverage is absent. Otherwise writes durable memory and closes out empty. Adapts to which
- fields the project actually captures.
+ coverage is absent. Immediately-actionable reports carry a fix-loop metric (measurement query,
+ baseline, goal) so the auto-started implementation task iterates until the number moves.
+ Otherwise writes durable memory and closes out empty. Adapts to which fields the project
+ actually captures.
compatibility: >
PostHog Signals agent (Claude sandbox). Read-only analytics + signal_scout_internal:write
(scratchpad) + signal_scout_report:write (report channel), plus execute-sql,
@@ -131,12 +133,28 @@ For a category with candidates clearing the bar, the call is **edit an existing
- **Edit** (`scout-edit-report`) when a still-live report already covers the category and it still has problem tools — the same ones, or new ones joining. `append_note` the fresh numbers (per-tool rate trends, broadening reach) and any newly-problematic tools, each with its own hypothesis; or rewrite the title/summary on a report you authored. This is the default when a match exists. `edit-report` can't change status, so if the matched report is `resolved` / `suppressed` / `failed`, don't append (it won't resurface) — author a fresh report for the relapse and repoint the `report:` key.
- **Author** (`scout-emit-report`) only when nothing live covers the category — **one report per category** (tools aggregated over the window), never one per tool or per failed call. A **report-worthy finding**: confidence ≥ 0.85, each listed tool's problem (failure / struggle / latency / bloat) high over the volume floor with reach across multiple users/sessions, and — when a Tier-2 lens is available — localized to a class/message/intent with counts in the `evidence`. Below that bar, write memory instead. The `title` names the category and the scale ("MCP data-warehouse tools need improvement: 4 tools failing/struggling"). The `summary` follows Hook (category + N problem tools + combined volume/reach + the category's share of project MCP traffic from query 9) → one short block per problem tool (the quantified problem, its shape from the Tier-2 lens, the fix hypothesis) → Recommendation. Write for an engineer on the owning team who's never seen these tools, and **state which regime the evidence came from**. Set `priority` (P0–P4) + `priority_explanation` — what the _worst_ tool would earn alone (P2 if any tool is high-rate/high-struggle, broad-reach, clearly-localized; P3 otherwise); bundling never raises priority. Set `suggested_reviewers` via `scout-members-list` (objects — a `{github_login}` or `{user_uuid}`, not bare strings; cache under `reviewer:mcp_analytics:<category>`, and check prior category reports' artefacts via `inbox-report-artefacts-list` for precedent); left empty the report reaches no one. Then choose the actionability + repo together:
- In the **hono regime** the tools live in PostHog's own MCP server, so unless this project's team owns that code, the action is an investigation / upstream report → `actionability=requires_human_input` and `repository=NO_REPO` (NO_REPO is what stops `priority`+reviewers from spawning a pointless repo-selection sandbox).
- - When the team **owns the MCP server** (the external-SDK regime, or PostHog's own project where the hono tools are in-repo) and the hypotheses are concrete code changes — a schema/description fix, a handler bug — → `actionability=immediately_actionable` with `repository="owner/repo"` (or omit `repository` to let the selector pick) to open a draft PR. A category report bundling _heterogeneous_ fixes across several tools leans `requires_human_input` even on an owned server — there's no single-PR shape; a single-tool or same-shape-systemic report can stay `immediately_actionable`.
+ - When the team **owns the MCP server** (the external-SDK regime, or PostHog's own project — the hono tools live in `PostHog/posthog`, handlers under `services/mcp/` and each product's `mcp/tools.yaml`, so `repository="PostHog/posthog"`) and the hypotheses are concrete code changes — a schema/description fix, a handler bug — → `actionability=immediately_actionable` with `repository="owner/repo"` (or omit `repository` to let the selector pick) to open a draft PR, and end the summary with the **Fix loop metric** section (next heading) so the implementation task iterates until the number moves. A category report bundling _heterogeneous_ fixes across several tools leans `requires_human_input` even on an owned server — there's no single-PR shape; a single-tool or same-shape-systemic report can stay `immediately_actionable`.
- After authoring, write the `report:mcp_analytics:category:<category>` pointer with the `report_id` so the next run edits instead of duplicating, and update the `dedupe:` entry.
- **Fold observability gaps in** (query 7): a tool that fails materially (≥50 errors) with ≥90% of failures unclassified (`$mcp_error_type IN ('', 'None')` and no message) enters its category's report as an entry whose suggestion is "add error-type/message instrumentation to its MCP handler". Only a _project-wide_ gap — failures undiagnosable across every category — is its own standalone P3 report; on a team-owned server the instrumentation change is concrete enough for `immediately_actionable` + the server repo, otherwise `requires_human_input` + `NO_REPO`.
- **Migrating legacy per-tool state**: a live per-tool report (or a `report:mcp_analytics:<tool>` key) for a tool in problem category X — if that tool is X's _only_ problem tool, edit that report in place (it is the category report de facto) and write `report:mcp_analytics:category:<X>` pointing at its id; if X has other problem tools too, author the category report noting it supersedes the legacy one, `append_note` the legacy report pointing forward, and repoint the keys. Never end a run with two live reports independently claiming the same tool.
- **Remember** if below the bar or to record what you ruled out; **skip** with a one-line note if a `noise:` / `addressed:` / `dedupe:` entry or a live inbox report already covers it.
+## Fix loop metric — the autoresearch handoff
+
+Every report filed `immediately_actionable` with a repository must end its summary with a **`Fix loop metric`** section.
+Its presence is what turns the auto-started implementation task from a one-shot patch into a measure → fix → re-measure loop, so it must stand alone for an agent that has never seen this scout or its cookbook:
+
+- **Metric** — one number matching the finding's primary lens, scoped to the category's problem tools over a trailing 7d window: failure rate for a failure finding, share of sessions with struggle (hammering / fail-then-retry) for a struggle/discoverability finding, p95 `$mcp_duration_ms` for latency.
+- **Measurement** — the exact HogQL to re-run (the cookbook query you used, inlined with the category/tool filters baked in — never a reference to "query 1"), plus the fastest local proxy: reproducing the cited failing calls against a dev MCP server, or the affected handler's unit tests.
+- **Baseline** — the value measured this run, with volume and reach ("41% of 2,013 calls across 34 users, 7d").
+- **Goal** — the direction and a concrete bar, e.g. decrease to at or below the project-wide error rate from `pattern:mcp_analytics:baseline`.
+- **Constraints** — the metric must move because the calls genuinely succeed: no masking errors, retry-hiding, swallowing exceptions, loosening schema validation to accept garbage, and no touching the `$mcp_tool_call` analytics stamping that feeds the measurement.
+- **Evidence hygiene** — the PR's before/after evidence shows aggregate metric outputs and synthetic/local reproductions only: raw telemetry rows, error messages, intent strings, and user/customer identifiers never appear in a PR or its attached images (the target repo may be public, and PR image assets stay readable forever).
+- **Intent evidence** — when `pct_with_intent` clears the bar, one line on what agents were trying to do when the tool failed (top `$mcp_intent` values), so the fix validates against real usage rather than the schema alone.
+
+The cadence math is deliberate: the daily schedule + one report per category + autostart's one-implementation-task-per-report gate means each owning team receives at most one autonomous fix PR per day, aimed at its category's worst measurable problem.
+A category whose live report already has an implementation task in flight gets an **edit** with fresh numbers, never a second actionable report.
+
## Disqualifiers (skip these)
- **Single-user / single-session** — a tool "failing" or "hammered" from one `distinct_id` or one `$session_id` is one developer, not a fleet problem. Always weigh `users` / `sessions`.