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.

fix(alerts): write investigation notebooks as markdown (#98159)

posthog[bot]ea9041ed0750
diff --git a/posthog/temporal/ai/anomaly_investigation/notebook.py b/posthog/temporal/ai/anomaly_investigation/notebook.py
index 4ea6452be049..fe7bcbc25a31 100644
--- a/posthog/temporal/ai/anomaly_investigation/notebook.py
+++ b/posthog/temporal/ai/anomaly_investigation/notebook.py
@@ -1,7 +1,6 @@
import json
import uuid
from dataclasses import dataclass
-from typing import Any
from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
@@ -9,8 +8,8 @@ from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
from products.notebooks.backend.facade.content import (
TipTapContent,
TipTapNode,
+ convert_notebook_content_to_markdown,
create_bullet_list,
- create_empty_paragraph,
create_heading_with_text,
create_paragraph_with_text,
)
@@ -31,32 +30,28 @@ class NotebookRenderContext:
report: InvestigationReport
-def build_investigation_notebook(ctx: NotebookRenderContext) -> dict[str, Any]:
- """Render the agent's InvestigationReport into a TipTap document.
+def build_investigation_markdown(ctx: NotebookRenderContext) -> str:
+ """Render the agent's InvestigationReport into notebook markdown.
Keeps presentation concerns out of the agent loop. Embedded insight uses the
- SavedInsightNode ph-query form so the notebook always renders current data.
+ SavedInsightNode Query form so the notebook always renders current data.
"""
content: TipTapContent = []
content.append(create_heading_with_text(f"Investigation — {ctx.alert.name}", level=1))
content.append(create_paragraph_with_text(_summary_line(ctx)))
- content.append(create_empty_paragraph())
content.append(create_heading_with_text("Verdict", level=2))
verdict_text = VERDICT_LABEL.get(ctx.report.verdict, ctx.report.verdict)
content.append(create_paragraph_with_text(f"{verdict_text} — {ctx.report.summary}"))
- content.append(create_empty_paragraph())
metric_meaning = ctx.report.metric_meaning.strip()
if metric_meaning:
content.append(create_heading_with_text("What this metric measures", level=2))
content.append(create_paragraph_with_text(metric_meaning))
- content.append(create_empty_paragraph())
content.append(create_heading_with_text("Source insight", level=2))
content.append(_saved_insight_query_node(ctx.insight))
- content.append(create_empty_paragraph())
if ctx.report.hypotheses:
content.append(create_heading_with_text("Hypotheses", level=2))
@@ -70,18 +65,16 @@ def build_investigation_notebook(ctx: NotebookRenderContext) -> dict[str, Any]:
evidence = [e for e in hypothesis.evidence if e and e.strip()]
if evidence:
content.append(create_bullet_list(evidence))
- content.append(create_empty_paragraph())
recommendations = [r for r in ctx.report.recommendations if r and r.strip()]
if recommendations:
content.append(create_heading_with_text("Recommendations", level=2))
content.append(create_bullet_list(recommendations))
- content.append(create_empty_paragraph())
- content.append(create_heading_with_text("Run details", level=3, collapsed=True))
+ content.append(create_heading_with_text("Run details", level=3))
content.append(create_paragraph_with_text(_footer_line(ctx)))
- return {"type": "doc", "content": content}
+ return convert_notebook_content_to_markdown({"type": "doc", "content": content})
def _summary_line(ctx: NotebookRenderContext) -> str:
@@ -114,7 +107,6 @@ def _saved_insight_query_node(insight: Insight) -> TipTapNode:
return {
"type": "ph-query",
"attrs": {
- "height": None,
"title": insight.name or insight.short_id,
"nodeId": str(uuid.uuid4()),
"query": json.dumps(query),
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.py
index c9f05e6eb30a..d07ad9d3d985 100644
--- a/posthog/temporal/ai/anomaly_investigation/workflow.py
+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py
@@ -32,7 +32,7 @@ from posthog.tasks.alerts.utils import (
from posthog.temporal.ai.anomaly_investigation.charts import png_to_b64, render_series_chart
from posthog.temporal.ai.anomaly_investigation.event_provenance import alerted_series_event, describe_event_provenance
from posthog.temporal.ai.anomaly_investigation.metric_definition import describe_metric_definition
-from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebook
+from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_markdown
from posthog.temporal.ai.anomaly_investigation.prompts import build_anomaly_context
from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
from posthog.temporal.ai.anomaly_investigation.runner import run_investigation
@@ -44,6 +44,7 @@ from posthog.utils import absolute_uri
from products.alerts.backend.investigation_episode import EpisodeInvestigations, episode_investigations
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
from products.notebooks.backend.facade import api as notebooks
+from products.notebooks.backend.facade.content import build_markdown_notebook_content
from products.signals.backend.facade import api as signals
if TYPE_CHECKING:
@@ -194,7 +195,7 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
await _mark_failed(alert_check, f"Agent run failed: {err}")
raise
- notebook_content = build_investigation_notebook(
+ notebook_markdown = build_investigation_markdown(
NotebookRenderContext(
alert=alert,
alert_check=alert_check,
@@ -206,8 +207,8 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
notebook = await sync_to_async(notebooks.create_notebook, thread_sensitive=False)(
team.id,
title=f"Investigation — {alert.name or 'anomaly alert'}",
- content=notebook_content,
- text_content=result.report.summary,
+ content=build_markdown_notebook_content(notebook_markdown),
+ text_content=notebook_markdown,
created_by_id=user.id,
last_modified_by_id=user.id,
creation_source=notebooks.NotebookCreationSource.TEMPORAL_AGENT,
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py b/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
index 57b464e568b5..d131d0217340 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
@@ -1,6 +1,6 @@
from posthog.test.base import BaseTest
-from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebook
+from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_markdown
from posthog.temporal.ai.anomaly_investigation.report import InvestigationHypothesis, InvestigationReport
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
@@ -24,7 +24,7 @@ class TestAnomalyInvestigationNotebook(BaseTest):
)
return NotebookRenderContext(alert=alert, alert_check=alert_check, insight=insight, report=report)
- def test_builds_well_formed_tiptap_doc(self) -> None:
+ def test_builds_markdown_the_cell_tools_accept(self) -> None:
report = InvestigationReport(
verdict="true_positive",
metric_meaning="Unique users who loaded a page under /pricing each day.",
@@ -42,19 +42,19 @@ class TestAnomalyInvestigationNotebook(BaseTest):
recommendations=["Confirm the spike with the marketing team.", "Hold further alerting for 24h."],
tool_calls_used=3,
)
- doc = build_investigation_notebook(self._make_context(report))
+ ctx = self._make_context(report)
+ markdown = build_investigation_markdown(ctx)
- assert doc["type"] == "doc"
- headings = [node for node in doc["content"] if node.get("type") == "heading"]
- heading_texts = [node["content"][0]["text"] for node in headings if node.get("content")]
- assert any("Verdict" == t for t in heading_texts)
- assert any("What this metric measures" == t for t in heading_texts)
- assert any("Hypotheses" == t for t in heading_texts)
- assert any("Recommendations" == t for t in heading_texts)
+ assert "## Verdict" in markdown
+ assert "## What this metric measures" in markdown
+ assert "## Hypotheses" in markdown
+ assert "## Recommendations" in markdown
+ assert "### Run details" in markdown
+ assert "- Campaign ID 42 launched at 2024-06-01 08:00" in markdown
- # The saved insight node is present and uses the insight's short_id.
- ph_queries = [node for node in doc["content"] if node.get("type") == "ph-query"]
- assert len(ph_queries) == 1
+ # The source insight stays live through a SavedInsightNode Query component.
+ assert '<Query title="pageviews/day"' in markdown
+ assert f'query={{{{"kind":"SavedInsightNode","shortId":"{ctx.insight.short_id}"}}}}' in markdown
def test_handles_inconclusive_verdict_with_empty_sections(self) -> None:
report = InvestigationReport(
@@ -64,14 +64,9 @@ class TestAnomalyInvestigationNotebook(BaseTest):
recommendations=[],
tool_calls_used=0,
)
- doc = build_investigation_notebook(self._make_context(report))
- # Recommendations and Hypotheses headings should be absent when lists are empty.
- heading_texts = [
- node["content"][0]["text"]
- for node in doc["content"]
- if node.get("type") == "heading" and node.get("content")
- ]
- assert "Hypotheses" not in heading_texts
- assert "Recommendations" not in heading_texts
- assert "What this metric measures" not in heading_texts
- assert "Verdict" in heading_texts
+ markdown = build_investigation_markdown(self._make_context(report))
+
+ assert "## Hypotheses" not in markdown
+ assert "## Recommendations" not in markdown
+ assert "## What this metric measures" not in markdown
+ assert "## Verdict" in markdown
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
index 9523153c8ee9..fb79371f90d6 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
@@ -29,6 +29,8 @@ from products.alerts.backend.models.alert import (
)
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.exports.backend.models.exported_asset import ExportedAsset
+from products.notebooks.backend.facade.content import is_markdown_notebook_content
+from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.facade.models import Insight
@@ -101,6 +103,10 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):
assert self.alert_check.investigation_summary == "Confirmed spike caused by campaign launch."
assert self.alert_check.investigation_notebook_id is not None
+ # A follow-up agent appends through the MCP cell tools, which only accept a markdown notebook.
+ notebook = await sync_to_async(Notebook.objects.get)(id=self.alert_check.investigation_notebook_id)
+ assert is_markdown_notebook_content(notebook.content)
+
@pytest.mark.asyncio
@patch("posthog.tasks.alerts.utils.exports.render_png_export")
@patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")