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(insights): save chart explanations of an insight (#129262)

Sam Pennington9a7202430c72
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 32e6e872aaf9..03fa34f80597 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -261,6 +261,7 @@ rules:
|HogFunctionRevision
|Hook
|Insight
+ |InsightExplanation
|InsightVariable
|Integration
|IntegrationRepositoryCacheEntry
@@ -773,6 +774,7 @@ rules:
|HogFunctionRevision
|Hook
|Insight
+ |InsightExplanation
|InsightVariable
|Integration
|IntegrationRepositoryCacheEntry
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 20623519b0f5..84f29e7462d5 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -939,6 +939,7 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"short_id",
"insightviewed",
"dashboardtile",
+ "explanations",
],
"EventDefinition": [
"eventdefinition_ptr_id",
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index a20c4ef7f456..956477e60d19 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -928,6 +928,7 @@
'dashboards',
'dive_dashboard',
'dive_dashboard_id',
+ 'explanations',
'exportedasset_set',
'filters_hash',
'funnel',
diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.py
index 1ac9b8f1f283..79181714e1ab 100644
--- a/products/product_analytics/backend/facade/api.py
+++ b/products/product_analytics/backend/facade/api.py
@@ -24,6 +24,8 @@ from posthog.models import Team, User
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.product_analytics.backend import logic
from products.product_analytics.backend.facade.contracts import (
+ ChartExplanation,
+ ChartExplanationAuthor,
InsightDashboardContext,
InsightSeries,
InsightVariableDefinition,
@@ -32,6 +34,7 @@ from products.product_analytics.backend.facade.contracts import (
ViewableInsight,
)
from products.product_analytics.backend.models.insight import Insight
+from products.product_analytics.backend.models.insight_explanation import InsightExplanation
from products.product_analytics.backend.models.insight_variable import InsightVariable
if TYPE_CHECKING:
@@ -86,6 +89,47 @@ def create_insight_variable(
return _to_variable_definition(variable)
+def _to_chart_explanation(explanation: InsightExplanation) -> ChartExplanation:
+ author = explanation.created_by
+ return ChartExplanation(
+ id=explanation.id,
+ insight_id=explanation.insight_id,
+ data=explanation.data,
+ created_by=ChartExplanationAuthor(
+ id=author.id, first_name=author.first_name, last_name=author.last_name, email=author.email
+ )
+ if author is not None
+ else None,
+ created_at=explanation.created_at,
+ )
+
+
+def create_insight_explanation(
+ *, team_id: int, insight_id: int, user_id: int, data: dict[str, Any]
+) -> ChartExplanation:
+ """Save a new chart explanation of the insight. Pass the insight's own team."""
+ return _to_chart_explanation(
+ logic.create_insight_explanation(team_id=team_id, insight_id=insight_id, user_id=user_id, data=data)
+ )
+
+
+def update_insight_explanation(
+ *, team_id: int, insight_id: int, explanation_id: UUID, user_id: int, data: dict[str, Any]
+) -> ChartExplanation | None:
+ """Replace the data of an explanation this person saved of this insight, so its link shows the fix.
+ None when they saved no explanation with this id."""
+ explanation = logic.update_insight_explanation(
+ team_id=team_id, insight_id=insight_id, explanation_id=explanation_id, user_id=user_id, data=data
+ )
+ return _to_chart_explanation(explanation) if explanation is not None else None
+
+
+def get_insight_explanation(*, team_id: int, insight_id: int, explanation_id: UUID) -> ChartExplanation | None:
+ """The saved chart explanation with this id, only when it belongs to this insight."""
+ explanation = logic.insight_explanation(team_id=team_id, insight_id=insight_id, explanation_id=explanation_id)
+ return _to_chart_explanation(explanation) if explanation is not None else None
+
+
def lock_insight_for_evaluation(*, team_id: int, insight_id: int) -> bool:
"""Hold the insight definition stable while saving a dependent evaluation.
diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.py
index 4a4d925d4592..6b396e416610 100644
--- a/products/product_analytics/backend/facade/contracts.py
+++ b/products/product_analytics/backend/facade/contracts.py
@@ -198,3 +198,28 @@ class OrganizationEventsRetention:
plan_months: int
min_months: int
max_months: int
+
+
+@dataclass(frozen=True)
+class ChartExplanationAuthor:
+ """The person who saved a chart explanation, directly or through an agent."""
+
+ id: int
+ first_name: str
+ last_name: str
+ email: str
+
+
+@dataclass(frozen=True)
+class ChartExplanation:
+ """A saved walkthrough of one saved trends insight, which a link opens beside the chart.
+
+ ``data`` is the explanation document the insight page draws. The API validates its shape on
+ the way in, and the backend stores it without reading it.
+ """
+
+ id: UUID
+ insight_id: int
+ data: dict[str, Any]
+ created_by: ChartExplanationAuthor | None
+ created_at: datetime
diff --git a/products/product_analytics/backend/logic.py b/products/product_analytics/backend/logic.py
index c7108867baea..aad96c3b6b37 100644
--- a/products/product_analytics/backend/logic.py
+++ b/products/product_analytics/backend/logic.py
@@ -10,6 +10,7 @@ from django.utils.timezone import now
from products.product_analytics.backend.facade.contracts import InsightVariableDefinition, SavedTrendsInsight
from products.product_analytics.backend.models.insight import Insight, InsightViewed
+from products.product_analytics.backend.models.insight_explanation import InsightExplanation
from products.product_analytics.backend.models.insight_variable import InsightVariable
if TYPE_CHECKING:
@@ -263,3 +264,36 @@ def get_or_create_saved_insight(
insight.deleted = False
insight.save(update_fields=["deleted"])
return insight.id, created
+
+
+def create_insight_explanation(
+ *, team_id: int, insight_id: int, user_id: int, data: dict[str, Any]
+) -> InsightExplanation:
+ return InsightExplanation.objects.for_team(team_id).create(
+ team_id=team_id, insight_id=insight_id, created_by_id=user_id, data=data
+ )
+
+
+def update_insight_explanation(
+ *, team_id: int, insight_id: int, explanation_id: UUID, user_id: int, data: dict[str, Any]
+) -> InsightExplanation | None:
+ explanation = (
+ InsightExplanation.objects.for_team(team_id)
+ .select_related("created_by")
+ .filter(insight_id=insight_id, id=explanation_id, created_by_id=user_id)
+ .first()
+ )
+ if explanation is None:
+ return None
+ explanation.data = data
+ explanation.save(update_fields=["data"])
+ return explanation
+
+
+def insight_explanation(*, team_id: int, insight_id: int, explanation_id: UUID) -> InsightExplanation | None:
+ return (
+ InsightExplanation.objects.for_team(team_id)
+ .select_related("created_by")
+ .filter(insight_id=insight_id, id=explanation_id)
+ .first()
+ )
diff --git a/products/product_analytics/backend/migrations/0012_insight_explanation.py b/products/product_analytics/backend/migrations/0012_insight_explanation.py
new file mode 100644
index 000000000000..e992cbdd9e54
--- /dev/null
+++ b/products/product_analytics/backend/migrations/0012_insight_explanation.py
@@ -0,0 +1,79 @@
+# Generated by Django 5.2.18 on 2026-10-30 12:43
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+from posthog.migration_helpers import AddForeignKeyNotValid
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1415_organizationaiterms"),
+ ("product_analytics", "0011_insight_viewed_context_fields"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="InsightExplanation",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("data", models.JSONField()),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "insight",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="explanations",
+ to="product_analytics.insight",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ AddForeignKeyNotValid(
+ model_name="insightexplanation",
+ name="insightexplanation_team_id_fk",
+ column="team_id",
+ to_table="posthog_team",
+ ),
+ AddForeignKeyNotValid(
+ model_name="insightexplanation",
+ name="insightexplanation_insight_id_fk",
+ column="insight_id",
+ to_table="posthog_dashboarditem",
+ ),
+ ]
diff --git a/products/product_analytics/backend/migrations/max_migration.txt b/products/product_analytics/backend/migrations/max_migration.txt
index 3ea33c7209a3..3347d94683a7 100644
--- a/products/product_analytics/backend/migrations/max_migration.txt
+++ b/products/product_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_insight_viewed_context_fields
+0012_insight_explanation
diff --git a/products/product_analytics/backend/models/__init__.py b/products/product_analytics/backend/models/__init__.py
index c44cb5191832..d6c8101d0a67 100644
--- a/products/product_analytics/backend/models/__init__.py
+++ b/products/product_analytics/backend/models/__init__.py
@@ -1,8 +1,10 @@
from .insight import Insight, InsightViewed
+from .insight_explanation import InsightExplanation
from .insight_variable import InsightVariable
__all__ = [
"Insight",
+ "InsightExplanation",
"InsightVariable",
"InsightViewed",
]
diff --git a/products/product_analytics/backend/models/insight_explanation.py b/products/product_analytics/backend/models/insight_explanation.py
new file mode 100644
index 000000000000..08eadf5b74c7
--- /dev/null
+++ b/products/product_analytics/backend/models/insight_explanation.py
@@ -0,0 +1,18 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel, sane_repr
+
+
+class InsightExplanation(UUIDModel, TeamScopedRootMixin):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ insight = models.ForeignKey(
+ "product_analytics.Insight", on_delete=models.CASCADE, related_name="explanations", db_constraint=False
+ )
+ data = models.JSONField()
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ __repr__ = sane_repr("id", "insight_id")
diff --git a/products/product_analytics/backend/presentation/insight_explanation.py b/products/product_analytics/backend/presentation/insight_explanation.py
new file mode 100644
index 000000000000..c9e5c62f3a4a
--- /dev/null
+++ b/products/product_analytics/backend/presentation/insight_explanation.py
@@ -0,0 +1,347 @@
+import re
+import json
+from functools import cached_property
+from typing import Any, cast
+from uuid import UUID
+
+from django.db import models
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.exceptions import NotFound
+from rest_framework.permissions import BasePermission, IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.throttling import BaseThrottle, UserRateThrottle
+from rest_framework.views import APIView
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import User
+from posthog.permissions import AccessControlPermission, APIScopePermission, TeamMemberAccessPermission
+
+from products.product_analytics.backend.facade import api
+from products.product_analytics.backend.facade.contracts import ChartExplanation, ChartExplanationAuthor
+from products.product_analytics.backend.facade.models import Insight
+
+# The text caps match the explain-chart MCP tool's input schema.
+MAX_EXPLANATION_BYTES = 300_000
+MAX_EVIDENCE_QUERY_BYTES = 10_000
+MAX_SERIES_POINTS = 5_000
+# Evidence may only link to GitHub pull requests and commits. Anything else is a query or a saved insight.
+GITHUB_CHANGE_LINK = re.compile(
+ r"https://github\.com/[A-Za-z0-9-]+/[A-Za-z0-9._-]+/(pull/\d+|commit/[0-9a-fA-F]{7,40})/?"
+)
+
+
+class InsightExplanationCreateThrottle(UserRateThrottle):
+ scope = "insight_explanation_create"
+ rate = "120/hour"
+
+
+class StoryEvidenceChartType(models.TextChoices):
+ LINE = "line", "Line"
+ BAR = "bar", "Bar"
+
+
+class ChartExplanationShape(models.TextChoices):
+ TIME_SERIES = "time_series", "Time series"
+
+
+class StoryEvidenceQueryTool(models.TextChoices):
+ QUERY_TRENDS = "query-trends", "Trends"
+ QUERY_FUNNEL = "query-funnel", "Funnel"
+ QUERY_RETENTION = "query-retention", "Retention"
+ QUERY_STICKINESS = "query-stickiness", "Stickiness"
+ QUERY_PATHS = "query-paths", "Paths"
+ QUERY_LIFECYCLE = "query-lifecycle", "Lifecycle"
+
+
+QUERY_KIND_BY_TOOL = {
+ StoryEvidenceQueryTool.QUERY_TRENDS: "TrendsQuery",
+ StoryEvidenceQueryTool.QUERY_FUNNEL: "FunnelsQuery",
+ StoryEvidenceQueryTool.QUERY_RETENTION: "RetentionQuery",
+ StoryEvidenceQueryTool.QUERY_STICKINESS: "StickinessQuery",
+ StoryEvidenceQueryTool.QUERY_PATHS: "PathsQuery",
+ StoryEvidenceQueryTool.QUERY_LIFECYCLE: "LifecycleQuery",
+}
+
+
+class StoryConfidence(models.TextChoices):
+ HIGH = "high", "High confidence"
+ MEDIUM = "medium", "Medium confidence"
+ LOW = "low", "Low confidence"
+
+
+class StoryEvidenceSeriesSerializer(serializers.Serializer):
+ name = serializers.CharField(allow_blank=True, help_text="The breakdown value or column this line draws.")
+ values = serializers.ListField(
+ child=serializers.FloatField(allow_null=True),
+ max_length=MAX_SERIES_POINTS,
+ help_text="One value per label. Null where the breakdown value has no row for that point.",
+ )
+
+
+class StoryEvidenceChartSerializer(serializers.Serializer):
+ type = serializers.ChoiceField(
+ choices=StoryEvidenceChartType.choices, help_text="How the evidence chart draws its series."
+ )
+ labels = serializers.ListField(
+ child=serializers.CharField(allow_blank=True), max_length=MAX_SERIES_POINTS, help_text="The x-axis points."
+ )
+ ticks = serializers.ListField(
+ child=serializers.CharField(allow_blank=True),
+ max_length=MAX_SERIES_POINTS,
+ required=False,
+ help_text="The axis label of each point, which leaves out a date that repeats.",
+ )
+ series = StoryEvidenceSeriesSerializer(many=True, max_length=20, help_text="The lines or bars to draw.") # type: ignore[call-arg]
+ yAxisLabel = serializers.CharField(allow_null=True, allow_blank=True, help_text="The y-axis label, if any.")
+
+
+class StoryEvidenceSerializer(serializers.Serializer):
+ text = serializers.CharField(max_length=400, help_text="One fact that supports the chapter, in one sentence.")
+ query = serializers.DictField(
+ child=serializers.JSONField(allow_null=True),
+ allow_null=True,
+ required=False,
+ help_text="The query that shows the fact. The page links to it.",
+ )
+ insightShortId = serializers.RegexField(
+ r"^[A-Za-z0-9]{8}$",
+ allow_null=True,
+ required=False,
+ help_text="The short id of a saved insight that shows the fact. The page links to it.",
+ )
+ url = serializers.CharField(
+ max_length=500,
+ allow_null=True,
+ required=False,
+ help_text="A link to the GitHub pull request or commit behind the fact. No other links are accepted.",
+ )
+ queryTool = serializers.ChoiceField(
+ choices=StoryEvidenceQueryTool.choices,
+ allow_null=True,
+ required=False,
+ help_text="The MCP query tool that can redraw `query`. The page redraws the query only when this is set.",
+ )
+ chart = StoryEvidenceChartSerializer(
+ allow_null=True, required=False, help_text="The fact drawn as a chart, from its SQL."
+ )
+
+ def validate_query(self, value: dict[str, Any] | None) -> dict[str, Any] | None:
+ if value is not None and len(json.dumps(value)) > MAX_EVIDENCE_QUERY_BYTES:
+ raise serializers.ValidationError("The query is too large to save.")
+ return value
+
+ def validate_url(self, value: str | None) -> str | None:
+ if value is not None and not GITHUB_CHANGE_LINK.fullmatch(value):
+ raise serializers.ValidationError("Only links to a GitHub pull request or commit are accepted.")
+ return value
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ tool = attrs.get("queryTool")
+ if tool is not None:
+ query = attrs.get("query") or {}
+ if query.get("kind", "TrendsQuery") != QUERY_KIND_BY_TOOL[tool]:
+ raise serializers.ValidationError({"queryTool": "This tool cannot redraw a query of this kind."})
+ return attrs
+
+
+class StoryChapterSerializer(serializers.Serializer):
+ title = serializers.CharField(max_length=80, help_text="The moment on the chart this chapter explains.")
+ range = serializers.ListField(
+ child=serializers.IntegerField(min_value=0),
+ min_length=2,
+ max_length=2,
+ allow_null=True,
+ help_text="Inclusive indexes into the series' points. Null when the chapter's dates match no point.",
+ )
+ summary = serializers.CharField(
+ allow_null=True, allow_blank=True, max_length=400, help_text="What happened in this moment."
+ )
+ cause = serializers.CharField(
+ allow_null=True, allow_blank=True, max_length=600, help_text="The likely cause of this moment."
+ )
+ confidence = serializers.ChoiceField(
+ choices=StoryConfidence.choices, allow_null=True, help_text="How sure the investigation is of the cause."
+ )
+ confidenceReason = serializers.CharField(
+ allow_null=True, allow_blank=True, max_length=200, help_text="Why the confidence is what it is."
+ )
+ evidence = StoryEvidenceSerializer(many=True, max_length=6, help_text="The facts behind the cause.") # type: ignore[call-arg]
+
+
+class StorySeriesResultSerializer(serializers.Serializer):
+ label = serializers.CharField( # type: ignore[assignment]
+ required=False, allow_blank=True, max_length=400, help_text="The series name."
+ )
+ data = serializers.ListField( # type: ignore[assignment]
+ child=serializers.FloatField(),
+ max_length=MAX_SERIES_POINTS,
+ required=False,
+ help_text="One value per point. Saved for the followed series only.",
+ )
+ days = serializers.ListField(
+ child=serializers.CharField(),
+ max_length=MAX_SERIES_POINTS,
+ required=False,
+ help_text="The date of each point, in the query's timezone. Saved for the followed series only.",
+ )
+
+
+class ExplainChartDataSerializer(serializers.Serializer):
+ shape = serializers.ChoiceField(
+ choices=ChartExplanationShape.choices,
+ default=ChartExplanationShape.TIME_SERIES,
+ help_text="What the explanation walks through, whichever insight drew the chart. A funnel over time is a time series too.",
+ )
+ query = serializers.DictField(
+ child=serializers.JSONField(allow_null=True), help_text="The insight query the explanation follows."
+ )
+ results = StorySeriesResultSerializer( # type: ignore[call-arg]
+ many=True, max_length=1_000, help_text="Every series on the chart when it was explained."
+ )
+ seriesIndex = serializers.IntegerField(min_value=0, help_text="The index in `results` the explanation follows.")
+ insightName = serializers.CharField(
+ allow_null=True, allow_blank=True, max_length=400, help_text="The insight's name."
+ )
+ lastPointInProgress = serializers.BooleanField(help_text="Whether the last point's period had not ended yet.")
+ headline = serializers.CharField(
+ max_length=300, help_text="One sentence a person could read in place of the whole explanation."
+ )
+ chapters = StoryChapterSerializer( # type: ignore[call-arg]
+ many=True, min_length=1, max_length=8, help_text="The moments that stand out, in reading order."
+ )
+ warnings = serializers.ListField(
+ child=serializers.JSONField(),
+ max_length=20,
+ required=False,
+ help_text="Warnings the chart's query came back with.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ followed = attrs["seriesIndex"]
+ if followed >= len(attrs["results"]):
+ raise serializers.ValidationError({"seriesIndex": "There is no series at this index."})
+ # The page draws the live chart and reads the points of the followed series only.
+ attrs["results"] = [
+ result if index == followed else {key: value for key, value in result.items() if key == "label"}
+ for index, result in enumerate(attrs["results"])
+ ]
+ return attrs
+
+
+class InsightExplanationCreateSerializer(serializers.Serializer):
+ data = ExplainChartDataSerializer( # type: ignore[assignment]
+ help_text="The chart explanation, as the insight page shows it."
+ )
+
+ def validate_data(self, value: dict[str, Any]) -> dict[str, Any]:
+ if len(json.dumps(value)) > MAX_EXPLANATION_BYTES:
+ raise serializers.ValidationError("The explanation is too large to save.")
+ return value
+
+
+class ChartExplanationAuthorSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = ChartExplanationAuthor
+ extra_kwargs = {
+ "id": {"help_text": "The user's id."},
+ "first_name": {"help_text": "The user's first name."},
+ "last_name": {"help_text": "The user's last name."},
+ "email": {"help_text": "The user's email address."},
+ }
+
+
+class ChartExplanationSerializer(DataclassSerializer):
+ data = ExplainChartDataSerializer( # type: ignore[assignment]
+ help_text="The chart explanation, as the insight page shows it."
+ )
+ created_by = ChartExplanationAuthorSerializer(
+ allow_null=True, help_text="Who saved the explanation, directly or through an agent."
+ )
+
+ class Meta:
+ dataclass = ChartExplanation
+ extra_kwargs = {
+ "id": {"help_text": "The explanation's id, which its link carries."},
+ "insight_id": {"help_text": "The insight the explanation belongs to."},
+ "created_at": {"help_text": "When the explanation was first saved."},
+ }
+
+
+class InsightExplanationAccessPermission(AccessControlPermission):
+ # A create is refused at the resource level before object grants are read, so the view checks the parent insight.
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ return getattr(view, "action", None) in ("create", "update") or super().has_permission(request, view)
+
+
+class InsightExplanationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "insight"
+ scope_object_read_actions = ["retrieve"]
+ scope_object_write_actions = ["create", "update"]
+ path_parameters = {"pk": UUID, "insight_id": int}
+
+ @cached_property
+ def insight(self) -> Insight:
+ insight = Insight.objects.filter(
+ pk=self.kwargs["parent_lookup_insight_id"], team__project_id=self.team.project_id, deleted=False
+ ).first()
+ if insight is None:
+ raise NotFound("Insight not found.")
+ self.check_object_permissions(self.request, insight)
+ return insight
+
+ def dangerously_get_permissions(self) -> list[BasePermission]:
+ return [
+ IsAuthenticated(),
+ APIScopePermission(),
+ TeamMemberAccessPermission(),
+ InsightExplanationAccessPermission(),
+ ]
+
+ def get_throttles(self) -> list[BaseThrottle]:
+ throttles = super().get_throttles()
+ if self.action in ("create", "update"):
+ throttles.append(InsightExplanationCreateThrottle())
+ return throttles
+
+ @validated_request(
+ request_serializer=InsightExplanationCreateSerializer,
+ responses={201: OpenApiResponse(response=ChartExplanationSerializer)},
+ )
+ def create(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ explanation = api.create_insight_explanation(
+ team_id=self.insight.team_id,
+ insight_id=self.insight.id,
+ user_id=cast(User, request.user).id,
+ data=request.validated_data["data"],
+ )
+ return Response(ChartExplanationSerializer(instance=explanation).data, status=status.HTTP_201_CREATED)
+
+ @validated_request(
+ request_serializer=InsightExplanationCreateSerializer,
+ responses={200: OpenApiResponse(response=ChartExplanationSerializer)},
+ )
+ def update(self, request: ValidatedRequest, pk: UUID, **kwargs: Any) -> Response:
+ explanation = api.update_insight_explanation(
+ team_id=self.insight.team_id,
+ insight_id=self.insight.id,
+ explanation_id=pk,
+ user_id=cast(User, request.user).id,
+ data=request.validated_data["data"],
+ )
+ if explanation is None:
+ raise NotFound("You saved no explanation of this insight with this id.")
+ return Response(ChartExplanationSerializer(instance=explanation).data)
+
+ @extend_schema(responses={200: ChartExplanationSerializer})
+ def retrieve(self, request: Request, pk: UUID, **kwargs: Any) -> Response:
+ explanation = api.get_insight_explanation(
+ team_id=self.insight.team_id, insight_id=self.insight.id, explanation_id=pk
+ )
+ if explanation is None:
+ raise NotFound("Explanation not found.")
+ return Response(ChartExplanationSerializer(instance=explanation).data)
diff --git a/products/product_analytics/backend/routes.py b/products/product_analytics/backend/routes.py
index 679af2fa8c50..891648459f31 100644
--- a/products/product_analytics/backend/routes.py
+++ b/products/product_analytics/backend/routes.py
@@ -7,6 +7,7 @@ from products.product_analytics.backend.presentation.events_retention import (
OrganizationEventsRetentionViewSet,
)
from products.product_analytics.backend.presentation.insight import InsightViewSet
+from products.product_analytics.backend.presentation.insight_explanation import InsightExplanationViewSet
from products.product_analytics.backend.presentation.insight_variable import InsightVariableViewSet
from products.product_analytics.backend.presentation.paths_v2 import PathsV2ViewSet
@@ -23,6 +24,13 @@ def register_routes(routers: RouterRegistry) -> None:
["team_id", "insight_id"],
)
+ insights_router.register(
+ r"explanations",
+ InsightExplanationViewSet,
+ "project_insight_explanations",
+ ["team_id", "insight_id"],
+ )
+
# ThresholdViewSet is owned by the alerts product but nests under insights.
insights_router.register(
"thresholds",
diff --git a/products/product_analytics/backend/tests/api/test_insight_explanation.py b/products/product_analytics/backend/tests/api/test_insight_explanation.py
new file mode 100644
index 000000000000..d1eb1860d337
--- /dev/null
+++ b/products/product_analytics/backend/tests/api/test_insight_explanation.py
@@ -0,0 +1,182 @@
+import copy
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+from posthog.models.organization import OrganizationMembership
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.product_analytics.backend.models import Insight
+from products.product_analytics.backend.presentation.insight_explanation import InsightExplanationCreateSerializer
+
+EXPLANATION: dict[str, Any] = {
+ "query": {"interval": "day", "series": [{"kind": "EventsNode", "event": "$pageview"}], "compareFilter": None},
+ "results": [
+ {"label": "$pageview", "data": [3, 9, 4], "days": ["2026-10-01", "2026-10-02", "2026-10-03"], "count": 16},
+ {"label": "$autocapture", "data": [1, 1, 1], "days": ["2026-10-01", "2026-10-02", "2026-10-03"]},
+ ],
+ "seriesIndex": 0,
+ "insightName": "Pageviews",
+ "lastPointInProgress": False,
+ "headline": "A spike from **news.example.com**.",
+ "chapters": [
+ {
+ "title": "A spike on October 2",
+ "range": [1, 1],
+ "summary": "Pageviews tripled for one day.",
+ "cause": "A link on news.example.com.",
+ "confidence": "high",
+ "confidenceReason": "",
+ "evidence": [
+ {"text": "Most views came from one referrer.", "url": "https://github.com/example/app/pull/12"}
+ ],
+ }
+ ],
+}
+
+
+def _explanation(**changes: Any) -> dict[str, Any]:
+ data = copy.deepcopy(EXPLANATION)
+ data.update(changes)
+ return data
+
+
+def _with_evidence(**item: Any) -> dict[str, Any]:
+ data = copy.deepcopy(EXPLANATION)
+ data["chapters"][0]["evidence"] = [{"text": "Most views came from one referrer.", **item}]
+ return data
+
+
+class TestInsightExplanationCreateSerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("missing_series", _explanation(seriesIndex=2)),
+ ("unknown_shape", _explanation(shape="funnel_steps")),
+ ("evidence_longer_than_a_sentence", _with_evidence(text="x" * 401)),
+ ("evidence_link_off_github", _with_evidence(url="https://hackmycomputer.example/pull/1")),
+ ("evidence_link_to_a_github_file", _with_evidence(url="https://github.com/example/app/raw/main/setup.exe")),
+ ("evidence_insight_id_with_a_path", _with_evidence(insightShortId="../admin")),
+ ("redraw_tool_for_another_kind", _with_evidence(query={"kind": "HogQLQuery"}, queryTool="query-trends")),
+ ("too_large", _explanation(query={"filter": "x" * 300_000})),
+ ]
+ )
+ def test_rejects(self, _name: str, data: dict[str, Any]) -> None:
+ serializer = InsightExplanationCreateSerializer(data={"data": data})
+ assert not serializer.is_valid()
+ assert "data" in serializer.errors
+
+ def test_keeps_only_what_the_page_reads(self) -> None:
+ serializer = InsightExplanationCreateSerializer(data={"data": EXPLANATION})
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["data"]["results"] == [
+ {"label": "$pageview", "data": [3.0, 9.0, 4.0], "days": ["2026-10-01", "2026-10-02", "2026-10-03"]},
+ {"label": "$autocapture"},
+ ]
+ assert serializer.validated_data["data"]["shape"] == "time_series"
+ assert serializer.validated_data["data"]["chapters"][0]["evidence"] == [
+ {"text": "Most views came from one referrer.", "url": "https://github.com/example/app/pull/12"}
+ ]
+
+
+class TestInsightExplanationAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.insight = Insight.objects.create(team=self.team, name="Pageviews", created_by=self.user)
+
+ def _url(self, insight: Insight) -> str:
+ return f"/api/projects/{self.team.id}/insights/{insight.id}/explanations/"
+
+ def test_a_read_only_key_cannot_save_an_explanation(self) -> None:
+ key = self.create_personal_api_key_with_scopes(["insight:read"])
+ self.client.logout()
+
+ response = self.client.post(
+ self._url(self.insight), {"data": EXPLANATION}, format="json", HTTP_AUTHORIZATION=f"Bearer {key}"
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_a_write_key_saves_an_explanation_the_page_can_load(self) -> None:
+ key = self.create_personal_api_key_with_scopes(["insight:write"])
+ self.client.logout()
+
+ created = self.client.post(
+ self._url(self.insight), {"data": EXPLANATION}, format="json", HTTP_AUTHORIZATION=f"Bearer {key}"
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+
+ loaded = self.client.get(
+ f"{self._url(self.insight)}{created.json()['id']}/", HTTP_AUTHORIZATION=f"Bearer {key}"
+ )
+ assert loaded.status_code == status.HTTP_200_OK
+ assert loaded.json()["data"]["headline"] == EXPLANATION["headline"]
+ assert loaded.json()["created_by"]["id"] == self.user.id
+
+ def test_an_explanation_only_loads_under_its_own_insight(self) -> None:
+ created = self.client.post(self._url(self.insight), {"data": EXPLANATION}, format="json")
+ other = Insight.objects.create(team=self.team, name="Other", created_by=self.user)
+
+ response = self.client.get(f"{self._url(other)}{created.json()['id']}/")
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_fixing_an_explanation_keeps_its_link(self) -> None:
+ created = self.client.post(self._url(self.insight), {"data": EXPLANATION}, format="json")
+ url = f"{self._url(self.insight)}{created.json()['id']}/"
+
+ fixed = self.client.put(url, {"data": _explanation(headline="A spike from **ads**.")}, format="json")
+
+ assert fixed.status_code == status.HTTP_200_OK, fixed.json()
+ assert fixed.json()["id"] == created.json()["id"]
+ assert self.client.get(url).json()["data"]["headline"] == "A spike from **ads**."
+
+ @parameterized.expand(
+ [
+ ("insight_hidden", "none", None, status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN),
+ ("insight_shared_for_viewing", "none", "viewer", status.HTTP_403_FORBIDDEN, status.HTTP_200_OK),
+ ("insight_shared_for_editing", "none", "editor", status.HTTP_201_CREATED, status.HTTP_200_OK),
+ ]
+ )
+ def test_access_follows_the_insight(
+ self, _name: str, resource_level: str, insight_level: str | None, save_status: int, load_status: int
+ ) -> None:
+ created = self.client.post(self._url(self.insight), {"data": EXPLANATION}, format="json")
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+ AccessControl.objects.create(team=self.team, resource="insight", resource_id=None, access_level=resource_level)
+ if insight_level:
+ AccessControl.objects.create(
+ team=self.team,
+ resource="insight",
+ resource_id=str(self.insight.id),
+ access_level=insight_level,
+ organization_member=member.organization_memberships.first(),
+ )
+ self.client.force_login(member)
+
+ saved = self.client.post(self._url(self.insight), {"data": EXPLANATION}, format="json")
+ loaded = self.client.get(f"{self._url(self.insight)}{created.json()['id']}/")
+
+ assert saved.status_code == save_status, saved.json()
+ assert loaded.status_code == load_status, loaded.json()
+
+ def test_saving_is_rate_limited_per_user(self) -> None:
+ with patch(
+ "products.product_analytics.backend.presentation.insight_explanation.InsightExplanationCreateThrottle.rate",
+ "1/hour",
+ ):
+ first = self.client.post(self._url(self.insight), {"data": EXPLANATION}, format="json")
+ second = self.client.post(self._url(self.insight), {"data": EXPLANATION}, format="json")
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_429_TOO_MANY_REQUESTS
diff --git a/products/product_analytics/backend/tests/test_facade.py b/products/product_analytics/backend/tests/test_facade.py
index 5e67b8bce1c5..b15577f400be 100644
--- a/products/product_analytics/backend/tests/test_facade.py
+++ b/products/product_analytics/backend/tests/test_facade.py
@@ -17,10 +17,13 @@ from posthog.models.team import Team
from posthog.models.user import User
from products.product_analytics.backend.facade.api import (
+ create_insight_explanation,
+ get_insight_explanation,
insight_short_ids_built_by,
insight_variables_for_team,
insights_including_soft_deleted_for_team,
record_insight_view,
+ update_insight_explanation,
viewer_counts_by_insight,
)
from products.product_analytics.backend.facade.queries import run_cached_trends_query
@@ -134,6 +137,37 @@ class TestInsightReads(BaseTest):
assert counts == {viewed.pk: 2}
+class TestSaveInsightExplanation(BaseTest):
+ @parameterized.expand(
+ [
+ ("by_the_person_who_saved_it", True, True),
+ ("by_another_person", False, False),
+ ]
+ )
+ def test_only_the_person_who_saved_an_explanation_can_change_it(
+ self, _name: str, same_person: bool, changed: bool
+ ) -> None:
+ insight = Insight.objects.create(team=self.team, name="Pageviews")
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ first = create_insight_explanation(
+ team_id=self.team.id, insight_id=insight.id, user_id=self.user.id, data={"headline": "First."}
+ )
+
+ updated = update_insight_explanation(
+ team_id=self.team.id,
+ insight_id=insight.id,
+ explanation_id=first.id,
+ user_id=(self.user if same_person else other).id,
+ data={"headline": "Second."},
+ )
+
+ assert (updated is not None) == changed
+ stored = get_insight_explanation(team_id=self.team.id, insight_id=insight.id, explanation_id=first.id)
+ assert stored is not None
+ assert stored.data == {"headline": "Second." if changed else "First."}
+ assert stored.created_by is not None and stored.created_by.id == self.user.id
+
+
class TestRunCachedTrendsQuery(BaseTest):
def tearDown(self) -> None:
reset_query_tags()
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index ff99b0caf2b8..4837b5fc04d8 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -9129,6 +9129,268 @@ export interface PaginatedInsightListApi {
results: InsightApi[]
}
+/**
+ * * `time_series` - Time series
+ */
+export type ChartExplanationShapeEnumApi =
+ (typeof ChartExplanationShapeEnumApi)[keyof typeof ChartExplanationShapeEnumApi]
+
+export const ChartExplanationShapeEnumApi = {
+ TimeSeries: 'time_series',
+} as const
+
+export interface StorySeriesResultApi {
+ /**
+ * The series name.
+ * @maxLength 400
+ */
+ label?: string
+ /**
+ * One value per point. Saved for the followed series only.
+ * @maxItems 5000
+ */
+ data?: number[]
+ /**
+ * The date of each point, in the query's timezone. Saved for the followed series only.
+ * @maxItems 5000
+ */
+ days?: string[]
+}
+
+/**
+ * * `high` - High confidence
+ * * `medium` - Medium confidence
+ * * `low` - Low confidence
+ */
+export type StoryConfidenceEnumApi = (typeof StoryConfidenceEnumApi)[keyof typeof StoryConfidenceEnumApi]
+
+export const StoryConfidenceEnumApi = {
+ High: 'high',
+ Medium: 'medium',
+ Low: 'low',
+} as const
+
+/**
+ * * `query-trends` - Trends
+ * * `query-funnel` - Funnel
+ * * `query-retention` - Retention
+ * * `query-stickiness` - Stickiness
+ * * `query-paths` - Paths
+ * * `query-lifecycle` - Lifecycle
+ */
+export type StoryEvidenceQueryToolEnumApi =
+ (typeof StoryEvidenceQueryToolEnumApi)[keyof typeof StoryEvidenceQueryToolEnumApi]
+
+export const StoryEvidenceQueryToolEnumApi = {
+ QueryTrends: 'query-trends',
+ QueryFunnel: 'query-funnel',
+ QueryRetention: 'query-retention',
+ QueryStickiness: 'query-stickiness',
+ QueryPaths: 'query-paths',
+ QueryLifecycle: 'query-lifecycle',
+} as const
+
+/**
+ * * `line` - Line
+ * * `bar` - Bar
+ */
+export type StoryEvidenceChartTypeEnumApi =
+ (typeof StoryEvidenceChartTypeEnumApi)[keyof typeof StoryEvidenceChartTypeEnumApi]
+
+export const StoryEvidenceChartTypeEnumApi = {
+ Line: 'line',
+ Bar: 'bar',
+} as const
+
+export interface StoryEvidenceSeriesApi {
+ /** The breakdown value or column this line draws. */
+ name: string
+ /**
+ * One value per label. Null where the breakdown value has no row for that point.
+ * @maxItems 5000
+ */
+ values: (number | null)[]
+}
+
+export interface StoryEvidenceChartApi {
+ /** How the evidence chart draws its series.
+ *
+ * * `line` - Line
+ * * `bar` - Bar */
+ type: StoryEvidenceChartTypeEnumApi
+ /**
+ * The x-axis points.
+ * @maxItems 5000
+ */
+ labels: string[]
+ /**
+ * The axis label of each point, which leaves out a date that repeats.
+ * @maxItems 5000
+ */
+ ticks?: string[]
+ /** The lines or bars to draw. */
+ series: StoryEvidenceSeriesApi[]
+ /**
+ * The y-axis label, if any.
+ * @nullable
+ */
+ yAxisLabel: string | null
+}
+
+/**
+ * The query that shows the fact. The page links to it.
+ * @nullable
+ */
+export type StoryEvidenceApiQuery = { [key: string]: unknown } | null
+
+export interface StoryEvidenceApi {
+ /**
+ * One fact that supports the chapter, in one sentence.
+ * @maxLength 400
+ */
+ text: string
+ /**
+ * The query that shows the fact. The page links to it.
+ * @nullable
+ */
+ query?: StoryEvidenceApiQuery
+ /**
+ * The short id of a saved insight that shows the fact. The page links to it.
+ * @nullable
+ * @pattern ^[A-Za-z0-9]{8}$
+ */
+ insightShortId?: string | null
+ /**
+ * A link to the GitHub pull request or commit behind the fact. No other links are accepted.
+ * @maxLength 500
+ * @nullable
+ */
+ url?: string | null
+ /** The MCP query tool that can redraw `query`. The page redraws the query only when this is set.
+ *
+ * * `query-trends` - Trends
+ * * `query-funnel` - Funnel
+ * * `query-retention` - Retention
+ * * `query-stickiness` - Stickiness
+ * * `query-paths` - Paths
+ * * `query-lifecycle` - Lifecycle */
+ queryTool?: StoryEvidenceQueryToolEnumApi | null
+ /** The fact drawn as a chart, from its SQL. */
+ chart?: StoryEvidenceChartApi | null
+}
+
+export interface StoryChapterApi {
+ /**
+ * The moment on the chart this chapter explains.
+ * @maxLength 80
+ */
+ title: string
+ /**
+ * Inclusive indexes into the series' points. Null when the chapter's dates match no point.
+ * @minItems 2
+ * @maxItems 2
+ * @nullable
+ * @items.minimum 0
+ */
+ range: number[] | null
+ /**
+ * What happened in this moment.
+ * @maxLength 400
+ * @nullable
+ */
+ summary: string | null
+ /**
+ * The likely cause of this moment.
+ * @maxLength 600
+ * @nullable
+ */
+ cause: string | null
+ /** How sure the investigation is of the cause.
+ *
+ * * `high` - High confidence
+ * * `medium` - Medium confidence
+ * * `low` - Low confidence */
+ confidence: StoryConfidenceEnumApi | null
+ /**
+ * Why the confidence is what it is.
+ * @maxLength 200
+ * @nullable
+ */
+ confidenceReason: string | null
+ /** The facts behind the cause. */
+ evidence: StoryEvidenceApi[]
+}
+
+/**
+ * The insight query the explanation follows.
+ */
+export type ExplainChartDataApiQuery = { [key: string]: unknown }
+
+export interface ExplainChartDataApi {
+ /** What the explanation walks through, whichever insight drew the chart. A funnel over time is a time series too.
+ *
+ * * `time_series` - Time series */
+ shape?: ChartExplanationShapeEnumApi
+ /** The insight query the explanation follows. */
+ query: ExplainChartDataApiQuery
+ /** Every series on the chart when it was explained. */
+ results: StorySeriesResultApi[]
+ /**
+ * The index in `results` the explanation follows.
+ * @minimum 0
+ */
+ seriesIndex: number
+ /**
+ * The insight's name.
+ * @maxLength 400
+ * @nullable
+ */
+ insightName: string | null
+ /** Whether the last point's period had not ended yet. */
+ lastPointInProgress: boolean
+ /**
+ * One sentence a person could read in place of the whole explanation.
+ * @maxLength 300
+ */
+ headline: string
+ /** The moments that stand out, in reading order. */
+ chapters: StoryChapterApi[]
+ /**
+ * Warnings the chart's query came back with.
+ * @maxItems 20
+ */
+ warnings?: unknown[]
+}
+
+export interface InsightExplanationCreateApi {
+ /** The chart explanation, as the insight page shows it. */
+ data: ExplainChartDataApi
+}
+
+export interface ChartExplanationAuthorApi {
+ /** The user's id. */
+ id: number
+ /** The user's first name. */
+ first_name: string
+ /** The user's last name. */
+ last_name: string
+ /** The user's email address. */
+ email: string
+}
+
+export interface ChartExplanationApi {
+ /** The chart explanation, as the insight page shows it. */
+ data: ExplainChartDataApi
+ /** Who saved the explanation, directly or through an agent. */
+ created_by: ChartExplanationAuthorApi | null
+ /** The explanation's id, which its link carries. */
+ id: string
+ /** The insight the explanation belongs to. */
+ insight_id: number
+ /** When the explanation was first saved. */
+ created_at: string
+}
+
/**
* The period that this insight's query covered, with both ends resolved to timestamps. Null when the insight has no result yet or its query type does not report the range.
* @nullable
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index 4c5ef0be3fec..96d724c7d533 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -12,6 +12,7 @@ import type {
ActivityLogPaginatedResponseApi,
BulkUpdateTagsRequestApi,
BulkUpdateTagsResponseApi,
+ ChartExplanationApi,
ColumnConfigurationApi,
ColumnConfigurationsListParams,
ElementApi,
@@ -30,6 +31,7 @@ import type {
InsightBulkSetTestAccountFilterResponseApi,
InsightDataChecksApi,
InsightDataChecksRequestApi,
+ InsightExplanationCreateApi,
InsightViewedRequestApi,
InsightsActivityRetrieveParams,
InsightsAllActivityRetrieveParams,
@@ -485,6 +487,59 @@ export const insightsCreate = async (
})
}
+export const getInsightsExplanationsCreateUrl = (projectId: string, insightId: number) => {
+ return `/api/projects/${projectId}/insights/${insightId}/explanations/`
+}
+
+export const insightsExplanationsCreate = async (
+ projectId: string,
+ insightId: number,
+ insightExplanationCreateApi: InsightExplanationCreateApi,
+ options?: RequestInit
+): Promise<ChartExplanationApi> => {
+ return apiMutator<ChartExplanationApi>(getInsightsExplanationsCreateUrl(projectId, insightId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(insightExplanationCreateApi),
+ })
+}
+
+export const getInsightsExplanationsRetrieveUrl = (projectId: string, insightId: number, id: string) => {
+ return `/api/projects/${projectId}/insights/${insightId}/explanations/${id}/`
+}
+
+export const insightsExplanationsRetrieve = async (
+ projectId: string,
+ insightId: number,
+ id: string,
+ options?: RequestInit
+): Promise<ChartExplanationApi> => {
+ return apiMutator<ChartExplanationApi>(getInsightsExplanationsRetrieveUrl(projectId, insightId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getInsightsExplanationsUpdateUrl = (projectId: string, insightId: number, id: string) => {
+ return `/api/projects/${projectId}/insights/${insightId}/explanations/${id}/`
+}
+
+export const insightsExplanationsUpdate = async (
+ projectId: string,
+ insightId: number,
+ id: string,
+ insightExplanationCreateApi: InsightExplanationCreateApi,
+ options?: RequestInit
+): Promise<ChartExplanationApi> => {
+ return apiMutator<ChartExplanationApi>(getInsightsExplanationsUpdateUrl(projectId, insightId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(insightExplanationCreateApi),
+ })
+}
+
export const getInsightsRetrieveUrl = (projectId: string, id: number | string, params?: InsightsRetrieveParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.ts
index c8e1417efcd7..21b558aa2206 100644
--- a/products/product_analytics/frontend/generated/api.zod.ts
+++ b/products/product_analytics/frontend/generated/api.zod.ts
@@ -225,6 +225,496 @@ export const InsightsCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+export const insightsExplanationsCreateBodyDataOneShapeDefault = `time_series`
+export const insightsExplanationsCreateBodyDataOneResultsItemLabelMax = 400
+
+export const insightsExplanationsCreateBodyDataOneResultsItemDataMax = 5000
+
+export const insightsExplanationsCreateBodyDataOneResultsItemDaysMax = 5000
+
+export const insightsExplanationsCreateBodyDataOneSeriesIndexMin = 0
+
+export const insightsExplanationsCreateBodyDataOneInsightNameMax = 400
+
+export const insightsExplanationsCreateBodyDataOneHeadlineMax = 300
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemTitleMax = 80
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemRangeItemMin = 0
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemRangeMin = 2
+export const insightsExplanationsCreateBodyDataOneChaptersItemRangeMax = 2
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemSummaryMax = 400
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemCauseMax = 600
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemConfidenceReasonMax = 200
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemTextMax = 400
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemInsightShortIdRegExp = new RegExp(
+ '^[A-Za-z0-9]{8}$'
+)
+export const insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemUrlMax = 500
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemChartOneLabelsMax = 5000
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemChartOneTicksMax = 5000
+
+export const insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemChartOneSeriesItemValuesMax = 5000
+
+export const insightsExplanationsCreateBodyDataOneWarningsMax = 20
+
+export const InsightsExplanationsCreateBody = /* @__PURE__ */ zod.object({
+ data: zod
+ .object({
+ shape: zod
+ .enum(['time_series'])
+ .describe('\* `time_series` - Time series')
+ .default(insightsExplanationsCreateBodyDataOneShapeDefault)
+ .describe(
+ 'What the explanation walks through, whichever insight drew the chart. A funnel over time is a time series too.\n\n\* `time_series` - Time series'
+ ),
+ query: zod.record(zod.string(), zod.unknown()).describe('The insight query the explanation follows.'),
+ results: zod
+ .array(
+ zod.object({
+ label: zod
+ .string()
+ .max(insightsExplanationsCreateBodyDataOneResultsItemLabelMax)
+ .optional()
+ .describe('The series name.'),
+ data: zod
+ .array(zod.number())
+ .max(insightsExplanationsCreateBodyDataOneResultsItemDataMax)
+ .optional()
+ .describe('One value per point. Saved for the followed series only.'),
+ days: zod
+ .array(zod.string())
+ .max(insightsExplanationsCreateBodyDataOneResultsItemDaysMax)
+ .optional()
+ .describe(
+ "The date of each point, in the query's timezone. Saved for the followed series only."
+ ),
+ })
+ )
+ .describe('Every series on the chart when it was explained.'),
+ seriesIndex: zod
+ .number()
+ .min(insightsExplanationsCreateBodyDataOneSeriesIndexMin)
+ .describe('The index in `results` the explanation follows.'),
+ insightName: zod
+ .string()
+ .max(insightsExplanationsCreateBodyDataOneInsightNameMax)
+ .nullable()
+ .describe("The insight's name."),
+ lastPointInProgress: zod.boolean().describe("Whether the last point's period had not ended yet."),
+ headline: zod
+ .string()
+ .max(insightsExplanationsCreateBodyDataOneHeadlineMax)
+ .describe('One sentence a person could read in place of the whole explanation.'),
+ chapters: zod
+ .array(
+ zod.object({
+ title: zod
+ .string()
+ .max(insightsExplanationsCreateBodyDataOneChaptersItemTitleMax)
+ .describe('The moment on the chart this chapter explains.'),
+ range: zod
+ .array(zod.number().min(insightsExplanationsCreateBodyDataOneChaptersItemRangeItemMin))
+ .min(insightsExplanationsCreateBodyDataOneChaptersItemRangeMin)
+ .max(insightsExplanationsCreateBodyDataOneChaptersItemRangeMax)
+ .nullable()
+ .describe(
+ "Inclusive indexes into the series' points. Null when the chapter's dates match no point."
+ ),
+ summary: zod
+ .string()
+ .max(insightsExplanationsCreateBodyDataOneChaptersItemSummaryMax)
+ .nullable()
+ .describe('What happened in this moment.'),
+ cause: zod
+ .string()
+ .max(insightsExplanationsCreateBodyDataOneChaptersItemCauseMax)
+ .nullable()
+ .describe('The likely cause of this moment.'),
+ confidence: zod
+ .union([
+ zod
+ .enum(['high', 'medium', 'low'])
+ .describe(
+ '\* `high` - High confidence\n\* `medium` - Medium confidence\n\* `low` - Low confidence'
+ ),
+ zod.null(),
+ ])
+ .describe(
+ 'How sure the investigation is of the cause.\n\n\* `high` - High confidence\n\* `medium` - Medium confidence\n\* `low` - Low confidence'
+ ),
+ confidenceReason: zod
+ .string()
+ .max(insightsExplanationsCreateBodyDataOneChaptersItemConfidenceReasonMax)
+ .nullable()
+ .describe('Why the confidence is what it is.'),
+ evidence: zod
+ .array(
+ zod.object({
+ text: zod
+ .string()
+ .max(insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemTextMax)
+ .describe('One fact that supports the chapter, in one sentence.'),
+ query: zod
+ .record(zod.string(), zod.unknown())
+ .nullish()
+ .describe('The query that shows the fact. The page links to it.'),
+ insightShortId: zod
+ .string()
+ .regex(
+ insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemInsightShortIdRegExp
+ )
+ .nullish()
+ .describe(
+ 'The short id of a saved insight that shows the fact. The page links to it.'
+ ),
+ url: zod
+ .string()
+ .max(insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemUrlMax)
+ .nullish()
+ .describe(
+ 'A link to the GitHub pull request or commit behind the fact. No other links are accepted.'
+ ),
+ queryTool: zod
+ .union([
+ zod
+ .enum([
+ 'query-trends',
+ 'query-funnel',
+ 'query-retention',
+ 'query-stickiness',
+ 'query-paths',
+ 'query-lifecycle',
+ ])
+ .describe(
+ '\* `query-trends` - Trends\n\* `query-funnel` - Funnel\n\* `query-retention` - Retention\n\* `query-stickiness` - Stickiness\n\* `query-paths` - Paths\n\* `query-lifecycle` - Lifecycle'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'The MCP query tool that can redraw `query`. The page redraws the query only when this is set.\n\n\* `query-trends` - Trends\n\* `query-funnel` - Funnel\n\* `query-retention` - Retention\n\* `query-stickiness` - Stickiness\n\* `query-paths` - Paths\n\* `query-lifecycle` - Lifecycle'
+ ),
+ chart: zod
+ .union([
+ zod.object({
+ type: zod
+ .enum(['line', 'bar'])
+ .describe('\* `line` - Line\n\* `bar` - Bar')
+ .describe(
+ 'How the evidence chart draws its series.\n\n\* `line` - Line\n\* `bar` - Bar'
+ ),
+ labels: zod
+ .array(zod.string())
+ .max(
+ insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemChartOneLabelsMax
+ )
+ .describe('The x-axis points.'),
+ ticks: zod
+ .array(zod.string())
+ .max(
+ insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemChartOneTicksMax
+ )
+ .optional()
+ .describe(
+ 'The axis label of each point, which leaves out a date that repeats.'
+ ),
+ series: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .describe(
+ 'The breakdown value or column this line draws.'
+ ),
+ values: zod
+ .array(zod.number().nullable())
+ .max(
+ insightsExplanationsCreateBodyDataOneChaptersItemEvidenceItemChartOneSeriesItemValuesMax
+ )
+ .describe(
+ 'One value per label. Null where the breakdown value has no row for that point.'
+ ),
+ })
+ )
+ .describe('The lines or bars to draw.'),
+ yAxisLabel: zod
+ .string()
+ .nullable()
+ .describe('The y-axis label, if any.'),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('The fact drawn as a chart, from its SQL.'),
+ })
+ )
+ .describe('The facts behind the cause.'),
+ })
+ )
+ .describe('The moments that stand out, in reading order.'),
+ warnings: zod
+ .array(zod.unknown())
+ .max(insightsExplanationsCreateBodyDataOneWarningsMax)
+ .optional()
+ .describe("Warnings the chart's query came back with."),
+ })
+ .describe('The chart explanation, as the insight page shows it.'),
+})
+
+export const insightsExplanationsUpdateBodyDataOneShapeDefault = `time_series`
+export const insightsExplanationsUpdateBodyDataOneResultsItemLabelMax = 400
+
+export const insightsExplanationsUpdateBodyDataOneResultsItemDataMax = 5000
+
+export const insightsExplanationsUpdateBodyDataOneResultsItemDaysMax = 5000
+
+export const insightsExplanationsUpdateBodyDataOneSeriesIndexMin = 0
+
+export const insightsExplanationsUpdateBodyDataOneInsightNameMax = 400
+
+export const insightsExplanationsUpdateBodyDataOneHeadlineMax = 300
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemTitleMax = 80
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemRangeItemMin = 0
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemRangeMin = 2
+export const insightsExplanationsUpdateBodyDataOneChaptersItemRangeMax = 2
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemSummaryMax = 400
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemCauseMax = 600
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemConfidenceReasonMax = 200
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemTextMax = 400
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemInsightShortIdRegExp = new RegExp(
+ '^[A-Za-z0-9]{8}$'
+)
+export const insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemUrlMax = 500
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemChartOneLabelsMax = 5000
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemChartOneTicksMax = 5000
+
+export const insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemChartOneSeriesItemValuesMax = 5000
+
+export const insightsExplanationsUpdateBodyDataOneWarningsMax = 20
+
+export const InsightsExplanationsUpdateBody = /* @__PURE__ */ zod.object({
+ data: zod
+ .object({
+ shape: zod
+ .enum(['time_series'])
+ .describe('\* `time_series` - Time series')
+ .default(insightsExplanationsUpdateBodyDataOneShapeDefault)
+ .describe(
+ 'What the explanation walks through, whichever insight drew the chart. A funnel over time is a time series too.\n\n\* `time_series` - Time series'
+ ),
+ query: zod.record(zod.string(), zod.unknown()).describe('The insight query the explanation follows.'),
+ results: zod
+ .array(
+ zod.object({
+ label: zod
+ .string()
+ .max(insightsExplanationsUpdateBodyDataOneResultsItemLabelMax)
+ .optional()
+ .describe('The series name.'),
+ data: zod
+ .array(zod.number())
+ .max(insightsExplanationsUpdateBodyDataOneResultsItemDataMax)
+ .optional()
+ .describe('One value per point. Saved for the followed series only.'),
+ days: zod
+ .array(zod.string())
+ .max(insightsExplanationsUpdateBodyDataOneResultsItemDaysMax)
+ .optional()
+ .describe(
+ "The date of each point, in the query's timezone. Saved for the followed series only."
+ ),
+ })
+ )
+ .describe('Every series on the chart when it was explained.'),
+ seriesIndex: zod
+ .number()
+ .min(insightsExplanationsUpdateBodyDataOneSeriesIndexMin)
+ .describe('The index in `results` the explanation follows.'),
+ insightName: zod
+ .string()
+ .max(insightsExplanationsUpdateBodyDataOneInsightNameMax)
+ .nullable()
+ .describe("The insight's name."),
+ lastPointInProgress: zod.boolean().describe("Whether the last point's period had not ended yet."),
+ headline: zod
+ .string()
+ .max(insightsExplanationsUpdateBodyDataOneHeadlineMax)
+ .describe('One sentence a person could read in place of the whole explanation.'),
+ chapters: zod
+ .array(
+ zod.object({
+ title: zod
+ .string()
+ .max(insightsExplanationsUpdateBodyDataOneChaptersItemTitleMax)
+ .describe('The moment on the chart this chapter explains.'),
+ range: zod
+ .array(zod.number().min(insightsExplanationsUpdateBodyDataOneChaptersItemRangeItemMin))
+ .min(insightsExplanationsUpdateBodyDataOneChaptersItemRangeMin)
+ .max(insightsExplanationsUpdateBodyDataOneChaptersItemRangeMax)
+ .nullable()
+ .describe(
+ "Inclusive indexes into the series' points. Null when the chapter's dates match no point."
+ ),
+ summary: zod
+ .string()
+ .max(insightsExplanationsUpdateBodyDataOneChaptersItemSummaryMax)
+ .nullable()
+ .describe('What happened in this moment.'),
+ cause: zod
+ .string()
+ .max(insightsExplanationsUpdateBodyDataOneChaptersItemCauseMax)
+ .nullable()
+ .describe('The likely cause of this moment.'),
+ confidence: zod
+ .union([
+ zod
+ .enum(['high', 'medium', 'low'])
+ .describe(
+ '\* `high` - High confidence\n\* `medium` - Medium confidence\n\* `low` - Low confidence'
+ ),
+ zod.null(),
+ ])
+ .describe(
+ 'How sure the investigation is of the cause.\n\n\* `high` - High confidence\n\* `medium` - Medium confidence\n\* `low` - Low confidence'
+ ),
+ confidenceReason: zod
+ .string()
+ .max(insightsExplanationsUpdateBodyDataOneChaptersItemConfidenceReasonMax)
+ .nullable()
+ .describe('Why the confidence is what it is.'),
+ evidence: zod
+ .array(
+ zod.object({
+ text: zod
+ .string()
+ .max(insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemTextMax)
+ .describe('One fact that supports the chapter, in one sentence.'),
+ query: zod
+ .record(zod.string(), zod.unknown())
+ .nullish()
+ .describe('The query that shows the fact. The page links to it.'),
+ insightShortId: zod
+ .string()
+ .regex(
+ insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemInsightShortIdRegExp
+ )
+ .nullish()
+ .describe(
+ 'The short id of a saved insight that shows the fact. The page links to it.'
+ ),
+ url: zod
+ .string()
+ .max(insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemUrlMax)
+ .nullish()
+ .describe(
+ 'A link to the GitHub pull request or commit behind the fact. No other links are accepted.'
+ ),
+ queryTool: zod
+ .union([
+ zod
+ .enum([
+ 'query-trends',
+ 'query-funnel',
+ 'query-retention',
+ 'query-stickiness',
+ 'query-paths',
+ 'query-lifecycle',
+ ])
+ .describe(
+ '\* `query-trends` - Trends\n\* `query-funnel` - Funnel\n\* `query-retention` - Retention\n\* `query-stickiness` - Stickiness\n\* `query-paths` - Paths\n\* `query-lifecycle` - Lifecycle'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'The MCP query tool that can redraw `query`. The page redraws the query only when this is set.\n\n\* `query-trends` - Trends\n\* `query-funnel` - Funnel\n\* `query-retention` - Retention\n\* `query-stickiness` - Stickiness\n\* `query-paths` - Paths\n\* `query-lifecycle` - Lifecycle'
+ ),
+ chart: zod
+ .union([
+ zod.object({
+ type: zod
+ .enum(['line', 'bar'])
+ .describe('\* `line` - Line\n\* `bar` - Bar')
+ .describe(
+ 'How the evidence chart draws its series.\n\n\* `line` - Line\n\* `bar` - Bar'
+ ),
+ labels: zod
+ .array(zod.string())
+ .max(
+ insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemChartOneLabelsMax
+ )
+ .describe('The x-axis points.'),
+ ticks: zod
+ .array(zod.string())
+ .max(
+ insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemChartOneTicksMax
+ )
+ .optional()
+ .describe(
+ 'The axis label of each point, which leaves out a date that repeats.'
+ ),
+ series: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .describe(
+ 'The breakdown value or column this line draws.'
+ ),
+ values: zod
+ .array(zod.number().nullable())
+ .max(
+ insightsExplanationsUpdateBodyDataOneChaptersItemEvidenceItemChartOneSeriesItemValuesMax
+ )
+ .describe(
+ 'One value per label. Null where the breakdown value has no row for that point.'
+ ),
+ })
+ )
+ .describe('The lines or bars to draw.'),
+ yAxisLabel: zod
+ .string()
+ .nullable()
+ .describe('The y-axis label, if any.'),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('The fact drawn as a chart, from its SQL.'),
+ })
+ )
+ .describe('The facts behind the cause.'),
+ })
+ )
+ .describe('The moments that stand out, in reading order.'),
+ warnings: zod
+ .array(zod.unknown())
+ .max(insightsExplanationsUpdateBodyDataOneWarningsMax)
+ .optional()
+ .describe("Warnings the chart's query came back with."),
+ })
+ .describe('The chart explanation, as the insight page shows it.'),
+})
+
export const InsightsUpdateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 868ff846a1af..b5b16cf93e4e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24820,6 +24820,264 @@ export namespace Schemas {
star?: boolean;
}
+ /**
+ * * `time_series` - Time series
+ */
+ export type ChartExplanationShapeEnum = typeof ChartExplanationShapeEnum[keyof typeof ChartExplanationShapeEnum];
+
+
+ export const ChartExplanationShapeEnum = {
+ TimeSeries: 'time_series',
+ } as const;
+
+ export interface StorySeriesResult {
+ /**
+ * The series name.
+ * @maxLength 400
+ */
+ label?: string;
+ /**
+ * One value per point. Saved for the followed series only.
+ * @maxItems 5000
+ */
+ data?: number[];
+ /**
+ * The date of each point, in the query's timezone. Saved for the followed series only.
+ * @maxItems 5000
+ */
+ days?: string[];
+ }
+
+ /**
+ * * `high` - High confidence
+ * * `medium` - Medium confidence
+ * * `low` - Low confidence
+ */
+ export type StoryConfidenceEnum = typeof StoryConfidenceEnum[keyof typeof StoryConfidenceEnum];
+
+
+ export const StoryConfidenceEnum = {
+ High: 'high',
+ Medium: 'medium',
+ Low: 'low',
+ } as const;
+
+ /**
+ * * `query-trends` - Trends
+ * * `query-funnel` - Funnel
+ * * `query-retention` - Retention
+ * * `query-stickiness` - Stickiness
+ * * `query-paths` - Paths
+ * * `query-lifecycle` - Lifecycle
+ */
+ export type StoryEvidenceQueryToolEnum = typeof StoryEvidenceQueryToolEnum[keyof typeof StoryEvidenceQueryToolEnum];
+
+
+ export const StoryEvidenceQueryToolEnum = {
+ QueryTrends: 'query-trends',
+ QueryFunnel: 'query-funnel',
+ QueryRetention: 'query-retention',
+ QueryStickiness: 'query-stickiness',
+ QueryPaths: 'query-paths',
+ QueryLifecycle: 'query-lifecycle',
+ } as const;
+
+ /**
+ * * `line` - Line
+ * * `bar` - Bar
+ */
+ export type StoryEvidenceChartTypeEnum = typeof StoryEvidenceChartTypeEnum[keyof typeof StoryEvidenceChartTypeEnum];
+
+
+ export const StoryEvidenceChartTypeEnum = {
+ Line: 'line',
+ Bar: 'bar',
+ } as const;
+
+ export interface StoryEvidenceSeries {
+ /** The breakdown value or column this line draws. */
+ name: string;
+ /**
+ * One value per label. Null where the breakdown value has no row for that point.
+ * @maxItems 5000
+ */
+ values: (number | null)[];
+ }
+
+ export interface StoryEvidenceChart {
+ /** How the evidence chart draws its series.
+ *
+ * * `line` - Line
+ * * `bar` - Bar */
+ type: StoryEvidenceChartTypeEnum;
+ /**
+ * The x-axis points.
+ * @maxItems 5000
+ */
+ labels: string[];
+ /**
+ * The axis label of each point, which leaves out a date that repeats.
+ * @maxItems 5000
+ */
+ ticks?: string[];
+ /** The lines or bars to draw. */
+ series: StoryEvidenceSeries[];
+ /**
+ * The y-axis label, if any.
+ * @nullable
+ */
+ yAxisLabel: string | null;
+ }
+
+ /**
+ * The query that shows the fact. The page links to it.
+ * @nullable
+ */
+ export type StoryEvidenceQuery = {[key: string]: unknown} | null;
+
+ export interface StoryEvidence {
+ /**
+ * One fact that supports the chapter, in one sentence.
+ * @maxLength 400
+ */
+ text: string;
+ /**
+ * The query that shows the fact. The page links to it.
+ * @nullable
+ */
+ query?: StoryEvidenceQuery;
+ /**
+ * The short id of a saved insight that shows the fact. The page links to it.
+ * @nullable
+ * @pattern ^[A-Za-z0-9]{8}$
+ */
+ insightShortId?: string | null;
+ /**
+ * A link to the GitHub pull request or commit behind the fact. No other links are accepted.
+ * @maxLength 500
+ * @nullable
+ */
+ url?: string | null;
+ /** The MCP query tool that can redraw `query`. The page redraws the query only when this is set.
+ *
+ * * `query-trends` - Trends
+ * * `query-funnel` - Funnel
+ * * `query-retention` - Retention
+ * * `query-stickiness` - Stickiness
+ * * `query-paths` - Paths
+ * * `query-lifecycle` - Lifecycle */
+ queryTool?: StoryEvidenceQueryToolEnum | null;
+ /** The fact drawn as a chart, from its SQL. */
+ chart?: StoryEvidenceChart | null;
+ }
+
+ export interface StoryChapter {
+ /**
+ * The moment on the chart this chapter explains.
+ * @maxLength 80
+ */
+ title: string;
+ /**
+ * Inclusive indexes into the series' points. Null when the chapter's dates match no point.
+ * @minItems 2
+ * @maxItems 2
+ * @nullable
+ * @items.minimum 0
+ */
+ range: number[] | null;
+ /**
+ * What happened in this moment.
+ * @maxLength 400
+ * @nullable
+ */
+ summary: string | null;
+ /**
+ * The likely cause of this moment.
+ * @maxLength 600
+ * @nullable
+ */
+ cause: string | null;
+ /** How sure the investigation is of the cause.
+ *
+ * * `high` - High confidence
+ * * `medium` - Medium confidence
+ * * `low` - Low confidence */
+ confidence: StoryConfidenceEnum | null;
+ /**
+ * Why the confidence is what it is.
+ * @maxLength 200
+ * @nullable
+ */
+ confidenceReason: string | null;
+ /** The facts behind the cause. */
+ evidence: StoryEvidence[];
+ }
+
+ /**
+ * The insight query the explanation follows.
+ */
+ export type ExplainChartDataQuery = {[key: string]: unknown};
+
+ export interface ExplainChartData {
+ /** What the explanation walks through, whichever insight drew the chart. A funnel over time is a time series too.
+ *
+ * * `time_series` - Time series */
+ shape?: ChartExplanationShapeEnum;
+ /** The insight query the explanation follows. */
+ query: ExplainChartDataQuery;
+ /** Every series on the chart when it was explained. */
+ results: StorySeriesResult[];
+ /**
+ * The index in `results` the explanation follows.
+ * @minimum 0
+ */
+ seriesIndex: number;
+ /**
+ * The insight's name.
+ * @maxLength 400
+ * @nullable
+ */
+ insightName: string | null;
+ /** Whether the last point's period had not ended yet. */
+ lastPointInProgress: boolean;
+ /**
+ * One sentence a person could read in place of the whole explanation.
+ * @maxLength 300
+ */
+ headline: string;
+ /** The moments that stand out, in reading order. */
+ chapters: StoryChapter[];
+ /**
+ * Warnings the chart's query came back with.
+ * @maxItems 20
+ */
+ warnings?: unknown[];
+ }
+
+ export interface ChartExplanationAuthor {
+ /** The user's id. */
+ id: number;
+ /** The user's first name. */
+ first_name: string;
+ /** The user's last name. */
+ last_name: string;
+ /** The user's email address. */
+ email: string;
+ }
+
+ export interface ChartExplanation {
+ /** The chart explanation, as the insight page shows it. */
+ data: ExplainChartData;
+ /** Who saved the explanation, directly or through an agent. */
+ created_by: ChartExplanationAuthor | null;
+ /** The explanation's id, which its link carries. */
+ id: string;
+ /** The insight the explanation belongs to. */
+ insight_id: number;
+ /** When the explanation was first saved. */
+ created_at: string;
+ }
+
/**
* * `author_scout` - author_scout
* * `fleet_overview` - fleet_overview
@@ -58644,6 +58902,11 @@ export namespace Schemas {
depth?: InsightDataChecksDepthEnum;
}
+ export interface InsightExplanationCreate {
+ /** The chart explanation, as the insight page shows it. */
+ data: ExplainChartData;
+ }
+
/**
* The anomaly detector the alert uses in place of its threshold, or null for a threshold alert. It can't change through this API.
*/