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): let the research pipeline attach charts to reports (#74601)

Andrew Maguire546b44680da9
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index cb4a05457942..8810156fac11 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -456,6 +456,8 @@ An **append-only, attributed, schema-validated log of the work done on a report*
Scouts write them via `charts` on `emit_report` / `edit_report`. On an edit `charts` is the report's whole set — it replaces what was there, the way `summary` replaces the summary, and omitting it leaves the existing charts alone. On the emit path the safety judge sees a report's chart titles, captions, and queries alongside its prose, so an injected chart is suppressed with the report. The edit path judges nothing today — not title, summary, notes, reviewers, or charts — so a chart set by a later edit reaches the reader unscreened, exactly as an edited summary does.
+The main **agentic research pipeline** authors charts too, so every signal source that funnels through it (not just scouts) can produce a visual report. The research agent's presentation step (`report_generation/research.py`) returns `charts` alongside the title and summary; the caller activity (`temporal/agentic/report.py`) replaces `SignalReport.charts` with them, and a re-research is shown the report's current charts to keep, refresh, or drop. It is gated per team by the `signals-report-charts` flag (`_team_report_charts_enabled`, on in DEBUG) so it ships dark on the fleet-wide path. Unlike the scout emit path, these charts are **not** safety-judged: the pipeline judge screens the input signals before research runs, so it never sees research-authored charts — the same as it never sees the research-authored title/summary, which are agent output from already-screened signals.
+
**Attribution.** Every write helper (`append_status` / `add_log` / `append_finding` / `append_dismissal`) requires an `ArtefactAttribution` — exactly one of `from_user(user_id)` / `from_task(task_id)` / `system()` — so no write site can silently skip it. Agent writes are attributed deterministically: sandbox provisioning bakes the agent's task id into an `X-PostHog-Task-Id` header on its MCP config, forwarded by the MCP server on every API call; the LLM never handles its own task id. The header is attribution metadata, not an authorization boundary (the token is team-scoped and the named task must belong to the same team).
**Write surface.** `SignalReportArtefactViewSet` exposes POST / PATCH / DELETE for any type (a status write appends a new latest-wins row), the bespoke `suggested_reviewers` PUT, and a `diff` action that renders a `commit` artefact's branch against the repository default branch via `GitHubIntegration.get_diff` (GitHub compare API, validated repo/ref/sha). All gated by `scope_object = "task"` (`task:write`). Custom agents queue artefacts during a run via `CustomSignalAgent.register_artefact`, persisted in the report's transaction and attributed to the agent's task — except `commit` (written automatically by the signed-commit harness) and `task_run` (written by report persistence), which never need registering there.
diff --git a/products/signals/backend/management/commands/analyze_report.py b/products/signals/backend/management/commands/analyze_report.py
index 534c0d47e7ec..2a9e7e115576 100644
--- a/products/signals/backend/management/commands/analyze_report.py
+++ b/products/signals/backend/management/commands/analyze_report.py
@@ -244,6 +244,9 @@ class Command(BaseCommand):
previous_report_research=previous_report_research,
verbose=verbose,
output_fn=self._flushing_write,
+ # Local debug tool: always exercise the chart-authoring path, mirroring the
+ # DEBUG-on default of the production `signals-report-charts` gate.
+ charts_enabled=True,
)
)
@@ -251,6 +254,9 @@ class Command(BaseCommand):
self.stdout.write(self.style.SUCCESS("=== Research Result ==="))
self.stdout.write(f"Title: {result.title}")
self.stdout.write(f"Summary: {result.summary}")
+ self.stdout.write(f"Charts: {len(result.charts)}")
+ for chart in result.charts:
+ self.stdout.write(f" - {chart.chart_id}: {chart.title}")
actionability = result.effective_actionability()
priority = result.effective_priority()
self.stdout.write(f"Actionability: {actionability.actionability}")
diff --git a/products/signals/backend/report_charts.py b/products/signals/backend/report_charts.py
index d8a91d93d92b..e00587ccb422 100644
--- a/products/signals/backend/report_charts.py
+++ b/products/signals/backend/report_charts.py
@@ -275,3 +275,33 @@ class ReportChart(BaseModel):
def chart_batch_query_chars(charts: Sequence[ReportChart]) -> int:
"""Serialized size of a set of charts' queries, for `MAX_REPORT_CHARTS_QUERY_CHARS`."""
return sum(len(json.dumps(chart.query)) for chart in charts)
+
+
+def chart_batch_error(charts: Sequence[ReportChart]) -> str | None:
+ """Why a set of charts can't be stored together, or None if it can.
+
+ A `ReportChart` field validator already vets each chart's shape; this is the whole-set contract
+ no single chart can enforce — the count cap, the combined query-size budget, and `chart_id`
+ uniqueness. All three are decided from the payload alone, so a caller writing charts from any
+ authoring surface (a scout tool, the research pipeline) shares one contract rather than
+ restating the checks. Uniqueness matters because the inbox indexes a report's charts by id: two
+ charts under one id collapse to whichever is last, so a `chart:` reference draws the wrong query
+ and the other chart silently vanishes.
+ """
+ if len(charts) > MAX_REPORT_CHARTS:
+ return f"a report accepts at most {MAX_REPORT_CHARTS} charts ({len(charts)})"
+ total_query_chars = chart_batch_query_chars(charts)
+ if total_query_chars > MAX_REPORT_CHARTS_QUERY_CHARS:
+ # Echo the actual total, not just the limit: a scout agent reads this error off its
+ # emit_report / edit_report tool call and needs to know how far over budget it is to trim
+ # and retry. The total is already computed for the comparison, so including it is free.
+ return (
+ f"the charts' queries total {total_query_chars} characters, "
+ f"the limit is {MAX_REPORT_CHARTS_QUERY_CHARS} across one report"
+ )
+ seen: set[str] = set()
+ for chart in charts:
+ if chart.chart_id in seen:
+ return f"duplicate chart_id {chart.chart_id!r} — chart_ids must be unique within a report"
+ seen.add(chart.chart_id)
+ return None
diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.md
index 0b153307afb4..e0796000b183 100644
--- a/products/signals/backend/report_generation/AGENTS.md
+++ b/products/signals/backend/report_generation/AGENTS.md
@@ -25,6 +25,7 @@ the safety judge first, then calls into this flow via a Temporal activity if the
- priority assessment when actionable
- final report title
- very short factual summary
+ - optional charts (see below), when the team is opted in
The repository used for research is tracked separately via the `repo_selection` artefact.
- `fixtures/analyze_report_funnel_research_output.json`
Saved previous research output used by local `update` testing.
@@ -69,6 +70,41 @@ This module is intentionally prompt-orchestration only.
Production persistence is handled outside `run_multi_turn_research()`, in the caller activity,
so this module stays isolated from report DB writes.
+### Charts
+
+The presentation step can also author `charts` — query nodes the inbox draws on the report body,
+so a finding about a metric move is visible next to the sentence describing it. They are the same
+`SignalReport.charts` the scout channel writes (schema + bounds in `report_charts.py`), authored in
+the same structured response as the title/summary so the summary can place one with a
+`[label](chart:<id>)` markdown link. This is the pipeline counterpart of the scout `emit_report`
+charts path.
+
+- **Opt-in.** Gated per team by the `signals-report-charts` flag (`_team_report_charts_enabled` in
+ the caller activity; on in DEBUG). When off, both the chart guidance and the `charts` field itself
+ are dropped from the presentation prompt (chart-free schema), and the caller drops anything the
+ model returns anyway — so an un-opted team is never shown or steered toward charts on the delicate
+ fleet-wide path.
+- **Replace, not append.** `charts` is the report's whole set. On a re-research the previous charts
+ are shown back as context (loaded from `SignalReport.charts` by `_load_previous_research`); the run
+ keeps, refreshes, or drops them and the caller replaces the column with the result.
+- **Persistence is atomic with the prose.** `run_agentic_report_activity` only _resolves_ the charts
+ payload (`_resolve_report_charts_payload`) and returns it on `RunAgenticReportOutput.charts`; the
+ column is written by the transition activity that also writes the title/summary
+ (`mark_report_ready_activity` / `mark_report_pending_input_activity`), inside the same
+ `transition_to` transaction. So charts and the prose they illustrate land together — a failed run
+ or the not-actionable reset (neither writes the new prose) leaves the charts alone by construction,
+ with no separate-transaction window. The resolver yields three outcomes: a valid non-empty set
+ (replace the column); `None` when the team isn't opted in **or** the run authored no charts (leave
+ the column alone — the presentation field is optional, so an omitted key and a deliberate "drop
+ everything" both arrive empty and are indistinguishable, and wiping user-visible charts on that
+ ambiguity is the worse failure, so the pipeline never auto-clears to zero; a human can clear from
+ the inbox); and `[]` when the set busts the whole-set caps (clear, so a stale set can't sit under
+ the new summary).
+- **Not safety-judged.** The pipeline's safety judge screens the input signals before research runs,
+ so it never sees research-authored charts — the same as it never sees research-authored
+ title/summary. Charts are agent output derived from already-screened signals, consistent with that
+ model. (This differs from the scout emit path, where charts and prose are judged together.)
+
The caller activity passes `has_business_knowledge=True` when the team's business knowledge
product is both feature-flagged on and has at least one READY source (via
`products.business_knowledge.backend.logic.is_available_for_team`). When true, the research
@@ -129,7 +165,8 @@ and optional thought chunks.
summary/title describe what the report is about;
actionability/priority explain what to do and how urgent it is.
- If you change the output shape of `ReportResearchOutput`,
- update `fixtures/analyze_report_funnel_research_output.json` too.
+ update `fixtures/analyze_report_funnel_research_output.json` and
+ `fixtures/insight_scene_logic_mode_property_bug.json` too.
- Keep persistence out of `run_multi_turn_research()`.
If production needs new report artefacts or state transitions, do that in the caller activity/workflow.
- If you change how local debug commands exercise this flow,
diff --git a/products/signals/backend/report_generation/fixtures/analyze_report_funnel_research_output.json b/products/signals/backend/report_generation/fixtures/analyze_report_funnel_research_output.json
index e8fb7187b5dc..214bba530279 100644
--- a/products/signals/backend/report_generation/fixtures/analyze_report_funnel_research_output.json
+++ b/products/signals/backend/report_generation/fixtures/analyze_report_funnel_research_output.json
@@ -12,6 +12,7 @@
"result": {
"title": "Funnel insights lack time-based comparison and statistical options",
"summary": "The signals point to missing funnel analysis capabilities rather than a broken funnel engine. The consistent gaps are native time-period comparison, fixed Time to Convert histogram buckets, and percentile-based conversion-time summaries, while the onboarding drop-off report could not be verified without customer data.",
+ "charts": [],
"new_artefacts": [],
"old_artefacts": [
{
diff --git a/products/signals/backend/report_generation/fixtures/insight_scene_logic_mode_property_bug.json b/products/signals/backend/report_generation/fixtures/insight_scene_logic_mode_property_bug.json
index 95980bf7a20c..023087fb79db 100644
--- a/products/signals/backend/report_generation/fixtures/insight_scene_logic_mode_property_bug.json
+++ b/products/signals/backend/report_generation/fixtures/insight_scene_logic_mode_property_bug.json
@@ -7,6 +7,7 @@
"result": {
"title": "fix(backups): correct 'succesful' typo in docstring",
"summary": "The docstring of the `_get_base_backup` function in `posthog/dags/backups.py` (line 346) misspells 'successful' as 'succesful'. This is a single-word typo in a docstring — no code behavior is affected.",
+ "charts": [],
"old_artefacts": [],
"new_artefacts": [
{
diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.py
index a5326a8c2b39..cb9c19484ddf 100644
--- a/products/signals/backend/report_generation/research.py
+++ b/products/signals/backend/report_generation/research.py
@@ -18,6 +18,10 @@ from products.signals.backend.artefact_schemas import (
SignalFinding,
)
+# Dependency-light on purpose (see its module docstring): safe to import here without dragging
+# `posthog.schema` onto the research path.
+from products.signals.backend.report_charts import MAX_REPORT_CHARTS, ReportChart
+
# Deferred: importing temporal.types here runs the signals temporal package __init__, which
# eager-imports agentic -> report -> back into this module, forming a circular import.
# SignalData is annotation-only (this module uses `from __future__ import annotations`); the one
@@ -82,6 +86,16 @@ Hard rules:
- Separate sections and paragraphs with blank lines; you don't need any special line-break syntax.
"""
)
+ charts: list[ReportChart] = Field(
+ default_factory=list,
+ description=(
+ "Charts the inbox draws on the report, so a finding about a metric move is visible next "
+ "to the sentence describing it. Optional — attach one only when the shape of the data is "
+ "the point. Reference a chart from the summary as a markdown link with a `chart:` target "
+ "(e.g. `[Daily signups](chart:signups-drop)`) to place it inline; an unreferenced chart "
+ "renders after the prose. Leave empty when a chart would only restate a number."
+ ),
+ )
@field_validator("title", "summary")
@classmethod
@@ -98,6 +112,11 @@ ResearchArtefactContent = SignalFinding | ActionabilityAssessment | PriorityAsse
class ReportResearchOutput(BaseModel):
title: str = Field(description="Generated report title.")
summary: str = Field(description="Generated factual report summary.")
+ charts: list[ReportChart] = Field(
+ default_factory=list,
+ description="Charts the summary illustrates itself with. The report's whole set — the caller "
+ "replaces `SignalReport.charts` with it, the way it replaces title/summary.",
+ )
research_task_id: str | None = Field(
default=None,
description="UUID of the sandbox task that performed the research; artefacts persisted from "
@@ -320,6 +339,38 @@ def _render_previous_presentation_context(previous_title: str | None, previous_s
return "\n".join(parts)
+# Chart-authoring guidance for the presentation step, adapted from the scout channel's
+# `_REPORT_CHARTS`. Rendered only when the team has the report-charts capability — and when it isn't,
+# the `charts` field is dropped from the schema too (see `build_report_presentation_prompt`), so a
+# team that isn't opted in is never shown or steered toward charts on the delicate fleet-wide path.
+_REPORT_CHARTS_GUIDANCE = f"""## Attaching charts
+
+You may attach charts under `charts`, which the inbox draws on the report itself so a data move is visible next to the sentence describing it rather than a number the reader has to go and reproduce. This is optional and usually the wrong call — attach a chart only when the *shape* of the data is the point (a trend that broke, a distribution that shifted, a funnel step that collapsed). A chart restating one number the summary already gives is noise; write the number. Most reports should carry zero charts.
+
+- **Each chart is `chart_id` + `title` + `query`.** `chart_id` is your own slug (lowercase letters, numbers, `_`, `-`); `title` is the heading above it; `query` is a query node — `InsightVizNode` (an ad-hoc product-analytics chart), `DataVisualizationNode` (a `HogQLQuery` source, plus `display` and `chartSettings` for a graph rather than a result table), or `SavedInsightNode` (an existing insight by `shortId`). Any other kind is refused. Add a `caption` when there's a specific thing to look at.
+- **A graph from SQL needs its axes named.** Setting `display` on a `DataVisualizationNode` without `chartSettings` draws every row at one x position instead of a series: `chartSettings.xAxis.column` and `chartSettings.yAxis[].column` say which columns of your result are which, naming them exactly as your `SELECT` aliases them. A daily count aliased `SELECT toDate(timestamp) AS day, count() AS occurrences` needs `"chartSettings": {{"xAxis": {{"column": "day"}}, "yAxis": [{{"column": "occurrences"}}]}}`. Leave `display` off entirely and the node renders the result table instead, which reads better than a chart for a handful of rows.
+- **Only attach a query you actually ran this session.** A well-formed node of an allowed kind holding a broken query is stored without complaint and then fails to draw when the reader opens the report, with nothing to tell you. So build each chart from a query you already executed via the PostHog MCP tools (`query-run`, `execute-sql`, or read the exact node off an existing insight) — never one written from memory.
+- **A chart renders data, it does not run code.** HogVM `bytecode`, a nested `HogQuery`, `sendRawQuery`, and a nested `SuggestedQuestionsQuery` are each refused wherever they sit in the node. A warehouse query is fine through HogQL — keep `connectionId`, drop `sendRawQuery`.
+- **Place it from the summary.** A markdown link with a `chart:` target — `[Daily signups](chart:signups-drop)` — draws the chart at that point in the body; reference it once. A chart you never reference still renders, after the prose. Two references in one paragraph sit side by side.
+- **Prose must stand on its own.** The report is also delivered to Slack, where nothing draws a chart and a reference degrades to its plain label. State the finding in words and let the chart corroborate it — never "the chart below shows the drop".
+- **Pin the window** to absolute dates wherever the node supports it, so the reader sees the data you wrote about rather than whatever a relative range resolves to days later.
+- **At most {MAX_REPORT_CHARTS} per report**, far more than any report should use — three charts a reader studies beat a dozen they scroll past.
+- **`charts` is the report's whole set.** It replaces whatever the report showed before, the way title and summary do. To keep a chart across a re-research, send it again; drop one by leaving it out."""
+
+
+def _render_previous_charts_context(previous_charts: list[ReportChart]) -> str:
+ if not previous_charts:
+ return ""
+ rendered = json.dumps([chart.model_dump(mode="json") for chart in previous_charts], indent=2)
+ return (
+ "## Charts this report already shows\n\n"
+ "Re-send the ones still worth showing (refreshing their window to the data you researched "
+ "this run), drop the ones the latest findings make stale, and add any the new evidence calls "
+ "for. Omitting a chart removes it.\n\n"
+ f"```json\n{rendered}\n```"
+ )
+
+
def _render_signal_for_research(signal: SignalData, index: int, total: int) -> str:
"""Render a single signal for the research prompt, with numbering."""
from products.signals.backend.temporal.types import _render_extra_to_text # noqa: PLC0415
@@ -581,14 +632,32 @@ def build_report_presentation_prompt(
*,
previous_title: str | None = None,
previous_summary: str | None = None,
+ previous_charts: list[ReportChart] | None = None,
+ charts_enabled: bool = False,
) -> str:
- schema = json.dumps(ReportPresentationOutput.model_json_schema(), indent=2)
+ schema_dict = ReportPresentationOutput.model_json_schema()
+ if not charts_enabled:
+ # Emit a chart-free schema when the team isn't opted in: drop the `charts` field (and the
+ # now-unreferenced chart type defs) so the model is never shown — let alone told to fill —
+ # a field whose description mentions authoring `chart:` links. Combined with the caller
+ # dropping any charts anyway, an un-opted report can never carry one.
+ schema_dict.get("properties", {}).pop("charts", None)
+ schema_dict.pop("$defs", None)
+ schema = json.dumps(schema_dict, indent=2)
previous_presentation_context = _render_previous_presentation_context(previous_title, previous_summary)
+ # The charts guidance (and any previous-charts context) is rendered only when the team is opted in.
+ charts_sections = ""
+ if charts_enabled:
+ previous_charts_context = _render_previous_charts_context(previous_charts or [])
+ charts_sections = "\n\n" + _REPORT_CHARTS_GUIDANCE
+ if previous_charts_context:
+ charts_sections += "\n\n" + previous_charts_context
+
return f"""Now write the final **report title and summary** based on your research across all {total_signals} signal(s).
Style rules:
-{previous_presentation_context}
+{previous_presentation_context}{charts_sections}
Respond with a JSON object matching this schema:
@@ -667,6 +736,7 @@ async def run_multi_turn_research(
has_business_knowledge: bool = False,
resolved_report_title: str | None = None,
resolved_report_summary: str | None = None,
+ charts_enabled: bool = False,
) -> ReportResearchOutput:
"""Orchestrate a multi-turn sandbox session that investigates each signal individually."""
from products.tasks.backend.facade import api as tasks_facade
@@ -825,6 +895,8 @@ async def run_multi_turn_research(
total,
previous_title=title or (previous_report_research.title if previous_report_research else None),
previous_summary=summary or (previous_report_research.summary if previous_report_research else None),
+ previous_charts=previous_report_research.charts if previous_report_research else None,
+ charts_enabled=charts_enabled,
)
presentation_result = await session.send_followup(
presentation_prompt,
@@ -848,6 +920,10 @@ async def run_multi_turn_research(
return ReportResearchOutput(
title=presentation_result.title,
summary=presentation_result.summary,
+ # Only carry charts for an opted-in team, regardless of what the model returned — a redundant
+ # guard alongside the gated schema/guidance, so the capability can't leak even if a future
+ # change reintroduces the field into a disabled prompt.
+ charts=presentation_result.charts if charts_enabled else [],
research_task_id=str(session.task.id),
old_artefacts=old_artefacts,
new_artefacts=new_artefacts,
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index c95324268bf7..5106438d3f67 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -47,13 +47,7 @@ from products.signals.backend.artefact_schemas import (
SuggestedReviewers,
)
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalScoutRun
-from products.signals.backend.report_charts import (
- MAX_REPORT_CHARTS,
- MAX_REPORT_CHARTS_QUERY_CHARS,
- ChartSize,
- ReportChart,
- chart_batch_query_chars,
-)
+from products.signals.backend.report_charts import ChartSize, ReportChart, chart_batch_error
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
@@ -235,10 +229,7 @@ def _build_charts(charts: list[ReportChartInput] | None) -> list[ReportChart]:
"""
if not charts:
return []
- if len(charts) > MAX_REPORT_CHARTS:
- raise InvalidScoutReportError(f"a report accepts at most {MAX_REPORT_CHARTS} charts ({len(charts)})")
built: list[ReportChart] = []
- seen: set[str] = set()
for chart in charts:
try:
content = ReportChart(
@@ -250,16 +241,10 @@ def _build_charts(charts: list[ReportChartInput] | None) -> list[ReportChart]:
)
except ValidationError as exc:
raise InvalidScoutReportError(f"invalid chart {chart.chart_id!r}: {exc}")
- if content.chart_id in seen:
- raise InvalidScoutReportError(f"duplicate chart_id {content.chart_id!r} in the same call")
- seen.add(content.chart_id)
built.append(content)
- total_query_chars = chart_batch_query_chars(built)
- if total_query_chars > MAX_REPORT_CHARTS_QUERY_CHARS:
- raise InvalidScoutReportError(
- f"the charts' queries total {total_query_chars} characters, the limit is "
- f"{MAX_REPORT_CHARTS_QUERY_CHARS} across one report"
- )
+ # Whole-set checks (count, combined query size, id uniqueness) live in the shared validator.
+ if batch_error := chart_batch_error(built):
+ raise InvalidScoutReportError(batch_error)
return built
diff --git a/products/signals/backend/scout_report/__init__.py b/products/signals/backend/scout_report/__init__.py
index 610677b0f0af..4c5b924e1194 100644
--- a/products/signals/backend/scout_report/__init__.py
+++ b/products/signals/backend/scout_report/__init__.py
@@ -6,8 +6,8 @@ pipeline. This package is the sanctioned write service the harness tools (Phase
code never touches `SignalReport` or the embeddings pipeline directly.
"""
+from products.signals.backend.report_charts import MAX_REPORT_CHARTS
from products.signals.backend.scout_report.persistence import (
- MAX_REPORT_CHARTS,
MAX_REPORT_SIGNALS,
InvalidScoutReportError,
PersistedScoutReport,
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index ddbe969cabd1..120fa110f8ce 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -51,12 +51,7 @@ from products.signals.backend.artefact_schemas import (
TaskRunArtefact,
)
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalScoutRun
-from products.signals.backend.report_charts import (
- MAX_REPORT_CHARTS,
- MAX_REPORT_CHARTS_QUERY_CHARS,
- ReportChart,
- chart_batch_query_chars,
-)
+from products.signals.backend.report_charts import ReportChart, chart_batch_error
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
from products.signals.backend.scout_harness.tools.emit import SCOUT_SIGNAL_WEIGHT, SOURCE_PRODUCT, SOURCE_TYPE
@@ -158,10 +153,8 @@ def create_scout_report(
`signal_count`/`total_weight`; it just stays invisible with no indexed evidence.
"""
_validate_create_inputs(title, summary, signals)
- if len(charts) > MAX_REPORT_CHARTS:
- raise InvalidScoutReportError(f"a report accepts at most {MAX_REPORT_CHARTS} charts ({len(charts)})")
- if chart_batch_query_chars(charts) > MAX_REPORT_CHARTS_QUERY_CHARS:
- raise InvalidScoutReportError(f"the charts' queries exceed {MAX_REPORT_CHARTS_QUERY_CHARS} characters in total")
+ if batch_error := chart_batch_error(charts):
+ raise InvalidScoutReportError(batch_error)
# Defense-in-depth: refuse to author against a run another team owns, so the tally write below
# can't corrupt a foreign team's `emitted_report_ids`. The harness tool already gates this with
# `_assert_team_owns_run`; this guards a future direct caller that bypasses it (mirrors `emit`).
@@ -390,10 +383,8 @@ def set_report_charts(
if not charts:
return False
_validate_report_id(report_id)
- if len(charts) > MAX_REPORT_CHARTS:
- raise InvalidScoutReportError(f"a report accepts at most {MAX_REPORT_CHARTS} charts ({len(charts)})")
- if chart_batch_query_chars(charts) > MAX_REPORT_CHARTS_QUERY_CHARS:
- raise InvalidScoutReportError(f"the charts' queries exceed {MAX_REPORT_CHARTS_QUERY_CHARS} characters in total")
+ if batch_error := chart_batch_error(charts):
+ raise InvalidScoutReportError(batch_error)
payload = [chart.model_dump(mode="json") for chart in charts]
with transaction.atomic():
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index 68cbc28b9843..61c1f89b0a40 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -1,6 +1,7 @@
from dataclasses import dataclass
-from typing import TypeVar
+from typing import Any, TypeVar
+from django.conf import settings
from django.db import transaction
import structlog
@@ -9,6 +10,7 @@ import posthoganalytics
from pydantic import BaseModel, ValidationError
from posthog.models.team.team import Team
+from posthog.ph_client import feature_enabled_or_false
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.scoped import scoped_temporal
@@ -19,6 +21,7 @@ from products.signals.backend.agent_runtime import STEP_RESEARCH, resolve_agent_
from products.signals.backend.artefact_schemas import ArtefactContent, RelatedTo, SuggestedReviewers
from products.signals.backend.auto_start import ReviewerContent, maybe_autostart_implementation_task
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
+from products.signals.backend.report_charts import ReportChart, chart_batch_error
from products.signals.backend.report_generation.research import (
ActionabilityAssessment,
ActionabilityChoice,
@@ -59,6 +62,11 @@ class RunAgenticReportOutput:
explanation: str
already_addressed: bool
repository: str
+ # Resolved chart payload for `SignalReport.charts`: the JSON set to store, `[]` to clear, or
+ # `None` to leave the column untouched. Applied by the transition activity that writes the
+ # matching title/summary, so charts and their prose land in one transaction. Defaults to `None`
+ # (the safe skip value) so an older workflow history that predates this field replays cleanly.
+ charts: list[dict[str, Any]] | None = None
_ArtefactContentT = TypeVar("_ArtefactContentT", bound=BaseModel)
@@ -81,7 +89,7 @@ def _parse_artefact_content(
async def _load_previous_research(report_id: str) -> ReportResearchOutput | None:
"""Reconstruct the previous report state."""
- report = await SignalReport.objects.filter(id=report_id).only("title", "summary").afirst()
+ report = await SignalReport.objects.filter(id=report_id).only("title", "summary", "charts").afirst()
if report is None or not report.title or not report.summary:
logger.info(
"load previous research: no report or missing title/summary, treating as first run",
@@ -131,12 +139,29 @@ async def _load_previous_research(report_id: str) -> ReportResearchOutput | None
return ReportResearchOutput(
title=report.title,
summary=report.summary,
+ # Shown to the re-research as the charts it may keep/refresh/drop. Parsed tolerantly: a stored
+ # chart that no longer validates (a tightened schema, a legacy shape) is dropped from the
+ # context rather than failing the run — the agent just won't be offered that one to re-send.
+ charts=_parse_stored_charts(report.charts, report_id),
# Reconstructed from already-persisted artefacts, so everything is "old" — a re-research that
# reuses these writes nothing; only what it changes lands in new_artefacts.
old_artefacts=[*findings, actionability, *([priority] if priority else [])],
)
+def _parse_stored_charts(raw: object, report_id: str) -> list[ReportChart]:
+ """Best-effort parse of a report's stored `charts` JSON into `ReportChart`s, skipping bad rows."""
+ if not isinstance(raw, list):
+ return []
+ parsed: list[ReportChart] = []
+ for entry in raw:
+ try:
+ parsed.append(ReportChart.model_validate(entry))
+ except ValidationError:
+ logger.warning("skipping unparseable stored chart", report_id=report_id)
+ return parsed
+
+
async def _load_resolved_report_context(team_id: int, report_id: str) -> tuple[str | None, str | None]:
"""Title/summary of the resolved report this one recurred from, if any.
@@ -243,6 +268,11 @@ def _append_agentic_report_artefacts(*, team_id: int, report_id: str, artefacts:
# write path, routing each type to its append semantics) in one transaction; the caller
# orchestrates auto-start explicitly, so appends opt out of the model's auto-start
# re-evaluation hook.
+ #
+ # Charts are NOT written here: they are report content that must land in the same transaction as
+ # the title/summary they illustrate, which a later activity writes (`mark_report_ready` /
+ # `mark_report_pending_input`). The research activity only resolves the payload; see
+ # `_resolve_report_charts_payload` and `RunAgenticReportOutput.charts`.
with transaction.atomic():
for draft in artefacts:
SignalReportArtefact.append(
@@ -254,8 +284,37 @@ def _append_agentic_report_artefacts(*, team_id: int, report_id: str, artefacts:
)
+def _resolve_report_charts_payload(
+ charts: list[ReportChart], charts_enabled: bool, *, report_id: str, team_id: int
+) -> list[dict[str, Any]] | None:
+ """Resolve an authored chart set to what a report's `charts` column should become, or `None` to
+ leave it untouched. The transition activity that writes the title/summary applies this atomically.
+
+ Three cases, because the model's output is untrusted and the presentation `charts` field is optional:
+ - a valid non-empty set → its JSON payload (replace the column).
+ - not opted in, or an *empty* set → `None` (leave the column alone). An omitted key and a
+ deliberate "drop everything" both arrive empty and are indistinguishable, so wiping
+ user-visible charts on that ambiguity is refused — the pipeline never auto-clears to zero (a
+ human can clear from the inbox).
+ - a cap-busting set (too many, too large, or a duplicate id the agent produced) → `[]` (clear),
+ so a stale set can't sit under the run's new summary; any `chart:` link then degrades to a label.
+ """
+ if not charts_enabled or not charts:
+ return None
+ batch_error = chart_batch_error(charts)
+ if batch_error:
+ logger.warning(
+ "clearing report charts: %s", batch_error, report_id=report_id, team_id=team_id, chart_count=len(charts)
+ )
+ return []
+ return [chart.model_dump(mode="json") for chart in charts]
+
+
async def _persist_agentic_report_artefacts(
- team_id: int, report_id: str, result: ReportResearchOutput, repo_selection: RepoSelectionResult
+ team_id: int,
+ report_id: str,
+ result: ReportResearchOutput,
+ repo_selection: RepoSelectionResult,
) -> None:
# Resolve suggested reviewers from commit hashes (always, from the effective findings —
# auto-start below needs them even when nothing is persisted this run)
@@ -348,6 +407,29 @@ def _team_has_business_knowledge(team_id: int) -> bool:
return False
+def _team_report_charts_enabled(team_id: int) -> bool:
+ """Whether the research agent may attach charts to this team's reports.
+
+ Gated by the `signals-report-charts` flag, org-keyed, evaluated fresh per run so a flip takes
+ effect immediately. Off by default everywhere so this ships dark on the fleet-wide research path;
+ on locally so `analyze_report` exercises it. Fails closed to False — a flag-service hiccup must
+ not start charting reports on a team that isn't opted in."""
+ if settings.DEBUG:
+ return True
+ try:
+ team = Team.objects.get(id=team_id)
+ return feature_enabled_or_false(
+ "signals-report-charts",
+ str(team.organization_id),
+ groups={"organization": str(team.organization_id)},
+ group_properties={"organization": {"id": str(team.organization_id)}},
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ logger.warning("report-charts availability check failed", team_id=team_id, exc_info=True)
+ return False
+
+
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
@@ -381,6 +463,9 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
reasoning_effort=agent_runtime.reasoning_effort,
)
has_bk = await database_sync_to_async(_team_has_business_knowledge, thread_sensitive=False)(input.team_id)
+ charts_enabled = await database_sync_to_async(_team_report_charts_enabled, thread_sensitive=False)(
+ input.team_id
+ )
# 2. Load previous research if this is a re-promoted report
previous_research = await _load_previous_research(input.report_id)
# 2b. Load the resolved report this one recurred from, if any, as extra research context
@@ -397,6 +482,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
has_business_knowledge=has_bk,
resolved_report_title=resolved_report_title,
resolved_report_summary=resolved_report_summary,
+ charts_enabled=charts_enabled,
)
# 4. Persist artefacts, avoid partial data from failed runs
await _persist_agentic_report_artefacts(
@@ -407,6 +493,12 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
)
actionability = result.effective_actionability()
priority = result.effective_priority()
+ # Resolve the charts payload here, but let the transition activity write it alongside the
+ # title/summary so charts and their prose land in one transaction (and never on the
+ # not-actionable reset or a failed run, which don't write the new prose).
+ charts_payload = _resolve_report_charts_payload(
+ result.charts, charts_enabled, report_id=input.report_id, team_id=input.team_id
+ )
logger.info(
"signals agentic report completed",
report_id=input.report_id,
@@ -422,6 +514,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
explanation=actionability.explanation,
already_addressed=actionability.already_addressed,
repository=repository,
+ charts=charts_payload,
)
except Exception as error:
logger.exception(
diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.py
index 6a92fef46eaf..29f2fdb48024 100644
--- a/products/signals/backend/temporal/summary.py
+++ b/products/signals/backend/temporal/summary.py
@@ -4,6 +4,7 @@ import json
import asyncio
from dataclasses import dataclass, field
from datetime import timedelta
+from typing import Any
from django.conf import settings
from django.db import transaction
@@ -104,6 +105,10 @@ class ReportDecision:
summary: str
choice: ActionabilityChoice
explanation: str
+ # Resolved chart payload to store with the title/summary (see `RunAgenticReportOutput.charts`):
+ # a JSON set, `[]` to clear, or `None` to leave the column alone. `None` for the no-repo branch,
+ # which does no research.
+ charts: list[dict[str, Any]] | None = None
@temporalio.workflow.defn(name="signal-report-summary")
@@ -271,6 +276,7 @@ class SignalReportSummaryWorkflow:
summary=agentic_result.summary,
choice=agentic_result.choice,
explanation=agentic_result.explanation,
+ charts=agentic_result.charts,
)
if decision.choice == ActionabilityChoice.NOT_ACTIONABLE:
log.info(
@@ -306,6 +312,7 @@ class SignalReportSummaryWorkflow:
reason=f"Requires human input: {decision.explanation}",
signal_count=signal_count,
source_products=source_products,
+ charts=decision.charts,
),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -322,6 +329,7 @@ class SignalReportSummaryWorkflow:
summary=decision.summary,
processed_signal_count=signal_count,
source_products=source_products,
+ charts=decision.charts,
),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -466,6 +474,10 @@ class MarkReportReadyInput:
summary: str
processed_signal_count: int
source_products: list[str] = field(default_factory=list)
+ # Chart payload to write alongside title/summary, in the same transaction: the JSON set to store,
+ # `[]` to clear, or `None` to leave the column untouched. Defaults to `None` so an older workflow
+ # history that predates this field replays cleanly.
+ charts: list[dict[str, Any]] | None = None
@temporalio.activity.defn
@@ -484,6 +496,9 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:
# Previous attempt took the re-promotion branch; preserve has_new_signals=True.
return True, report.run_count, True
updated_fields = report.transition_to(SignalReport.Status.READY, title=input.title, summary=input.summary)
+ if input.charts is not None:
+ report.charts = input.charts
+ updated_fields = [*updated_fields, "charts"]
report.save(update_fields=updated_fields)
# Loop to re-research only if new signals arrived and we're within the cap; past
# RERESEARCH_MAX_SIGNALS the report stays READY instead of re-running over a large set.
@@ -600,6 +615,8 @@ class MarkReportPendingInput:
reason: str
signal_count: int = 0
source_products: list[str] = field(default_factory=list)
+ # See MarkReportReadyInput.charts — written in the same transaction as the draft title/summary.
+ charts: list[dict[str, Any]] | None = None
@temporalio.activity.defn
@@ -617,6 +634,9 @@ async def mark_report_pending_input_activity(input: MarkReportPendingInput) -> N
updated_fields = report.transition_to(
SignalReport.Status.PENDING_INPUT, title=input.title, summary=input.summary, error=input.reason
)
+ if input.charts is not None:
+ report.charts = input.charts
+ updated_fields = [*updated_fields, "charts"]
report.save(update_fields=updated_fields)
return report.run_count, False
diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.py
index dbb8336d0de6..551ee912e759 100644
--- a/products/signals/backend/test/test_agentic_report_activity.py
+++ b/products/signals/backend/test/test_agentic_report_activity.py
@@ -16,6 +16,7 @@ from posthog.models.user_integration import UserIntegration
from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.report_charts import ReportChart
from products.signals.backend.report_generation.research import (
ActionabilityAssessment,
ActionabilityChoice,
@@ -33,12 +34,14 @@ from products.signals.backend.report_generation.select_repo import RepoSelection
from products.signals.backend.temporal.agentic.report import (
RunAgenticReportInput,
_parse_artefact_content,
+ _parse_stored_charts,
run_agentic_report_activity,
)
from products.signals.backend.temporal.agentic.select_repository import (
SelectRepositoryInput,
select_repository_activity,
)
+from products.signals.backend.temporal.summary import MarkReportReadyInput, mark_report_ready_activity
from products.signals.backend.temporal.types import SignalData
@@ -98,6 +101,64 @@ def _build_research_output() -> ReportResearchOutput:
)
+def _chart() -> ReportChart:
+ return ReportChart(
+ chart_id="signups-drop",
+ title="Daily signups",
+ query={
+ "kind": "InsightVizNode",
+ "source": {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "user_signed_up"}]},
+ },
+ )
+
+
+def _build_research_output_with_chart() -> ReportResearchOutput:
+ output = _build_research_output()
+ return output.model_copy(update={"charts": [_chart()]})
+
+
+def _build_research_output_with_duplicate_chart_ids() -> ReportResearchOutput:
+ dupe = _chart()
+ return _build_research_output().model_copy(
+ update={"charts": [dupe, dupe.model_copy(update={"title": "Same id, different chart"})]}
+ )
+
+
+_EXISTING_CHART = {
+ "chart_id": "existing",
+ "title": "Existing chart",
+ "query": {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery"}},
+}
+
+
+async def _run_activity_with_output(monkeypatch, ateam, report, output, *, charts_enabled=True):
+ monkeypatch.setattr(
+ "products.signals.backend.temporal.agentic.report.resolve_user_id_for_team",
+ lambda team_id: 1,
+ )
+ monkeypatch.setattr(
+ "products.signals.backend.temporal.agentic.report._team_report_charts_enabled",
+ lambda team_id: charts_enabled,
+ )
+
+ async def fake_run_multi_turn_research(*args, **kwargs):
+ return output
+
+ monkeypatch.setattr(
+ "products.signals.backend.temporal.agentic.report.run_multi_turn_research",
+ fake_run_multi_turn_research,
+ )
+ with patch("products.signals.backend.temporal.agentic.report.Heartbeater"):
+ return await run_agentic_report_activity(
+ RunAgenticReportInput(
+ team_id=ateam.id,
+ report_id=str(report.id),
+ signals=_build_signals(),
+ repo_selection=RepoSelectionResult(repository="posthog/posthog", reason="test"),
+ )
+ )
+
+
def _build_signals() -> list[SignalData]:
now = datetime.now(UTC)
return [
@@ -360,6 +421,87 @@ async def test_run_agentic_report_activity_persists_artefacts(monkeypatch, ateam
assert [finding["signal_id"] for finding in finding_contents] == ["sig-1", "sig-2"]
+ "name,charts_enabled,output_factory,expected",
+ [
+ # Opted-in + a valid chart → the JSON set to store.
+ ("enabled_non_empty", True, _build_research_output_with_chart, [{"chart_id": "signups-drop"}]),
+ # Not opted in → None (leave the column alone), even though the mocked run returned a chart.
+ ("disabled", False, _build_research_output_with_chart, None),
+ # Opted-in but the run authored no charts (optional field omitted / dropped) → None, never a
+ # wipe of whatever the report already showed.
+ ("enabled_empty", True, _build_research_output, None),
+ # Opted-in but the set busts the whole-set caps (duplicate id) → [] to clear, so a stale set
+ # can't sit under the new summary.
+ ("enabled_cap_bust", True, _build_research_output_with_duplicate_chart_ids, []),
+ ],
+)
+async def test_run_agentic_report_activity_resolves_charts_payload(
+ monkeypatch, ateam, name, charts_enabled, output_factory, expected
+):
+ # The activity resolves the charts payload but does not write it — the transition activity does,
+ # atomically with the title/summary (see test_mark_report_ready_activity_applies_charts). So we
+ # assert the resolved payload on the returned output rather than the report row.
+ report = await database_sync_to_async(SignalReport.objects.create)(
+ team=ateam, status=SignalReport.Status.IN_PROGRESS, signal_count=2, total_weight=1.3
+ )
+
+ result = await _run_activity_with_output(
+ monkeypatch, ateam, report, output_factory(), charts_enabled=charts_enabled
+ )
+
+ if expected is None:
+ assert result.charts is None
+ else:
+ assert [{"chart_id": chart["chart_id"]} for chart in result.charts] == expected
+
+
+ "name,charts,expected",
+ [
+ # A resolved set replaces the column, in the same transaction as the ready transition.
+ ("replace", [{"chart_id": "new", "title": "New", "query": {"kind": "InsightVizNode"}}], "replaced"),
+ # None means "leave alone" — the report keeps whatever it had.
+ ("leave_alone", None, "kept"),
+ # [] clears (the resolver's cap-bust signal) — a stale set must not survive under new prose.
+ ("clear", [], "cleared"),
+ ],
+)
+async def test_mark_report_ready_activity_applies_charts(ateam, name, charts, expected):
+ # Charts land in the same transaction as the title/summary the ready transition writes, so a
+ # failure of that activity can never leave new charts under stale prose.
+ report = await database_sync_to_async(SignalReport.objects.create)(
+ team=ateam,
+ status=SignalReport.Status.IN_PROGRESS,
+ signal_count=2,
+ total_weight=1.3,
+ charts=[_EXISTING_CHART],
+ )
+
+ await mark_report_ready_activity(
+ MarkReportReadyInput(
+ team_id=ateam.id,
+ report_id=str(report.id),
+ title="Title",
+ summary="Summary",
+ processed_signal_count=2,
+ charts=charts,
+ )
+ )
+
+ stored = await database_sync_to_async(lambda: SignalReport.objects.get(id=report.id).charts)()
+ if expected == "replaced":
+ assert [chart["chart_id"] for chart in stored] == ["new"]
+ elif expected == "kept":
+ assert stored == [_EXISTING_CHART]
+ else:
+ assert stored == []
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_run_agentic_report_activity_does_not_persist_partial_artefacts(monkeypatch, ateam):
@@ -439,6 +581,16 @@ def test_parse_artefact_content_raises_on_incompatible_schema():
_parse_artefact_content(ActionabilityAssessment, artefact, "report-1")
+def test_parse_stored_charts_skips_bad_rows_without_raising():
+ # A re-research loads a report's stored charts to show back to the agent. A row that no longer
+ # validates (a tightened schema, a legacy shape) must be dropped, not crash the re-promotion.
+ valid = _chart().model_dump(mode="json")
+ invalid = {"chart_id": "no-query"} # missing required title/query
+ assert [chart.chart_id for chart in _parse_stored_charts([valid, invalid], "report-1")] == ["signups-drop"]
+ # A non-list (a legacy null / bad column value) is treated as no charts rather than raising.
+ assert _parse_stored_charts(None, "report-1") == []
+
+
def _actionability(explanation: str) -> ActionabilityAssessment:
return ActionabilityAssessment(
explanation=explanation,
diff --git a/products/signals/backend/test/test_report_charts.py b/products/signals/backend/test/test_report_charts.py
index 15f24d27716f..de7776040f37 100644
--- a/products/signals/backend/test/test_report_charts.py
+++ b/products/signals/backend/test/test_report_charts.py
@@ -9,6 +9,7 @@ from products.signals.backend.report_charts import (
MAX_CHART_ID_LENGTH,
MAX_CHART_TITLE_LENGTH,
ReportChart,
+ chart_batch_error,
)
@@ -232,3 +233,21 @@ class TestReportCharts(SimpleTestCase):
with self.assertRaises(ValidationError):
ReportChart.model_validate({"chart_id": "ok", "title": "t", "query": {"kind": "InsightVizNode", **nested}})
+
+
+class TestChartBatchError(SimpleTestCase):
+ def _chart(self, chart_id: str) -> ReportChart:
+ return ReportChart(
+ chart_id=chart_id, title="t", query={"kind": "InsightVizNode", "source": {"kind": "TrendsQuery"}}
+ )
+
+ def test_accepts_a_set_with_distinct_ids(self) -> None:
+ assert chart_batch_error([self._chart("a"), self._chart("b")]) is None
+
+ def test_rejects_a_duplicate_chart_id(self) -> None:
+ # The inbox indexes a report's charts by id, so two under one id collapse to the last and a
+ # `chart:` reference draws the wrong query. Per-chart validation can't see this; the whole-set
+ # validator is the only guard on the pipeline authoring path.
+ error = chart_batch_error([self._chart("dupe"), self._chart("dupe")])
+ assert error is not None
+ assert "duplicate chart_id" in error
diff --git a/products/signals/backend/test/test_research_prompt.py b/products/signals/backend/test/test_research_prompt.py
index c87fe33a2732..47de60917380 100644
--- a/products/signals/backend/test/test_research_prompt.py
+++ b/products/signals/backend/test/test_research_prompt.py
@@ -2,10 +2,12 @@ from datetime import datetime
import pytest
+from products.signals.backend.report_charts import ReportChart
from products.signals.backend.report_generation.research import (
SignalFinding,
_render_signal_for_research,
build_initial_research_prompt,
+ build_report_presentation_prompt,
build_signal_investigation_prompt,
)
from products.signals.backend.temporal.types import SignalData
@@ -129,3 +131,46 @@ class TestBuildInitialResearchPrompt:
if not has_previous_finding:
assert "There is no previous finding for this signal" in initial_prompt
assert "There is no previous finding for this signal" in followup_prompt
+
+
+def _make_chart() -> ReportChart:
+ return ReportChart(
+ chart_id="signups-drop",
+ title="Daily signups",
+ query={
+ "kind": "InsightVizNode",
+ "source": {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "user_signed_up"}]},
+ },
+ )
+
+
+class TestBuildReportPresentationPrompt:
+ # A team that isn't opted in must never be steered to author charts: both the guidance section
+ # and the `charts` schema field have to stay out of the prompt on the fleet-wide path, so the
+ # model is never even shown a field whose description mentions authoring `chart:` links.
+ def test_chart_guidance_and_schema_field_only_present_when_enabled(self):
+ off = build_report_presentation_prompt(2, charts_enabled=False)
+ on = build_report_presentation_prompt(2, charts_enabled=True)
+ assert "Attaching charts" not in off
+ assert "Attaching charts" in on
+ # The schema field is dropped when disabled and present when enabled.
+ assert '"charts"' not in off
+ assert '"charts"' in on
+
+ # A DataVisualizationNode carrying `display` but no `chartSettings` stores and validates
+ # cleanly, then draws every row at a single x position instead of a series. The guidance is
+ # the only thing that tells the agent to set the axes, so losing this line means every
+ # SQL-backed chart the pipeline authors renders wrong in the reader's inbox with nothing
+ # reporting a failure. The scout channel guards the same instruction in its own example.
+ def test_chart_guidance_names_the_axes_a_sql_graph_needs(self):
+ on = build_report_presentation_prompt(2, charts_enabled=True)
+ assert "chartSettings.xAxis.column" in on
+ assert "chartSettings.yAxis[].column" in on
+
+ def test_previous_charts_context_only_rendered_when_enabled(self):
+ chart = _make_chart()
+ on = build_report_presentation_prompt(1, previous_charts=[chart], charts_enabled=True)
+ off = build_report_presentation_prompt(1, previous_charts=[chart], charts_enabled=False)
+ assert "Charts this report already shows" in on
+ assert "signups-drop" in on
+ assert "Charts this report already shows" not in off