: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): render Markdown in Slack report and signal deliveries (#95054)
Vojta Bartošfa0ea87633d3
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.pyindex dfdff4792630..02baed5e4a55 100644--- a/products/signals/backend/scout_harness/slack_delivery.py+++ b/products/signals/backend/scout_harness/slack_delivery.py@@ -24,14 +24,16 @@ from products.signals.backend.scout_harness.slack_charts import (strip_chart_blocks,)from products.signals.backend.slack_formatting import (- chunk_slack_mrkdwn,+ SLACK_MARKDOWN_TEXT_MAX_LEN,+ chunk_slack_text,+ defuse_slack_tokens,escape_slack_mrkdwn,group_segments_to_limit,- markdown_to_slack_mrkdwn,+ prepare_slack_markdown,slack_channel_id_from_target,+ slack_markdown_block,split_markdown_by_headings,strip_chart_references,- truncate_slack_section,)logger = structlog.get_logger(__name__)@@ -70,9 +72,9 @@ MAX_SCOUT_SLACK_DM_TARGETS = 5# before posting, since chart rendering can hold the worker long enough for the report to change.DELIVERABLE_REPORT_STATUSES = frozenset((SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT))-# Bound on the note snapshot a note-only edit carries through the Celery payload. Slack shows at-# most SLACK_SECTION_TEXT_MAX_LEN characters after conversion, so anything past this headroom is-# never rendered; the report keeps the full note either way.+# Bound on the note snapshot a note-only edit carries through the Celery payload. A note past this+# is clipped before Slack's own markdown-block cap applies; the report keeps the full note either+# way.MAX_SLACK_NOTE_SNAPSHOT_LEN = 6000# Posted as an in-thread reply under every scout Slack message, inviting @PostHog follow-ups.@@ -215,7 +217,7 @@ def _slack_channel_id(channel: str) -> str:def build_scout_slack_message(emission: SignalScoutEmission) -> tuple[list[dict], str]:- """Render a direct scout finding with the same safe Markdown conversion as inbox signals."""+ """Render a direct scout finding, with its description delivered as Markdown."""scout_name = _prettify_scout_name(emission.scout_run.skill_name)blocks: list[dict] = [{@@ -224,9 +226,9 @@ def build_scout_slack_message(emission: SignalScoutEmission) -> tuple[list[dict]}]- rendered_description = truncate_slack_section(markdown_to_slack_mrkdwn(emission.description.strip()))+ rendered_description = prepare_slack_markdown(emission.description.strip())if rendered_description:- blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered_description}})+ blocks.append(slack_markdown_block(rendered_description))details: list[str] = []if emission.severity:@@ -345,9 +347,9 @@ def build_scout_report_slack_message(# Chart links in the prose still reduce to their label; the charts themselves follow the prose# as image blocks, the way the inbox places charts the summary doesn't reference inline.summary_text = strip_chart_references((report.summary or "").strip())- rendered_summary = truncate_slack_section(markdown_to_slack_mrkdwn(summary_text))+ rendered_summary = prepare_slack_markdown(summary_text)if rendered_summary:- blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered_summary}})+ blocks.append(slack_markdown_block(rendered_summary))# `render_budget` shares one render allowance across a delivery's initial build and any rebuild.blocks.extend(build_scout_report_chart_blocks(report, run, delivery_id=delivery_id, budget=render_budget))@@ -357,24 +359,24 @@ def build_scout_report_slack_message(def _report_summary_chunks(report: SignalReport) -> list[str]:- """Convert the report summary to mrkdwn and split it into one chunk per section.+ """Split the report summary into one chunk of Markdown per section.Called only for a threaded delivery. The first chunk leads the channel and each later onebecomes a reply, so the thread mirrors the report's outline at any length. Length is not the- test: a typical digest fits inside one Slack section, so a length test leaves it as one wall of+ test: a typical digest fits inside one Slack block, so a length test leaves it as one wall oftext. A section is opened by a Markdown heading or a bold label, so the summary threads whetherthe scout wrote `## Evidence` or `**Evidence**`. A summary with neither has no seam and staysone chunk. A summary with more sections than `MAX_THREAD_SEGMENTS` has them grouped, so onedelivery cannot post a reply per paragraph of a malformed report. A section too long for one- Slack section is hard-chunked on its line ends. The split runs after `strip_chart_references`+ Slack block is hard-chunked on its line ends. The split runs after `strip_chart_references`so a chart link never straddles two messages."""summary_text = strip_chart_references((report.summary or "").strip())chunks: list[str] = []for segment in group_segments_to_limit(split_markdown_by_headings(summary_text)):- rendered_segment = markdown_to_slack_mrkdwn(segment.strip())+ rendered_segment = defuse_slack_tokens(segment.strip())if not rendered_segment:continue- chunks.extend(chunk_slack_mrkdwn(rendered_segment))+ chunks.extend(chunk_slack_text(rendered_segment, SLACK_MARKDOWN_TEXT_MAX_LEN))return chunks@@ -461,7 +463,7 @@ def build_scout_report_thread_slack_messages(The lead carries the scout name, the report title, the first summary chunk, the charts, and thereport link. Every later chunk becomes a threaded reply, so the channel shows a short lead and- the thread holds the report's sections in order, with nothing clipped at the section cap. A+ the thread holds the report's sections in order, with nothing clipped at the block's cap. Asummary that opens with a heading puts that first section in the lead, so the channel nevershows a title-only stub."""scout_name = _prettify_scout_name(run.skill_name)@@ -476,13 +478,13 @@ def build_scout_report_thread_slack_messages(chunks = _report_summary_chunks(report)if chunks:- lead_blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": chunks[0]}})+ lead_blocks.append(slack_markdown_block(chunks[0]))# Charts ride the lead rather than a reply: the lead is the message the channel sees, and the# replies only carry the summary's tail for anyone who opens the thread.lead_blocks.extend(build_scout_report_chart_blocks(report, run, delivery_id=delivery_id, budget=render_budget))lead_blocks.append(_report_link_block(report))- reply_blocks = [[{"type": "section", "text": {"type": "mrkdwn", "text": chunk}}] for chunk in chunks[1:]]+ reply_blocks = [[slack_markdown_block(chunk)] for chunk in chunks[1:]]fallback = f"Scout · {escape_slack_mrkdwn(scout_name)}: {escape_slack_mrkdwn(header[:200])}"return ScoutReportThreadMessages(lead_blocks=lead_blocks, fallback=fallback, reply_blocks=reply_blocks)@@ -511,9 +513,9 @@ def build_scout_report_note_slack_message(]note_text = strip_chart_references(note.strip())- rendered_note = truncate_slack_section(markdown_to_slack_mrkdwn(note_text))+ rendered_note = prepare_slack_markdown(note_text)if rendered_note:- blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered_note}})+ blocks.append(slack_markdown_block(rendered_note))blocks.append(_report_link_block(report))fallback = f"Scout · {escape_slack_mrkdwn(scout_name)} added a note to: {escape_slack_mrkdwn(header[:200])}"diff --git a/products/signals/backend/slack_formatting.py b/products/signals/backend/slack_formatting.pyindex cddb9103ebd2..9aa096a47e02 100644--- a/products/signals/backend/slack_formatting.py+++ b/products/signals/backend/slack_formatting.py@@ -2,25 +2,18 @@ from __future__ import annotationsimport refrom collections import Counter-from typing import TYPE_CHECKINGfrom posthog.dataclasses import frozen-if TYPE_CHECKING:- from markdown_to_mrkdwn import SlackMarkdownConverter--_SLACK_MRKDWN_CONVERTER: SlackMarkdownConverter | None = None-SLACK_SECTION_TEXT_MAX_LEN = 2900--# Matches a converter-emitted Slack angle token: `<dest>` or `<dest|label>`. Input `<`/`>`-# are escaped before conversion, so any literal angle bracket here was produced by the converter.-_SLACK_ANGLE_TOKEN_RE = re.compile(r"<([^<>|]*)(\|[^<>]*)?>")+# A Slack `markdown` block takes Markdown directly, and Slack budgets 12,000 characters across+# every markdown block in one message. A message carries one, and the headroom covers the blocks+# around it.+SLACK_MARKDOWN_TEXT_MAX_LEN = 11500# A summary places a chart inline with a markdown link targeting `chart:<chart_id>`. Slack cannot-# place an image mid-sentence and degrades the link badly either way: the mrkdwn converter emits a-# `<chart:id|label>` token that `_defang_unsafe_slack_tokens` escapes into visible `<…>`, and-# the excerpt path shows the raw `[label](chart:id)` syntax. So the link is reduced to its label-# first; report delivery renders the charts as image blocks after the prose instead.+# place an image mid-sentence, and the link degrades badly if left alone: `chart:` is no scheme a+# reader can follow, so the label becomes a dead link in the prose. So the link is reduced to its+# label first; report delivery renders the charts as image blocks after the prose instead.## The shapes matched are the ones the inbox's markdown parse resolves and therefore draws a chart# for: any target rather than the id charset (a typo is just as unrenderable), all three CommonMark@@ -82,6 +75,31 @@ def escape_slack_mrkdwn(text: str) -> str:return text.replace("&", "&").replace("<", "<").replace(">", ">")+# The Slack tokens that can address somebody or lie about where they point: the mentions+# (`<@U…>`, `<#C…>`, `<!here>`, `<!subteam^S…>`) and the labelled link form, whose `<dest|label>`+# shape lets the label say one thing while the link goes somewhere else. A bare `<https://…>` is+# neither — it links to exactly what it displays — so it is left for Slack to render.+_SLACK_TOKEN_RE = re.compile(r"<(?:[@#!][^<>]*|[^<>|]*\|[^<>]*)>")+++def defuse_slack_tokens(text: str) -> str:+ """Neutralize Slack's own tokens in untrusted Markdown, leaving the rest of the text alone.++ Slack parses these tokens inside a markdown block, so raw content from a report, a GitHub+ issue, or a support ticket reaches a reader as a live `@here`, a live mention, or a link whose+ label hides its destination. Escaping the angle brackets stops all three, and Slack renders the+ escaped form back as the literal characters.++ Only a token is rewritten. Escaping every `<` instead corrupts the three things that carry+ angle brackets innocently: a code span (`Vec<T>`), a CommonMark autolink, and an angle-bracket+ link destination, none of which decode the entity back.++ `&` is left alone throughout. Slack decodes an entity for display without re-reading the result+ as a token, so escaping it buys no safety, and it does not decode inside a link destination,+ where `&` would corrupt every query string a report links to."""+ return _SLACK_TOKEN_RE.sub(lambda m: m.group(0).replace("<", "<").replace(">", ">"), text)++def is_safe_slack_http_url(value: object) -> bool:"""Allow only URL forms that cannot break out of a Slack `<url|label>` token."""if not isinstance(value, str):@@ -91,39 +109,24 @@ def is_safe_slack_http_url(value: object) -> bool:return not any(char in value for char in ("<", ">", "|"))-def _defang_unsafe_slack_tokens(text: str) -> str:- """Render converter-created non-URL angle tokens as inert literal text."""-- def _replace(match: re.Match[str]) -> str:- if is_safe_slack_http_url(match.group(1)):- return match.group(0)- return match.group(0).replace("<", "<").replace(">", ">")-- return _SLACK_ANGLE_TOKEN_RE.sub(_replace, text)---def _get_slack_mrkdwn_converter() -> SlackMarkdownConverter:- """Lazily import and cache the converter so it stays off the django.setup() path."""- global _SLACK_MRKDWN_CONVERTER- if _SLACK_MRKDWN_CONVERTER is None:- from markdown_to_mrkdwn import (- SlackMarkdownConverter, # noqa: PLC0415 — keeps the dep off the app-registry startup path- )+def truncate_slack_text(text: str, limit: int) -> str:+ """Keep text below the block's character limit with headroom."""+ if len(text) <= limit:+ return text+ return text[: limit - 1].rstrip() + "…"- _SLACK_MRKDWN_CONVERTER = SlackMarkdownConverter()- return _SLACK_MRKDWN_CONVERTER+def slack_markdown_block(text: str) -> dict:+ """The Slack block that renders Markdown, for text `prepare_slack_markdown` has already made safe."""+ return {"type": "markdown", "text": text}-def markdown_to_slack_mrkdwn(text: str) -> str:- """Convert untrusted Markdown to Slack mrkdwn without allowing mention injection."""- return _defang_unsafe_slack_tokens(_get_slack_mrkdwn_converter().convert(escape_slack_mrkdwn(text)))+def prepare_slack_markdown(text: str) -> str:+ """Make untrusted Markdown safe to hand Slack, and keep it inside one markdown block.-def truncate_slack_section(text: str) -> str:- """Keep mrkdwn below Slack's 3000-character section limit with headroom."""- if len(text) <= SLACK_SECTION_TEXT_MAX_LEN:- return text- return text[: SLACK_SECTION_TEXT_MAX_LEN - 1].rstrip() + "…"+ Defusing precedes truncation so a trailing cut can only shorten an already-inert token, never+ leave a live mention behind."""+ return truncate_slack_text(defuse_slack_tokens(text), SLACK_MARKDOWN_TEXT_MAX_LEN)# A top-of-line ATX heading (`# `…`###### `). The scout writes its summary in Markdown, so its own@@ -274,17 +277,18 @@ def group_segments_to_limit(segments: list[str], limit: int = MAX_THREAD_SEGMENT# End of a sentence, allowing a closing quote or bracket before the space that follows it._SENTENCE_END_RE = re.compile(r"[.!?…][\"')\]]*\s")_WHITESPACE_RUN_RE = re.compile(r"\s+")-# A converter-emitted angle token left open at the end of a candidate chunk, as in `<https://ex`.-# Slack renders each half of a broken link as visible junk, so a cut here moves back before the `<`.-_TRAILING_OPEN_ANGLE_RE = re.compile(r"<[^<>]*$")+# A Markdown construct left open at the end of a candidate chunk: a link whose destination has not+# closed (`[label](https://ex`), or a label that has not (`[the failing`). Slack renders each half+# of a split link as visible junk, so a cut here moves back before the `[` that opened it.+_OPEN_MARKDOWN_LINK_RE = re.compile(r"\[[^\[\]]*\]\([^()]*$|\[[^\[\]]*$")# A break earlier than this share of the limit spends a whole reply on a stub, so the ladder in# `_line_break_index` prefers the next (later-breaking) rung over an early sentence or word end._MIN_LINE_BREAK_FILL = 0.6-def _pull_back_before_open_angle(window: str, index: int) -> int:- """Move a cut back before an angle token it would otherwise split, or leave it alone."""- match = _TRAILING_OPEN_ANGLE_RE.search(window[:index])+def _pull_back_before_open_link(window: str, index: int) -> int:+ """Move a cut back before a Markdown link it would otherwise split, or leave it alone."""+ match = _OPEN_MARKDOWN_LINK_RE.search(window[:index])return match.start() if match else index@@ -293,44 +297,44 @@ def _line_break_index(line: str, limit: int) -> int:Tries a sentence end, then any whitespace, so a reply never opens mid-word. Falls back to thelimit only for an unbreakable run such as a long URL or an encoded blob. Every rung stays out of- an angle token, because half a link is worse to read than an early break."""+ a Markdown link, because half a link is worse to read than an early break."""window = line[:limit]floor = int(limit * _MIN_LINE_BREAK_FILL)for pattern in (_SENTENCE_END_RE, _WHITESPACE_RUN_RE):matches = list(pattern.finditer(window))if not matches:continue- index = _pull_back_before_open_angle(window, matches[-1].end())+ index = _pull_back_before_open_link(window, matches[-1].end())if index >= floor:return index- hard_cut = _pull_back_before_open_angle(window, limit)- # A token longer than the whole window has nowhere safe to break, so the link is split anyway.+ hard_cut = _pull_back_before_open_link(window, limit)+ # A link longer than the whole window has nowhere safe to break, so it is split anyway.return hard_cut if hard_cut > 0 else limit-def chunk_slack_mrkdwn(text: str) -> list[str]:- """Split converted mrkdwn into chunks that each fit one Slack section, breaking on line ends.+def chunk_slack_text(text: str, limit: int) -> list[str]:+ """Split text into chunks that each fit one Slack block, breaking on line ends.A line longer than the limit on its own breaks at the best boundary `_line_break_index` finds,so a report written as unbroken prose still reads as sentences. Returns no empty chunks, so the- tail of a long report reaches the channel instead of being clipped at the section cap."""+ tail of a long report reaches the channel instead of being clipped at the block's cap."""text = text.strip()if not text:return []- if len(text) <= SLACK_SECTION_TEXT_MAX_LEN:+ if len(text) <= limit:return [text]chunks: list[str] = []current = ""for line in text.split("\n"):- while len(line) > SLACK_SECTION_TEXT_MAX_LEN:+ while len(line) > limit:if current:chunks.append(current.rstrip())current = ""- cut = _line_break_index(line, SLACK_SECTION_TEXT_MAX_LEN)+ cut = _line_break_index(line, limit)chunks.append(line[:cut].rstrip())line = line[cut:]candidate = f"{current}\n{line}" if current else line- if len(candidate) > SLACK_SECTION_TEXT_MAX_LEN:+ if len(candidate) > limit:if current:chunks.append(current.rstrip())current = linediff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.pyindex 6ba720ac9929..41d71469325f 100644--- a/products/signals/backend/slack_inbox_notifications.py+++ b/products/signals/backend/slack_inbox_notifications.py@@ -41,10 +41,10 @@ from products.signals.backend.report_generation.resolve_reviewers import (from products.signals.backend.slack_formatting import (escape_slack_mrkdwn as _escape_mrkdwn,is_safe_slack_http_url as _is_safe_http_url,- markdown_to_slack_mrkdwn as _markdown_to_slack_mrkdwn,+ prepare_slack_markdown as _prepare_markdown,slack_channel_id_from_target as _channel_id_from_target,+ slack_markdown_block as _markdown_block,strip_chart_references as _strip_chart_references,- truncate_slack_section as _truncate_slack_section,)# Actionability values shown in the inbox Reports tab. Slack notifications mirror that tab, so a@@ -340,23 +340,23 @@ def _build_message_blocks(if sources_line:meta_parts.append(sources_line)if repository:- # Escape LLM/user-derived strings before they enter mrkdwn so a crafted value can't- # inject `<!here>` / `<@U…>` mentions. Reviewer mentions are added pre-escaped elsewhere.- meta_parts.append(_escape_mrkdwn(repository))+ meta_parts.append(repository)+ # The body is escaped once as a whole below, so the LLM-derived parts assembled here stay raw.+ # The `**` this adds is the one piece of Markdown the message means, and escaping leaves it be.body_parts: list[str] = []if meta_parts:- body_parts.append(f"*{' · '.join(meta_parts)}*")+ body_parts.append(f"**{' · '.join(meta_parts)}**")# Strip before excerpting so truncation can't slice a chart link mid-syntax.summary_text = _summary_excerpt(_strip_chart_references(report.summary or ""))if summary_text:- body_parts.append(_escape_mrkdwn(summary_text))+ body_parts.append(summary_text)if not body_parts:- body_parts.append(f"*{_escape_mrkdwn(title_line)}*")+ body_parts.append(f"**{title_line}**")blocks: list[dict] = [{"type": "header", "text": {"type": "plain_text", "text": header_text}},- {"type": "section", "text": {"type": "mrkdwn", "text": "\n\n".join(body_parts)}},+ _markdown_block(_prepare_markdown("\n\n".join(body_parts))),]# Reviewer mentions sit in the context line — they still carry the `<@U…>` token so Slack pings them.@@ -478,13 +478,10 @@ def _build_signal_thread_blocks(signal: dict) -> tuple[list[dict], str]:content = (signal.get("content") or "").strip()if content:- # Render markdown to mrkdwn first, then truncate the rendered output: truncating raw- # markdown could slice a link/emphasis token mid-syntax, and conversion can lengthen- # text past Slack's section limit. Truncating post-defang output stays safe — a- # trailing cut can't synthesize a live mention (no closing `>` can appear).- rendered = _markdown_to_slack_mrkdwn(content)- rendered = _truncate_slack_section(rendered)- blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered}})+ # Slack renders the signal's Markdown itself, so the content goes out as written. Escaping+ # comes first: a trailing cut can then only shorten an already-inert token, never leave a+ # live mention behind.+ blocks.append(_markdown_block(_prepare_markdown(content)))detail_parts = _signal_detail_parts(source_product, extra)if detail_parts:diff --git a/products/signals/backend/test/test_scout_slack_charts.py b/products/signals/backend/test/test_scout_slack_charts.pyindex 72535db50d52..0933ba1df7df 100644--- a/products/signals/backend/test/test_scout_slack_charts.py+++ b/products/signals/backend/test/test_scout_slack_charts.py@@ -369,7 +369,7 @@ class TestScoutSlackReportCharts(BaseTest):url_mock.return_value = "https://img/1"blocks, _ = build_scout_report_slack_message(report, run)- assert [b["type"] for b in blocks] == ["context", "header", "section", "actions"]+ assert [b["type"] for b in blocks] == ["context", "header", "markdown", "actions"]def test_report_message_places_charts_between_prose_and_link(self) -> None:run = self._make_run(created_by=self.user)@@ -380,5 +380,5 @@ class TestScoutSlackReportCharts(BaseTest):url_mock.return_value = "https://img/1"blocks, _ = build_scout_report_slack_message(report, run)- assert [b["type"] for b in blocks] == ["context", "header", "section", "section", "image", "actions"]- assert blocks[2]["text"]["text"] == "Look at signups."+ assert [b["type"] for b in blocks] == ["context", "header", "markdown", "section", "image", "actions"]+ assert blocks[2]["text"] == "Look at signups."diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.pyindex a75949f02a6c..dfac5da7c190 100644--- a/products/signals/backend/test/test_scout_slack_delivery.py+++ b/products/signals/backend/test/test_scout_slack_delivery.py@@ -28,6 +28,7 @@ from products.signals.backend.scout_harness.slack_delivery import (post_scout_emission_to_slack,)from products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_delivery+from products.signals.backend.slack_formatting import SLACK_MARKDOWN_TEXT_MAX_LENfrom products.signals.backend.tasks import deliver_scout_slack_output, enqueue_scout_slack_delivery@@ -117,7 +118,7 @@ class TestScoutSlackDelivery(BaseTest):source_id=f"run:{run.id}:finding:checkout-500s",)- def test_posts_safe_mrkdwn_but_does_not_invite_followup_for_child_environment(self) -> None:+ def test_posts_safe_markdown_but_does_not_invite_followup_for_child_environment(self) -> None:emission = self._make_emission("**Checkout** failures [trace](https://example.com/trace) <!channel> [ping](!here)")@@ -144,12 +145,12 @@ class TestScoutSlackDelivery(BaseTest):assert call["channel"] == "CSCOUTS"assert call["client_msg_id"] == str(emission.id)assert "thread_ts" not in call- section = call["blocks"][1]["text"]["text"]- assert "*Checkout*" in section- assert "<https://example.com/trace|trace>" in section- assert "<!channel>" not in section- assert "<!here>" not in section- assert "<!channel>" in section+ markdown = call["blocks"][1]["text"]+ assert "**Checkout**" in markdown+ assert "[trace](https://example.com/trace)" in markdown+ assert "<!channel>" not in markdown+ assert "<!here>" not in markdown+ assert "<!channel>" in markdownassert call["blocks"][-1]["elements"][0]["url"] == (f"{settings.SITE_URL}/project/{self.team.id}/inbox/scouts/signals-scout-error-tracking/checkout%2F500s")@@ -161,7 +162,12 @@ class TestScoutSlackDelivery(BaseTest):team=self.team,status=SignalReport.Status.READY,title="Checkout failures",- summary="**Checkout** failed for <!channel> [trace](https://example.com/trace)",+ summary=(+ "**Checkout** failed for <!channel> [trace](https://example.com/trace)\n\n"+ "| PR | Status |\n"+ "| --- | --- |\n"+ "| [#93147 fix(checkout): retry 500s](https://example.com/pull/93147) | ready |\n"+ ),)integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)fake_client = MagicMock()@@ -184,11 +190,15 @@ class TestScoutSlackDelivery(BaseTest):assert call["channel"] == "CSCOUTS"assert call["client_msg_id"] == delivery_idassert "thread_ts" not in call- section = call["blocks"][2]["text"]["text"]- assert "*Checkout*" in section- assert "<!channel>" not in section- assert "<!channel>" in section- assert "<https://example.com/trace|trace>" in section+ markdown = call["blocks"][2]["text"]+ assert "**Checkout**" in markdown+ assert "<!channel>" not in markdown+ assert "<!channel>" in markdown+ assert "[trace](https://example.com/trace)" in markdown+ # A link inside a table reached Slack as raw `[label](url)` while delivery converted the+ # summary to mrkdwn: the converter lifted tables out before converting anything, then put+ # the cells back untouched.+ assert "[#93147 fix(checkout): retry 500s](https://example.com/pull/93147)" in markdownassert call["blocks"][-1]["elements"][0]["url"] == (f"{settings.SITE_URL}/project/{self.team.id}/inbox/reports/{report.id}")@@ -229,11 +239,11 @@ class TestScoutSlackDelivery(BaseTest):context = call["blocks"][0]["elements"][0]["text"]assert "added a note to an existing report" in contextassert call["blocks"][1]["text"]["text"] == "Checkout failures"- section = call["blocks"][2]["text"]["text"]- assert "*error rate*" in section- assert "<!channel>" not in section- assert "<!channel>" in section- assert "failed for many users" not in section+ markdown = call["blocks"][2]["text"]+ assert "**error rate**" in markdown+ assert "<!channel>" not in markdown+ assert "<!channel>" in markdown+ assert "failed for many users" not in markdownassert call["blocks"][-1]["elements"][0]["url"] == (f"{settings.SITE_URL}/project/{self.team.id}/inbox/reports/{report.id}")@@ -362,13 +372,13 @@ class TestScoutSlackDelivery(BaseTest):replies = calls[1:]assert len(replies) > 1assert all(reply.kwargs["thread_ts"] == "1785418710.000500" for reply in replies)- # Every posted section stays within the cap, and nothing is ellipsis-truncated.- section_texts = [- block["text"]["text"] for call in calls for block in call.kwargs["blocks"] if block["type"] == "section"+ # Every posted chunk stays within the cap, and nothing is ellipsis-truncated.+ markdown_texts = [+ block["text"] for call in calls for block in call.kwargs["blocks"] if block["type"] == "markdown"]- assert all(len(text) <= 2900 for text in section_texts)- assert not any(text.endswith("…") for text in section_texts)- assert any(tail_marker in text for text in section_texts)+ assert all(len(text) <= SLACK_MARKDOWN_TEXT_MAX_LEN for text in markdown_texts)+ assert not any(text.endswith("…") for text in markdown_texts)+ assert any(tail_marker in text for text in markdown_texts)@parameterized.expand([@@ -412,8 +422,8 @@ class TestScoutSlackDelivery(BaseTest):calls = fake_client.chat_postMessage.call_args_listassert len(calls) == 4assert "thread_ts" not in calls[0].kwargs- lead_sections = [block["text"]["text"] for block in calls[0].kwargs["blocks"] if block["type"] == "section"]- assert lead_sections == ["Lead line."]+ lead_chunks = [block["text"] for block in calls[0].kwargs["blocks"] if block["type"] == "markdown"]+ assert lead_chunks == ["Lead line."]first_reply, second_reply = calls[1].kwargs, calls[2].kwargs# Slack rejects a client_msg_id that is not a UUID, and the reply loop swallows the error,# so a malformed id costs every reply while the delivery still reports success.@@ -421,10 +431,10 @@ class TestScoutSlackDelivery(BaseTest):assert [str(uuid.UUID(reply_id)) for reply_id in reply_ids] == reply_idsassert len(set(reply_ids)) == 2assert first_reply["thread_ts"] == "1785418710.000600"- assert "First" in first_reply["blocks"][0]["text"]["text"]- assert "Detail" in first_reply["blocks"][0]["text"]["text"]- assert "Second" not in first_reply["blocks"][0]["text"]["text"]- assert "Second" in second_reply["blocks"][0]["text"]["text"]+ assert "First" in first_reply["blocks"][0]["text"]+ assert "Detail" in first_reply["blocks"][0]["text"]+ assert "Second" not in first_reply["blocks"][0]["text"]+ assert "Second" in second_reply["blocks"][0]["text"]assert calls[3].kwargs["blocks"][0]["type"] == "context"def test_threaded_report_without_section_labels_posts_a_single_message(self) -> None:@@ -458,9 +468,9 @@ class TestScoutSlackDelivery(BaseTest):calls = fake_client.chat_postMessage.call_args_listassert len(calls) == 2assert "thread_ts" not in calls[0].kwargs- section_texts = [block["text"]["text"] for block in calls[0].kwargs["blocks"] if block["type"] == "section"]- assert len(section_texts) == 1- assert "second one" in section_texts[0]+ markdown_texts = [block["text"] for block in calls[0].kwargs["blocks"] if block["type"] == "markdown"]+ assert len(markdown_texts) == 1+ assert "second one" in markdown_texts[0]assert calls[1].kwargs["blocks"][0]["type"] == "context"def test_reply_posted_regardless_of_ai_approval(self) -> None:@@ -951,8 +961,8 @@ class TestScoutSlackDelivery(BaseTest):)rejected, resent = (call.kwargs["blocks"] for call in fake_client.chat_postMessage.call_args_list[:2])- assert [b["type"] for b in rejected] == ["context", "header", "section", "section", "image", "actions"]- assert [b["type"] for b in resent] == ["context", "header", "section", "actions"]+ assert [b["type"] for b in rejected] == ["context", "header", "markdown", "section", "image", "actions"]+ assert [b["type"] for b in resent] == ["context", "header", "markdown", "actions"]def test_task_retries_transient_delivery_failure(self) -> None:emission = self._make_emission()diff --git a/products/signals/backend/test/test_slack_formatting.py b/products/signals/backend/test/test_slack_formatting.pyindex 154f1f946bca..75e315b16468 100644--- a/products/signals/backend/test/test_slack_formatting.py+++ b/products/signals/backend/test/test_slack_formatting.py@@ -5,10 +5,11 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom products.signals.backend.slack_formatting import (- SLACK_SECTION_TEXT_MAX_LEN,- chunk_slack_mrkdwn,+ SLACK_MARKDOWN_TEXT_MAX_LEN,+ chunk_slack_text,+ defuse_slack_tokens,+ escape_slack_mrkdwn,group_segments_to_limit,- markdown_to_slack_mrkdwn,split_markdown_by_headings,strip_chart_references,)@@ -63,14 +64,13 @@ class TestStripChartReferences(SimpleTestCase):def test_reduces_chart_links_to_their_label(self, _name: str, summary: str, expected: str) -> None:assert strip_chart_references(summary) == expected- def test_stripped_summary_survives_slack_conversion_without_markup(self) -> None:- # Left in place, the converter emits `<chart:signups-drop|Daily signups>`, which the safety- # wrapper escapes because the destination is not http(s) — visible markup in every- # notification for a report carrying an inline chart.- rendered = markdown_to_slack_mrkdwn(strip_chart_references("[Daily signups](chart:signups-drop)"))+ def test_stripped_summary_reaches_slack_without_markup(self) -> None:+ # Left in place, the link reaches Slack pointing at `chart:signups-drop`, a scheme no reader+ # can follow — a dead link in every notification for a report carrying an inline chart.+ rendered = escape_slack_mrkdwn(strip_chart_references("[Daily signups](chart:signups-drop)"))assert "chart:" not in rendered- assert "<" not in rendered+ assert "[" not in renderedassert "Daily signups" in rendered@parameterized.expand(@@ -94,6 +94,44 @@ class TestStripChartReferences(SimpleTestCase):assert time.perf_counter() - started < 0.5+class TestDefuseSlackTokens(SimpleTestCase):+ @parameterized.expand(+ [+ ("user_mention", "ping <@U12345678> now"),+ ("channel_link", "see <#C12345678> for more"),+ ("broadcast", "heads up <!here> everyone"),+ ("subteam", "ask <!subteam^S12345678> about it"),+ ("labelled_link_hides_its_target", "click <https://evil.example.com|your bank> now"),+ ("labelled_link_without_a_scheme", "click <evil.example.com|your bank> now"),+ ]+ )+ def test_a_token_that_pings_or_misleads_is_defused(self, _name: str, text: str) -> None:+ # Slack parses these inside a markdown block, so untrusted content reaches a reader as a+ # live ping or as a label that hides where the link goes.+ defused = defuse_slack_tokens(text)++ assert "<" not in defused+ assert ">" not in defused+ assert "<" in defused and ">" in defused++ @parameterized.expand(+ [+ ("code_span_generic", "the type is `Vec<T>` here"),+ ("code_span_comparison", "the guard is `count < 5` here"),+ ("autolink", "see <https://example.com/plain> for more"),+ ("angle_bracket_link_destination", "see [the run](<https://example.com/p?q=1&x=2>)"),+ ("bare_comparison", "fires when count < 5 and count > 1"),+ ("ampersand_in_prose", "research & development"),+ ("ampersand_in_a_link", "see [the run](https://example.com/i?a=1&b=2)"),+ ]+ )+ def test_text_that_only_looks_like_a_token_is_left_alone(self, _name: str, text: str) -> None:+ # Escaping every angle bracket instead corrupts all of these: Slack decodes the entity in+ # prose but not inside a code span or a link destination, so the escape shows through as+ # `<` or breaks the link outright.+ assert defuse_slack_tokens(text) == text++class TestSplitMarkdownByHeadings(SimpleTestCase):def test_lead_precedes_one_segment_per_heading(self) -> None:summary = "Intro line.\n\n## First\nbody one\n\n## Second\nbody two"@@ -236,34 +274,35 @@ class TestSplitMarkdownByHeadings(SimpleTestCase):assert [segment[: len(start)] for segment, start in zip(segments[1:], expected_starts)] == expected_starts-class TestChunkSlackMrkdwn(SimpleTestCase):+class TestChunkSlackText(SimpleTestCase):def test_short_text_is_one_chunk(self) -> None:- assert chunk_slack_mrkdwn("short") == ["short"]+ assert chunk_slack_text("short", SLACK_MARKDOWN_TEXT_MAX_LEN) == ["short"]- def test_long_text_splits_within_the_section_limit_without_losing_the_tail(self) -> None:- # The bug this guards: a summary past the section cap used to be truncated with an ellipsis,- # dropping everything after ~2,900 characters. Chunking must keep every line.- lines = [f"line {index}" for index in range(600)]- chunks = chunk_slack_mrkdwn("\n".join(lines))+ def test_long_text_splits_within_the_limit_without_losing_the_tail(self) -> None:+ # The bug this guards: a summary past the cap used to be truncated with an ellipsis,+ # dropping everything after it. Chunking must keep every line. The line count comes off the+ # limit so raising the cap cannot quietly leave this under it.+ lines = [f"line {index}" for index in range(SLACK_MARKDOWN_TEXT_MAX_LEN // 5)]+ chunks = chunk_slack_text("\n".join(lines), SLACK_MARKDOWN_TEXT_MAX_LEN)assert len(chunks) > 1- assert all(len(chunk) <= SLACK_SECTION_TEXT_MAX_LEN for chunk in chunks)+ assert all(len(chunk) <= SLACK_MARKDOWN_TEXT_MAX_LEN for chunk in chunks)recovered = "\n".join(chunks)assert all(line in recovered for line in lines)@parameterized.expand([- ("plain_run", "x" * (SLACK_SECTION_TEXT_MAX_LEN * 2 + 5)),- ("link_longer_than_a_section", "<https://example.com/" + "z" * (SLACK_SECTION_TEXT_MAX_LEN * 2) + "|l>"),+ ("plain_run", "x" * (SLACK_MARKDOWN_TEXT_MAX_LEN * 2 + 5)),+ ("link_longer_than_a_chunk", "https://example.com/" + "z" * (SLACK_MARKDOWN_TEXT_MAX_LEN * 2)),])def test_unbreakable_run_is_hard_sliced(self, _name: str, line: str) -> None:# A run with no sentence, word, or token boundary has nowhere safe to break, so it is sliced# at the limit. Guards both halves of that fallback: it has to terminate, and it has to keep# every character rather than dropping the remainder.- chunks = chunk_slack_mrkdwn(line)+ chunks = chunk_slack_text(line, SLACK_MARKDOWN_TEXT_MAX_LEN)- assert all(len(chunk) <= SLACK_SECTION_TEXT_MAX_LEN for chunk in chunks)+ assert all(len(chunk) <= SLACK_MARKDOWN_TEXT_MAX_LEN for chunk in chunks)assert "".join(chunks) == line@parameterized.expand(@@ -278,20 +317,27 @@ class TestChunkSlackMrkdwn(SimpleTestCase):# the retry..."). Comparing word sequences catches that, because a mid-word cut turns one# word into two and no longer round-trips.line = (sentence * 400).strip()- chunks = chunk_slack_mrkdwn(line)+ chunks = chunk_slack_text(line, SLACK_MARKDOWN_TEXT_MAX_LEN)assert len(chunks) > 1- assert all(len(chunk) <= SLACK_SECTION_TEXT_MAX_LEN for chunk in chunks)+ assert all(len(chunk) <= SLACK_MARKDOWN_TEXT_MAX_LEN for chunk in chunks)assert " ".join(chunks).split() == line.split()- def test_link_spanning_the_section_boundary_is_kept_whole(self) -> None:- # The bug this guards: a cut inside a converter-emitted `<url|label>` token leaves half a- # link in each message, and Slack renders both halves as visible junk.- link = "<https://example.com/a/very/long/path|the failing request>"- line = "x" * (SLACK_SECTION_TEXT_MAX_LEN - 20) + link + " and the prose that follows it."- chunks = chunk_slack_mrkdwn(line)-- assert all(len(chunk) <= SLACK_SECTION_TEXT_MAX_LEN for chunk in chunks)+ @parameterized.expand(+ [+ ("in_prose", "[the failing request](https://example.com/a/very/long/path?trace=1)", ""),+ ("in_a_table_row", "[#93147 the failing request](https://example.com/pull/93147)", "| "),+ ]+ )+ def test_markdown_link_spanning_the_limit_is_kept_whole(self, _name: str, link: str, prefix: str) -> None:+ # A cut inside `[label](url)` leaves half the syntax in each message, and Slack renders both+ # halves as visible junk instead of a link. A summary may run to 20,000 characters, so a link+ # can sit across the chunk boundary. The row's own pipes are not held together: a table row+ # that long has nowhere safe to break, and the link is what a reader loses.+ line = "x" * (SLACK_MARKDOWN_TEXT_MAX_LEN - 20) + prefix + link + " | ready | and more prose."+ chunks = chunk_slack_text(line, SLACK_MARKDOWN_TEXT_MAX_LEN)++ assert all(len(chunk) <= SLACK_MARKDOWN_TEXT_MAX_LEN for chunk in chunks)assert any(link in chunk for chunk in chunks)diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.pyindex 36aa2c9fc944..5fd05e2a05c7 100644--- a/products/signals/backend/test/test_slack_inbox_notifications.py+++ b/products/signals/backend/test/test_slack_inbox_notifications.py@@ -100,8 +100,8 @@ def test_build_message_blocks_includes_recipient_and_open_in_posthog_button() ->)assert blocks[0]["text"]["text"] == "Checkout errors spiked"- section_text = blocks[1]["text"]["text"]- assert section_text.startswith("*❗ P1 · Error tracking*")+ section_text = blocks[1]["text"]+ assert section_text.startswith("**❗ P1 · Error tracking**")assert "Error rate rose after deploy." in section_textassert "Ignored second line." not in section_text# A mention in plain_text would render as the raw token, never pinging anyone.@@ -126,7 +126,7 @@ def test_build_message_blocks_mentions_every_routed_reviewer() -> None:reviewer_mentions=["<@U1>", "<@U2>"],)- assert blocks[1]["text"]["text"] == "*🟠 P2*"+ assert blocks[1]["text"] == "**🟠 P2**"assert blocks[2]["elements"][0]["text"] == "👤 Suggested reviewers: <@U1> <@U2>"@@ -140,7 +140,7 @@ def test_build_message_blocks_includes_repository_in_metadata_line() -> None:repository="PostHog/posthog",)- assert blocks[1]["text"]["text"] == "*🟠 P2 · Error tracking · PostHog/posthog*"+ assert blocks[1]["text"] == "**🟠 P2 · Error tracking · PostHog/posthog**"def test_build_message_blocks_escapes_mrkdwn_in_llm_derived_fields() -> None:@@ -159,12 +159,15 @@ def test_build_message_blocks_escapes_mrkdwn_in_llm_derived_fields() -> None:repository="<!channel>/repo",)- section_text = blocks[1]["text"]["text"]+ section_text = blocks[1]["text"]assert "<!here>" not in section_textassert "<@U999>" not in section_textassert "<!channel>" not in section_textassert "<!here>" in section_text- assert "&" in section_text+ # `&` is left alone. Slack decodes an entity without re-reading it as a token, so escaping it+ # buys no safety, and it does not decode inside a link destination, where it would corrupt the+ # query string of every link a report carries.+ assert "everyone & " in section_text@pytest.mark.parametrize(@@ -186,7 +189,7 @@ def test_build_message_blocks_prefixes_priority_with_emoji(priority: str, expectreviewer_mentions=["<@U123>"],)- assert blocks[1]["text"]["text"] == f"*{expected_priority_label}*"+ assert blocks[1]["text"] == f"**{expected_priority_label}**"assert blocks[2]["elements"][0]["text"] == "👤 Suggested reviewers: <@U123>"@@ -332,7 +335,7 @@ def test_dispatch_sends_to_configured_reviewer(org_and_team):assert "Report (P1)" in call_kwargs["text"]blocks = call_kwargs["blocks"]assert blocks[0]["text"]["text"] == "Test report"- assert blocks[1]["text"]["text"].startswith("*❗ P1 · Error tracking*")+ assert blocks[1]["text"].startswith("**❗ P1 · Error tracking**")assert "👤 Suggested reviewers: <@U_REVIEWER>" in blocks[2]["elements"][0]["text"]assert all("<@" not in t for t in _plain_text_block_texts(blocks))assert blocks[3]["elements"][0]["url"] == f"{settings.SITE_URL}/project/{team.id}/inbox/reports/{report.id}"@@ -602,7 +605,7 @@ def test_dispatch_includes_repository_from_repo_selection_artefact(org_and_team)assert sent == 1blocks = fake_client.chat_postMessage.call_args.kwargs["blocks"]- assert "PostHog/posthog" in blocks[1]["text"]["text"]+ assert "PostHog/posthog" in blocks[1]["text"]@pytest.mark.django_db@@ -817,7 +820,7 @@ def test_build_signal_thread_blocks_renders_header_content_and_github_details()blocks, fallback = _build_signal_thread_blocks(signal)assert blocks[0]["elements"][0]["text"] == "*GitHub · Issue*"- assert blocks[1]["text"]["text"] == "Users report the export button does nothing"+ assert blocks[1]["text"] == "Users report the export button does nothing"detail = blocks[2]["elements"][0]["text"]assert "#42" in detailassert "bug, export" in detail@@ -834,7 +837,7 @@ def test_build_signal_thread_blocks_escapes_content_to_block_mention_injection()"extra": {},}blocks, fallback = _build_signal_thread_blocks(signal)- content_text = blocks[1]["text"]["text"]+ content_text = blocks[1]["text"]assert "<!here>" not in content_textassert "<@U999>" not in content_textassert "<!here>" in content_text@@ -876,30 +879,33 @@ def test_build_signal_thread_blocks_rejects_unsafe_detail_url() -> None:assert "javascript:" not in detail-def test_build_signal_thread_blocks_renders_markdown_content_as_mrkdwn() -> None:- # Markdown in the description (headings, bullets, emphasis, links) renders as Slack mrkdwn- # rather than showing literal `##`, `**`, and `[text](url)` noise.+def test_build_signal_thread_blocks_delivers_markdown_for_slack_to_render() -> None:+ # Slack renders the Markdown, so headings, emphasis, links, and table cells reach it as the+ # author wrote them. Converting to mrkdwn here dropped the links inside a table: the converter+ # lifted the table out before it converted anything, then put the cells back untouched.signal = {"source_product": "github","source_type": "issue","weight": 1.0,- "content": "## Bug\n**Export** is broken, see [issue](https://example.com/i?a=1&b=2)\n- step one\n- step two",+ "content": (+ "## Bug\n**Export** is broken, see [issue](https://example.com/i?a=1&b=2)\n- step one\n\n"+ "| PR | Status |\n| --- | --- |\n| [#42 fix export](https://example.com/pull/42) | ready |"+ ),"extra": {},}blocks, _ = _build_signal_thread_blocks(signal)- content_text = blocks[1]["text"]["text"]- assert "*Bug*" in content_text- assert "*Export*" in content_text- assert "<https://example.com/i?a=1&b=2|issue>" in content_text- assert "• step one" in content_text- # No raw markdown syntax should survive the conversion.- assert "##" not in content_text- assert "**" not in content_text- assert "[issue]" not in content_text+ content_text = blocks[1]["text"]+ assert "## Bug" in content_text+ # The link destination reaches Slack byte for byte, `&` included. Escaping it to `&` here+ # put that entity in the rendered link's href and broke the query string.+ assert "**Export** is broken, see [issue](https://example.com/i?a=1&b=2)" in content_text+ assert "- step one" in content_text+ assert "| [#42 fix export](https://example.com/pull/42) | ready |" in content_textdef test_build_signal_thread_blocks_neutralizes_injection_in_markdown_content() -> None:- # Even when converting markdown, raw mention/link syntax in untrusted content stays inert.+ # Slack reads its own tokens inside a markdown block, so untrusted content must not keep a live+ # one — neither a broadcast nor a `<url|label>` link whose label hides where it points.signal = {"source_product": "github","source_type": "issue",@@ -908,18 +914,20 @@ def test_build_signal_thread_blocks_neutralizes_injection_in_markdown_content()"extra": {},}blocks, _ = _build_signal_thread_blocks(signal)- content_text = blocks[1]["text"]["text"]- assert "*Heads up*" in content_text # markdown still rendered+ content_text = blocks[1]["text"]+ assert "**Heads up**" in content_text # the Markdown itself is left for Slack to renderassert "<!here>" not in content_textassert "<@U999>" not in content_textassert "<https://evil.com|click here>" not in content_textassert "<!here>" in content_textassert "<@U999>" in content_text+ assert "<https://evil.com|click here>" in content_text-def test_build_signal_thread_blocks_defangs_mention_injection_via_markdown_links() -> None:- # `markdown_to_mrkdwn` turns `[text](dest)` into Slack's `<dest|label>` form; an untrusted- # description could smuggle a broadcast/ping by pointing the link at `!channel` / `@U123`.+def test_build_signal_thread_blocks_never_turns_a_markdown_link_into_a_mention() -> None:+ # A markdown link pointing at `!channel` / `@U123` used to reach Slack as a live broadcast: the+ # mrkdwn converter rewrote every `[text](dest)` into Slack's `<dest|label>` token form, whatever+ # the destination was. Delivering the Markdown as written can synthesize no token at all.signal = {"source_product": "github","source_type": "issue",@@ -928,14 +936,11 @@ def test_build_signal_thread_blocks_defangs_mention_injection_via_markdown_links"extra": {},}blocks, _ = _build_signal_thread_blocks(signal)- content_text = blocks[1]["text"]["text"]- # No live mention/broadcast token survives.- assert "<!channel|" not in content_text- assert "<@U12345678|" not in content_text- assert "<!channel|ping everyone>" in content_text- assert "<@U12345678|dm me>" in content_text- # A genuine http(s) link is still rendered as a clickable Slack link.- assert "<https://example.com|real>" in content_text+ content_text = blocks[1]["text"]+ assert "<!channel" not in content_text+ assert "<@U12345678" not in content_text+ assert "[ping everyone](!channel)" in content_text+ assert "[real](https://example.com)" in content_text@pytest.mark.django_db