: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
chore(devex): give shared slack code one home in posthog/slack (#105858)
Julian Beza24fbe49ac2d
diff --git a/ee/tasks/subscriptions/slack_subscriptions.py b/ee/tasks/subscriptions/slack_subscriptions.pyindex efe5812950bf..8a154bd8c83a 100644--- a/ee/tasks/subscriptions/slack_subscriptions.py+++ b/ee/tasks/subscriptions/slack_subscriptions.py@@ -10,6 +10,7 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.dataclasses import frozenfrom posthog.models.integration import Integration, SlackIntegration+from posthog.slack.formatting import channel_id_from_targetfrom posthog.storage import object_storagefrom posthog.sync import database_sync_to_asyncfrom posthog.utils import absolute_uri@@ -176,7 +177,7 @@ def _prepare_slack_gallery(lines.append(explore_hint)return SlackGallery(- channel=subscription.target_value.split("|")[0],+ channel=channel_id_from_target(subscription.target_value),initial_comment="\n\n".join(lines),file_uploads=file_uploads,)@@ -244,7 +245,7 @@ def _prepare_slack_message(if not resource_info:raise NotImplementedError("This type of subscription resource is not supported")- channel = subscription.target_value.split("|")[0]+ channel = channel_id_from_target(subscription.target_value)first_asset, *other_assets = assetstitle = _subscription_title(subscription, resource_info, is_new_subscription)diff --git a/posthog/api/test/test_comment_slack_sync.py b/posthog/api/test/test_comment_slack_sync.pyindex f1b3828684ac..cf32f2c52b6e 100644--- a/posthog/api/test/test_comment_slack_sync.py+++ b/posthog/api/test/test_comment_slack_sync.py@@ -11,7 +11,7 @@ from rest_framework import statusfrom slack_sdk.errors import SlackApiErrorfrom posthog.api.comments import _slack_thread_url-from posthog.helpers.slack_thread_mirror import _discussion_card_blocks, escape_slack_mrkdwn+from posthog.helpers.slack_thread_mirror import _discussion_card_blocksfrom posthog.models.comment import Comment, CommentSlackThreadfrom posthog.models.integration import Integrationfrom posthog.tasks.comment_slack_sync import (@@ -620,15 +620,3 @@ class TestSlackThreadSerialization(APIBaseTest):res = self.client.get(f"/api/projects/{self.team.id}/comments/{self.parent.id}/")assert res.status_code == status.HTTP_200_OKassert res.json()["slack_thread"] is None---class TestEscapeSlackMrkdwn(APIBaseTest):- @parameterized.expand(- [- ("link_injection", "<https://evil|click>", "<https://evil|click>"),- ("ampersand", "Tom & Jerry", "Tom & Jerry"),- ("plain", "Alice", "Alice"),- ]- )- def test_escapes_slack_control_chars(self, _name, raw, expected):- assert escape_slack_mrkdwn(raw) == expecteddiff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex c61267b198c3..19d37919f8fd 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -73,7 +73,7 @@ from posthog.models.user_integration import ()from posthog.models.utils import hash_key_valuefrom posthog.rate_limit import GitHubRepositoryRefreshThrottle-from posthog.team_notifications.slack import is_shared_channel+from posthog.slack.channels import is_shared_channelfrom products.access_control.backend.models.access_control import AccessControlfrom products.batch_exports.backend.models import BatchExport, BatchExportDestination@@ -194,7 +194,7 @@ class TestSlackIntegration:channels = SlackIntegration(self.integration).list_public_channels()- # team_notifications reads all three flags to keep an internal message out of a channel+ # posthog.slack.channels reads all three flags to keep an internal message out of a channel# shared beyond the workspace. A dropped flag reads as not shared.assert is_shared_channel(channels[0])diff --git a/posthog/comment/formatting.py b/posthog/comment/formatting.pyindex a8fdbbe319e5..3d4ac42642bf 100644--- a/posthog/comment/formatting.py+++ b/posthog/comment/formatting.py@@ -8,6 +8,8 @@ from typing import Anyfrom urllib.parse import urlparsefrom uuid import UUID+from posthog.slack.formatting import escape_slack_mrkdwn+JSON = dict[str, Any]# Pre-compiled regexes for performance (compiled once at module load)@@ -40,17 +42,6 @@ _RE_MD_TRAILING_LINE_SPACES = re.compile(r"[ \t]+\n")_RE_BLANK_LINE_RUN = re.compile(r"\n{2,}")-def escape_slack_mrkdwn(text: str) -> str:- """Escape Slack mrkdwn control characters in user-supplied text.-- Unescaped `<...>` sequences are live in mrkdwn: `<!channel>` broadcasts,- `<@U…>` pings a user, and `<url|label>` renders a disguised link.- """- if not text:- return ""- return text.replace("&", "&").replace("<", "<").replace(">", ">")--def _slack_unicode_to_char(unicode_hex: str) -> str | None:"""Convert Slack's unicode hex field (e.g. '1f44d' or '1f1fa-1f1f8') to a Unicode string."""if not unicode_hex:diff --git a/posthog/helpers/slack_thread_mirror.py b/posthog/helpers/slack_thread_mirror.pyindex 4934c4bbaeb4..a138e9ffe97c 100644--- a/posthog/helpers/slack_thread_mirror.py+++ b/posthog/helpers/slack_thread_mirror.py@@ -11,8 +11,9 @@ from uuid import UUIDimport structlogfrom slack_sdk import WebClient-from posthog.comment.formatting import escape_slack_mrkdwn, rich_content_to_slack_payload-from posthog.helpers.slack_identity import resolve_slack_avatar_by_email+from posthog.comment.formatting import rich_content_to_slack_payload+from posthog.slack.formatting import escape_slack_mrkdwn+from posthog.slack.identity import resolve_slack_avatar_by_emaillogger = structlog.get_logger(__name__)diff --git a/posthog/models/integration/slack.py b/posthog/models/integration/slack.pyindex 16bff822548d..17158370bfb1 100644--- a/posthog/models/integration/slack.py+++ b/posthog/models/integration/slack.py@@ -221,7 +221,7 @@ class SlackIntegration:# fields they use.## Every SHARED_CHANNEL_FLAGS entry has to survive. A dropped flag reads as absent, which- # reads as not shared, and team_notifications uses that to decide whether a channel matched+ # reads as not shared, and posthog.slack.channels uses that to decide whether a channel matched# by name may receive an internal message.return {"id": channel["id"],diff --git a/posthog/owners.yaml b/posthog/owners.yamlindex f23450127b04..0edc9a45f0ce 100644--- a/posthog/owners.yaml+++ b/posthog/owners.yaml@@ -23,6 +23,8 @@ rules:owners: team-analytics-platform- match: '/rbac/'owners: team-platform-features+ - match: '/slack/'+ owners: team-devex- match: '/taxonomy/'owners: team-product-analytics- match: '/templates/surveys/'diff --git a/posthog/slack/README.md b/posthog/slack/README.mdnew file mode 100644index 000000000000..dbcdddc0373f--- /dev/null+++ b/posthog/slack/README.md@@ -0,0 +1,24 @@+# Slack domain helpers++Code about Slack that more than one product needs, and that is neither transport nor an outbound call.+Inbound transport is `posthog/ingress/slack/`.+Outbound calls go through `posthog/egress/slack/`.+Neither of those imports the other, and both may import this package.++## What belongs here++Knowledge about Slack itself, which changes when Slack changes.+Examples are how to escape `mrkdwn`, the limits Slack puts on a message, the format of a stored channel picker value, how to find a channel by name, and how to resolve a Slack user to a PostHog user.++## What stays with the product++Some code looks the same in two products but changes for product reasons.+That code stays in each product:++- Where a message goes: destination storage and routing.+- What a message says.+- What a failed post does: which Slack error codes a product treats as permanent, as retryable, or as a reason to disable a destination.+- Thread state: where a product stores the root message of a thread, and when it posts a reply instead of a new message.++Two copies of this kind of code are not duplication to remove.+Move code here only when every caller changes it for the same Slack reason.diff --git a/posthog/team_notifications/__init__.py b/posthog/slack/__init__.pysimilarity index 100%rename from posthog/team_notifications/__init__.pyrename to posthog/slack/__init__.pydiff --git a/posthog/team_notifications/slack.py b/posthog/slack/channels.pysimilarity index 100%rename from posthog/team_notifications/slack.pyrename to posthog/slack/channels.pydiff --git a/posthog/slack/formatting.py b/posthog/slack/formatting.pynew file mode 100644index 000000000000..87803b189501--- /dev/null+++ b/posthog/slack/formatting.py@@ -0,0 +1,18 @@+def escape_slack_mrkdwn(text: str) -> str:+ """Escape Slack mrkdwn control characters in user-supplied text.++ Unescaped `<...>` sequences are live in mrkdwn: `<!channel>` broadcasts,+ `<@U…>` pings a user, and `<url|label>` renders a disguised link.+ """+ if not text:+ return ""+ return text.replace("&", "&").replace("<", "<").replace(">", ">")+++def channel_id_from_target(value: str) -> str:+ """Extract the Slack id from the frontend picker's `id|#name` or `id|@name` value.++ Slack API calls accept only the id. `chat.postMessage` accepts a member id as its `channel` and+ opens a direct message, so a member target resolves the same way as a channel target.+ """+ return value.split("|", 1)[0].strip()diff --git a/posthog/helpers/slack_identity.py b/posthog/slack/identity.pysimilarity index 100%rename from posthog/helpers/slack_identity.pyrename to posthog/slack/identity.pydiff --git a/posthog/helpers/slack_markdown.py b/posthog/slack/markdown.pysimilarity index 100%rename from posthog/helpers/slack_markdown.pyrename to posthog/slack/markdown.pydiff --git a/posthog/team_notifications/test/__init__.py b/posthog/slack/test/__init__.pysimilarity index 100%rename from posthog/team_notifications/test/__init__.pyrename to posthog/slack/test/__init__.pydiff --git a/posthog/team_notifications/test/test_slack.py b/posthog/slack/test/test_channels.pysimilarity index 95%rename from posthog/team_notifications/test/test_slack.pyrename to posthog/slack/test/test_channels.pyindex 496037134e3a..0d0dda918acf 100644--- a/posthog/team_notifications/test/test_slack.py+++ b/posthog/slack/test/test_channels.py@@ -2,7 +2,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.team_notifications.slack import SlackChannel, clip_text, find_channel+from posthog.slack.channels import SlackChannel, clip_text, find_channel_TEAM_CHANNEL = SlackChannel(channel_id="C1", shared=False)_SHARED_CHANNEL = SlackChannel(channel_id="C2", shared=True)diff --git a/posthog/slack/test/test_formatting.py b/posthog/slack/test/test_formatting.pynew file mode 100644index 000000000000..9960838775b6--- /dev/null+++ b/posthog/slack/test/test_formatting.py@@ -0,0 +1,17 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.slack.formatting import escape_slack_mrkdwn+++class TestEscapeSlackMrkdwn(SimpleTestCase):+ @parameterized.expand(+ [+ ("link_injection", "<https://evil|click>", "<https://evil|click>"),+ ("ampersand", "Tom & Jerry", "Tom & Jerry"),+ ("plain", "Alice", "Alice"),+ ]+ )+ def test_escapes_slack_control_chars(self, _name, raw, expected):+ assert escape_slack_mrkdwn(raw) == expecteddiff --git a/posthog/helpers/tests/test_slack_identity.py b/posthog/slack/test/test_identity.pysimilarity index 95%rename from posthog/helpers/tests/test_slack_identity.pyrename to posthog/slack/test/test_identity.pyindex e4a633f9fd77..30ab29c829f1 100644--- a/posthog/helpers/tests/test_slack_identity.py+++ b/posthog/slack/test/test_identity.py@@ -3,7 +3,7 @@ from unittest.mock import MagicMockfrom django.core.cache import cachefrom django.test import SimpleTestCase-from posthog.helpers.slack_identity import resolve_slack_user+from posthog.slack.identity import resolve_slack_userdef _client_returning(name: str, email: str) -> MagicMock:diff --git a/posthog/helpers/tests/test_slack_markdown.py b/posthog/slack/test/test_markdown.pysimilarity index 95%rename from posthog/helpers/tests/test_slack_markdown.pyrename to posthog/slack/test/test_markdown.pyindex ab8f855d7614..2b3a53f01940 100644--- a/posthog/helpers/tests/test_slack_markdown.py+++ b/posthog/slack/test/test_markdown.py@@ -2,7 +2,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.helpers.slack_markdown import opens_with_line_anchored_markdown+from posthog.slack.markdown import opens_with_line_anchored_markdownclass TestOpensWithLineAnchoredMarkdown(SimpleTestCase):diff --git a/posthog/tasks/comment_slack_sync.py b/posthog/tasks/comment_slack_sync.pyindex e69c8c57b8f5..4a11939c516d 100644--- a/posthog/tasks/comment_slack_sync.py+++ b/posthog/tasks/comment_slack_sync.py@@ -8,7 +8,6 @@ from slack_sdk import WebClientfrom slack_sdk.errors import SlackApiErrorfrom posthog.comment.formatting import slack_files_to_placeholder_lines, slack_to_content_and_rich_content-from posthog.helpers.slack_identity import resolve_posthog_user_for_slack, resolve_slack_userfrom posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_userfrom posthog.models.comment import Comment, CommentSlackThreadfrom posthog.models.comment.comment import COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API@@ -16,6 +15,7 @@ from posthog.models.comment.slack_thread import DISCUSSIONS_SLACK_SYNC_FLAGfrom posthog.models.integration import SlackIntegrationfrom posthog.models.team import Teamfrom posthog.scoping_audit import skip_team_scope_audit+from posthog.slack.identity import resolve_posthog_user_for_slack, resolve_slack_userlogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/ai_observability/eval_reports/delivery.py b/posthog/temporal/ai_observability/eval_reports/delivery.pyindex 2e5d50ec6772..b9253363210b 100644--- a/posthog/temporal/ai_observability/eval_reports/delivery.py+++ b/posthog/temporal/ai_observability/eval_reports/delivery.py@@ -14,6 +14,7 @@ import structlogfrom markdown_it import MarkdownItfrom markdown_to_mrkdwn import SlackMarkdownConverter+from posthog.slack.formatting import channel_id_from_targetfrom posthog.temporal.ai_observability.eval_reports.report_agent.schema import (METRICS_UNAVAILABLE_MESSAGE,Citation,@@ -376,11 +377,7 @@ def deliver_slack_report(if not integration_id or not channel:continue- # The Slack channel picker stores the target as "<channel_id>|#<channel_name>"- # (e.g. "C0B5CHB0JQH|#tech-devops-cron"). chat.postMessage only accepts the channel- # ID, so strip the "|#name" suffix before sending. Mirrors the subscriptions path in- # ee/tasks/subscriptions/slack_subscriptions.py, which splits the same composite value.- channel_id = channel.split("|")[0]+ channel_id = channel_id_from_target(channel)if not channel_id:error_msg = f"Failed to send Slack message to {channel}: no channel ID in target value"logger.warning(error_msg)diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex 931b01350e52..dbeccad93735 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -67,7 +67,6 @@ posthog/admin/test_admin.py::TestPluginAttachmentInlineposthog/api/oauth/test_cimd.py::TestAuthorizationServerMetadataposthog/api/oauth/test_cimd.py::TestFetchCimdMetadataposthog/api/test/test_comment_slack_sync.py::TestDiscussionCardBlocks-posthog/api/test/test_comment_slack_sync.py::TestEscapeSlackMrkdwnposthog/api/test/test_comments.py::TestCommentHelperFunctionsposthog/api/test/test_csp.py::TestCSPModuleposthog/api/test/test_event_definition_base.py::TestEventDefinitionGeneratorBasediff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.pyindex 622303c1d4bc..b981c05ab8bf 100644--- a/products/conversations/backend/slack.py+++ b/products/conversations/backend/slack.py@@ -31,11 +31,11 @@ from posthog.comment.formatting import (from posthog.egress.slack.client import SlackWebClient as WebClientfrom posthog.event_usage import groups, report_team_actionfrom posthog.exceptions_capture import capture_exception-from posthog.helpers.slack_identity import resolve_posthog_user_for_slack, resolve_slack_userfrom posthog.models.comment import Commentfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.ph_client import ph_scoped_capture+from posthog.slack.identity import resolve_posthog_user_for_slack, resolve_slack_userfrom products.access_control.backend.facade.user_access_control import UserAccessControldiff --git a/products/conversations/backend/tasks/slack.py b/products/conversations/backend/tasks/slack.pyindex e71f267c18ca..fdd44507fca5 100644--- a/products/conversations/backend/tasks/slack.py+++ b/products/conversations/backend/tasks/slack.py@@ -16,14 +16,10 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.comment.formatting import extract_images_from_rich_content, rich_content_to_slack_payloadfrom posthog.dataclasses import frozen-from posthog.helpers.slack_identity import (- resolve_posthog_user_for_slack,- resolve_slack_avatar_by_email,- resolve_slack_user,-)from posthog.models.team import Teamfrom posthog.models.uploaded_media import UploadedMediafrom posthog.scoping_audit import skip_team_scope_audit+from posthog.slack.identity import resolve_posthog_user_for_slack, resolve_slack_avatar_by_email, resolve_slack_userfrom posthog.storage import object_storagefrom products.conversations.backend.cache import NUDGE_DISMISS_TTL, suppress_nudgediff --git a/products/error_tracking/backend/temporal/alerts/messages.py b/products/error_tracking/backend/temporal/alerts/messages.pyindex 2edb7e312a0d..0e9ce74d05ea 100644--- a/products/error_tracking/backend/temporal/alerts/messages.py+++ b/products/error_tracking/backend/temporal/alerts/messages.py@@ -7,6 +7,8 @@ interpolated into mrkdwn text.from django.conf import settings+from posthog.slack.formatting import escape_slack_mrkdwn+from products.error_tracking.backend.logic import build_issue_permalink_pathfrom products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs@@ -24,10 +26,6 @@ MAX_HEADER_LENGTH = 150MAX_DESCRIPTION_LENGTH = 500-def escape_slack_text(text: str) -> str:- return text.replace("&", "&").replace("<", "<").replace(">", ">")--def _truncate(text: str, limit: int) -> str:return text if len(text) <= limit else text[: limit - 1] + "…"@@ -105,7 +103,7 @@ def _build_blocks(inputs: AlertDeliveryWorkflowInputs, *, headline: str) -> listblocks.append({"type": "context",- "elements": [{"type": "mrkdwn", "text": f"Status: {escape_slack_text(inputs.status)}"}],+ "elements": [{"type": "mrkdwn", "text": f"Status: {escape_slack_mrkdwn(inputs.status)}"}],})if inputs.event == "$error_tracking_issue_spiking":@@ -120,7 +118,7 @@ def build_root_message(inputs: AlertDeliveryWorkflowInputs) -> dict:headline = root_headline(inputs.event)return {"blocks": _build_blocks(inputs, headline=headline),- "text": escape_slack_text(_header_text(inputs, headline)),+ "text": escape_slack_mrkdwn(_header_text(inputs, headline)),"headline": headline,}@@ -129,12 +127,12 @@ def build_root_edit(inputs: AlertDeliveryWorkflowInputs, *, headline: str) -> di# The headline never changes on edit: it is the thread's identity.return {"blocks": _build_blocks(inputs, headline=headline),- "text": escape_slack_text(_header_text(inputs, headline)),+ "text": escape_slack_mrkdwn(_header_text(inputs, headline)),}def build_reply_text(inputs: AlertDeliveryWorkflowInputs) -> str | None:- by = f" by {escape_slack_text(inputs.actor_email)}" if inputs.actor_email else ""+ by = f" by {escape_slack_mrkdwn(inputs.actor_email)}" if inputs.actor_email else ""extra = inputs.extra or {}match inputs.event:case "$error_tracking_issue_resolved":diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.pyindex c8967d48fa0d..80f804ee9a1d 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py@@ -17,6 +17,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.markdown_safety import strip_external_links_markdownfrom posthog.models import Team, Userfrom posthog.models.integration import Integration+from posthog.slack.formatting import channel_id_from_targetfrom posthog.sync import database_sync_to_asyncfrom posthog.utils import absolute_uri@@ -379,7 +380,7 @@ def _build_ai_slack_message(charts: list[dict] | None = None,) -> SlackMessage:utm_tags = f"{UTM_TAGS_BASE}&utm_medium=slack"- channel = subscription.target_value.split("|")[0]+ channel = channel_id_from_target(subscription.target_value)sections = _split_text_into_chunks(_SLACK_CONVERTER.convert(strip_external_links_markdown(markdown)))title = subscription.title or "Your PostHog AI report"first_section = sections[0] if sections else "_No report content was generated._"diff --git a/products/replay_vision/backend/alert_destinations.py b/products/replay_vision/backend/alert_destinations.pyindex bdd196329db7..8a818265856b 100644--- a/products/replay_vision/backend/alert_destinations.py+++ b/products/replay_vision/backend/alert_destinations.py@@ -160,9 +160,3 @@ VISION_ALERT_SLACK_CONTEXT_ELEMENTS = ("Scanner: {event.properties.scanner_name_mrkdwn}","Project: <{project.url}|{project.name}>",)---def escape_slack_mrkdwn(text: str) -> str:- """User-editable values interpolated into Slack mrkdwn must not carry control- syntax like <!channel> or <url|label>; webhooks keep the raw value."""- return text.replace("&", "&").replace("<", "<").replace(">", ">")diff --git a/products/replay_vision/backend/temporal/vision_alerts/activities.py b/products/replay_vision/backend/temporal/vision_alerts/activities.pyindex ffb3ba037a3f..adfec5435a69 100644--- a/products/replay_vision/backend/temporal/vision_alerts/activities.py+++ b/products/replay_vision/backend/temporal/vision_alerts/activities.py@@ -23,6 +23,7 @@ from pydantic import BaseModelfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.kafka_client.client import ProduceResult+from posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.sync import database_sync_to_asyncfrom products.alerts.backend.facade.destinations import (@@ -31,7 +32,6 @@ from products.alerts.backend.facade.destinations import (produce_alert_internal_event,)from products.alerts.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples-from products.replay_vision.backend.alert_destinations import escape_slack_mrkdwnfrom products.replay_vision.backend.alert_state_machine import (AlertCheckOutcome,AlertState,@@ -531,6 +531,7 @@ def _base_properties(alert: VisionAlertConfiguration, now: datetime) -> dict:"team_id": alert.team_id,"scanner_id": str(alert.scanner_id),"scanner_name": alert.scanner.name,+ # Slack templates read the escaped copy, and webhooks keep the raw scanner name."scanner_name_mrkdwn": escape_slack_mrkdwn(alert.scanner.name),"triggered_at": now.isoformat(),}diff --git a/products/signals/backend/admin.py b/products/signals/backend/admin.pyindex ff289d8c1ed6..629f8f71d2d0 100644--- a/products/signals/backend/admin.py+++ b/products/signals/backend/admin.py@@ -5,6 +5,8 @@ from django.contrib import adminfrom django.urls import reversefrom django.utils.html import format_html+from posthog.slack.formatting import channel_id_from_target+from .models import (SignalReport,SignalReportArtefact,@@ -242,7 +244,7 @@ class SignalTeamConfigAdminForm(forms.ModelForm):if not value:return None# Only the channel id is required; an optional "|#name" suffix is allowed for readability.- channel_id = value.split("|", 1)[0].strip()+ channel_id = channel_id_from_target(value)if not _SLACK_CHANNEL_ID_RE.match(channel_id):raise forms.ValidationError("Use 'CHANNELID|#name' form, or just the channel id. The id looks like 'C0123ABCD' "diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 614da9e0731c..6bb64bdc4b12 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -30,6 +30,7 @@ from posthog.event_usage import groupsfrom posthog.models.integration import Integrationfrom posthog.models.team.team import Teamfrom posthog.permissions import get_authenticator_scopes+from posthog.slack.formatting import channel_id_from_targetfrom posthog.temporal.oauth import SCOUT_GRANTABLE_WRITE_SCOPESfrom products.signals.backend.artefact_schemas import (@@ -2730,7 +2731,7 @@ class SignalScoutSlackDestinationSerializer(serializers.Serializer):deduped: list[str] = []seen_ids: set[str] = set()for target in value:- member_id = target.split("|", 1)[0].strip()+ member_id = channel_id_from_target(target)if not re.fullmatch(r"[UW][A-Z0-9]{4,}", member_id):raise serializers.ValidationError(f"{target!r} is not a Slack member target. Expected a member ID starting with U or W, "diff --git a/products/signals/backend/scout_harness/slack_charts.py b/products/signals/backend/scout_harness/slack_charts.pyindex 423dbb4f8273..04066917e389 100644--- a/products/signals/backend/scout_harness/slack_charts.py+++ b/products/signals/backend/scout_harness/slack_charts.py@@ -18,9 +18,9 @@ from posthog.dataclasses import frozenfrom posthog.models import Team, Userfrom posthog.query_creator_access import creator_access_revokedfrom posthog.redis import get_client+from posthog.slack.formatting import escape_slack_mrkdwnfrom products.signals.backend.models import SignalReport, SignalScoutRun-from products.signals.backend.slack_formatting import escape_slack_mrkdwnlogger = structlog.get_logger(__name__)diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.pyindex eeb72130e26a..3817df9ecdc7 100644--- a/products/signals/backend/scout_harness/slack_delivery.py+++ b/products/signals/backend/scout_harness/slack_delivery.py@@ -14,9 +14,10 @@ from slack_sdk.errors import SlackApiErrorfrom slack_sdk.web import SlackResponse, WebClientfrom posthog.dataclasses import frozen-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_blockfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.redis import get_client+from posthog.slack.formatting import channel_id_from_target, escape_slack_mrkdwn+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_blockfrom products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRunfrom products.signals.backend.scout_harness.slack_charts import (@@ -29,10 +30,8 @@ from products.signals.backend.scout_harness.slack_charts import (from products.signals.backend.slack_formatting import (chunk_slack_text,defuse_slack_tokens,- escape_slack_mrkdwn,group_segments_to_limit,prepare_slack_markdown,- slack_channel_id_from_target,split_markdown_by_headings,strip_chart_references,)@@ -210,7 +209,7 @@ def _ensure_dm_recipient_eligible(slack: SlackIntegration, target_id: str) -> Nodef _slack_channel_id(channel: str) -> str:- channel_id = slack_channel_id_from_target(channel)+ channel_id = channel_id_from_target(channel)if not channel_id:raise ScoutSlackPermanentDeliveryError("The configured Slack channel is empty",@@ -386,7 +385,7 @@ _LATEST_REPORT_DELIVERY_TTL_SECONDS = 24 * 60 * 60def _latest_report_delivery_key(report_id: str, integration_id: int, channel: str) -> str:# The resolved channel id, so two configs naming one channel differently share a marker.- channel_id = slack_channel_id_from_target(channel)+ channel_id = channel_id_from_target(channel)return f"signals_scout:slack_report_latest_delivery:{report_id}:{integration_id}:{channel_id}"diff --git a/products/signals/backend/slack_formatting.py b/products/signals/backend/slack_formatting.pyindex 447c6590fde0..313ca54a88a1 100644--- a/products/signals/backend/slack_formatting.py+++ b/products/signals/backend/slack_formatting.py@@ -4,7 +4,7 @@ import refrom collections import Counterfrom posthog.dataclasses import frozen-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN# A summary places a chart inline with a markdown link targeting `chart:<chart_id>`. Slack cannot# place an image mid-sentence, and the link degrades badly if left alone: `chart:` is no scheme a@@ -66,11 +66,6 @@ def strip_chart_references(text: str) -> str:return _REFERENCE_LINK_RE.sub(_reduce, _CHART_REF_DEFINITION_RE.sub("", text))-def escape_slack_mrkdwn(text: str) -> str:- """Neutralize Slack control syntax so untrusted text cannot inject mentions or links."""- 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@@ -334,8 +329,3 @@ def chunk_slack_text(text: str, limit: int) -> list[str]:if current.strip():chunks.append(current.rstrip())return chunks---def slack_channel_id_from_target(value: str) -> str:- """Extract the Slack channel ID from the frontend picker's `id|#name` value."""- return value.split("|", 1)[0].strip()diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.pyindex ee90f73d80b7..c7fdb7dc97ca 100644--- a/products/signals/backend/slack_inbox_notifications.py+++ b/products/signals/backend/slack_inbox_notifications.py@@ -23,10 +23,14 @@ from django.conf import settingsfrom posthog.dataclasses import frozenfrom posthog.event_usage import groups-from posthog.helpers.slack_markdown import slack_markdown_block as _markdown_blockfrom posthog.models import Userfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.ph_client import ph_scoped_capture+from posthog.slack.formatting import (+ channel_id_from_target as _channel_id_from_target,+ escape_slack_mrkdwn as _escape_mrkdwn,+)+from posthog.slack.markdown import slack_markdown_block as _markdown_blockfrom products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELSfrom products.signals.backend.models import (@@ -45,10 +49,8 @@ from products.signals.backend.report_generation.resolve_reviewers import (resolve_org_users_by_uuid,)from products.signals.backend.slack_formatting import (- escape_slack_mrkdwn as _escape_mrkdwn,is_safe_slack_http_url as _is_safe_http_url,prepare_slack_markdown as _prepare_markdown,- slack_channel_id_from_target as _channel_id_from_target,strip_chart_references as _strip_chart_references,)from products.signals.backend.slack_notification_targets import is_slack_member_target, lookup_slack_user_id_by_emaildiff --git a/products/signals/backend/slack_notification_targets.py b/products/signals/backend/slack_notification_targets.pyindex 4fb6eb2d921e..2b477733e9b4 100644--- a/products/signals/backend/slack_notification_targets.py+++ b/products/signals/backend/slack_notification_targets.py@@ -23,9 +23,9 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.user import Userfrom posthog.models.user_integration import UserIntegration+from posthog.slack.formatting import channel_id_from_targetfrom products.signals.backend.models import SignalUserAutonomyConfig-from products.signals.backend.slack_formatting import slack_channel_id_from_targetlogger = logging.getLogger(__name__)@@ -46,7 +46,7 @@ _MEMBER_LOOKUPS_PER_MINUTE = 30def is_slack_member_target(target: str) -> bool:"""Whether a target addresses one workspace member, which Slack delivers as a direct message."""- return bool(_MEMBER_ID_RE.fullmatch(slack_channel_id_from_target(target)))+ return bool(_MEMBER_ID_RE.fullmatch(channel_id_from_target(target)))def saved_notification_integration(user: User) -> Integration | None:@@ -155,7 +155,7 @@ def validate_slack_notification_target(user: User, target: str, integration: Intif integration is None:raise serializers.ValidationError({"slack_notification_channel": _NO_WORKSPACE_ERROR})resolved_target = resolve_own_direct_message_target(user, integration)- if slack_channel_id_from_target(resolved_target) != slack_channel_id_from_target(target):+ if channel_id_from_target(resolved_target) != channel_id_from_target(target):raise serializers.ValidationError({"slack_notification_channel": _UNRESOLVED_MEMBER_ERROR})diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.pyindex 37999f6cd135..8f27df4c844a 100644--- a/products/signals/backend/test/test_scout_slack_delivery.py+++ b/products/signals/backend/test/test_scout_slack_delivery.py@@ -12,10 +12,10 @@ from celery.exceptions import Retryfrom parameterized import parameterizedfrom slack_sdk.errors import SlackApiError-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom posthog.models import Teamfrom posthog.models.integration import Integrationfrom posthog.redis import get_client+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRunfrom products.signals.backend.scout_harness.slack_charts import CHART_BLOCK_ID_PREFIX as PREFIXdiff --git a/products/signals/backend/test/test_slack_formatting.py b/products/signals/backend/test/test_slack_formatting.pyindex 430a62bea330..e0300a63e815 100644--- a/products/signals/backend/test/test_slack_formatting.py+++ b/products/signals/backend/test/test_slack_formatting.py@@ -4,12 +4,12 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN+from posthog.slack.formatting import escape_slack_mrkdwn+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom products.signals.backend.slack_formatting import (chunk_slack_text,defuse_slack_tokens,- escape_slack_mrkdwn,group_segments_to_limit,split_markdown_by_headings,strip_chart_references,diff --git a/products/slack_app/backend/inbox_channel.py b/products/slack_app/backend/inbox_channel.pyindex 32a569bc2533..b415fbab035c 100644--- a/products/slack_app/backend/inbox_channel.py+++ b/products/slack_app/backend/inbox_channel.py@@ -8,6 +8,7 @@ import structlogfrom slack_sdk.errors import SlackApiErrorfrom posthog.models.integration import Integration, SlackIntegration+from posthog.slack.formatting import channel_id_from_targetlogger = structlog.get_logger(__name__)@@ -52,10 +53,6 @@ def _channel_target(channel_id: str, channel_name: str) -> str:return f"{channel_id}|{name}"-def channel_id_from_target(value: str) -> str:- return value.split("|", 1)[0].strip()--def channel_name_from_target(value: str) -> str:pipe = value.find("|")return value[pipe + 1 :].strip() if pipe != -1 else f"#{INBOX_CHANNEL_NAME}"diff --git a/products/slack_app/backend/onboarding.py b/products/slack_app/backend/onboarding.pyindex 5ffc3f35d392..1c483dbe2871 100644--- a/products/slack_app/backend/onboarding.py+++ b/products/slack_app/backend/onboarding.py@@ -15,12 +15,12 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.models import OrganizationMembership, Teamfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.user_integration import UserIntegration+from posthog.slack.formatting import channel_id_from_targetfrom products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.inbox_channel import (_get_team_channel,_is_channel_member,- channel_id_from_target,ensure_inbox_channel,has_inbox_scopes,invite_user_to_inbox,diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.pyindex 666b7397f041..8daf69d919d9 100644--- a/products/slack_app/backend/services/integration_resolver.py+++ b/products/slack_app/backend/services/integration_resolver.py@@ -6,10 +6,10 @@ from django.db.models import Qimport structlog-from posthog.comment.formatting import escape_slack_mrkdwnfrom posthog.dataclasses import frozenfrom posthog.models.integration import Integrationfrom posthog.models.user import User+from posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.user_permissions import UserPermissionsfrom products.signals.backend.facade import api as signals_facadediff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pyindex 19c34fa43746..a8f225d147df 100644--- a/products/slack_app/backend/services/slack_messages.py+++ b/products/slack_app/backend/services/slack_messages.py@@ -34,9 +34,9 @@ from slack_sdk import WebClientfrom slack_sdk.errors import SlackApiErrorfrom slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler-from posthog.comment.formatting import escape_slack_mrkdwnfrom posthog.dataclasses import frozenfrom posthog.models.integration import Integration, SlackIntegration+from posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.utils import absolute_urifrom products.slack_app.backend.services.model_catalogue import describe_run_modeldiff --git a/products/slack_app/backend/services/slack_welcome_messages.py b/products/slack_app/backend/services/slack_welcome_messages.pyindex 9035f847fa91..30c8fb65d4b0 100644--- a/products/slack_app/backend/services/slack_welcome_messages.py+++ b/products/slack_app/backend/services/slack_welcome_messages.py@@ -19,6 +19,7 @@ from typing import Anyfrom django.conf import settingsfrom posthog.models.integration import Integration, SlackIntegration+from posthog.slack.formatting import channel_id_from_targetfrom posthog.utils import absolute_urifrom products.slack_app.backend.feature_flags import is_slack_app_assistant_enabled@@ -26,7 +27,6 @@ from products.slack_app.backend.inbox_channel import (INBOX_CHANNEL_REQUIRED_SCOPES,_channel_exists,_get_team_channel,- channel_id_from_target,channel_name_from_target,)from products.slack_app.backend.services.followup_invite import BOT_SETUP_DOCS_URLdiff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.pyindex d7ffdde7deb4..06faf2910d5e 100644--- a/products/slack_app/backend/slack_link_unfurl.py+++ b/products/slack_app/backend/slack_link_unfurl.py@@ -1,4 +1,7 @@-"""Slack link unfurling for PostHog resource URLs (metadata only)."""+"""Slack link unfurling for PostHog resource URLs (metadata only).++Ticket subjects and messages are customer-authored, so every one goes through `escape_slack_mrkdwn`.+"""from __future__ import annotations@@ -14,6 +17,7 @@ from posthog.models import Teamfrom posthog.models.comment import Commentfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.user_integration import UserIntegration+from posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.utils import get_instance_regionfrom products.access_control.backend.facade.user_access_control import (@@ -225,11 +229,6 @@ def _find_ticket(team_id: int, ref: str) -> Ticket | None:return None-def _escape_mrkdwn(text: str) -> str:- """Escape mrkdwn control chars — ticket subjects/messages are customer-authored."""- return text.replace("&", "&").replace("<", "<").replace(">", ">")--def _ticket_requester(team: Team, ticket: Ticket) -> str:"""Display the ticket's requester using the project's person display-name settings.@@ -260,7 +259,7 @@ def _ticket_opening_message(team_id: int, ticket_id: UUID) -> str | None:.values_list("content", flat=True).first())- return _truncate(_escape_mrkdwn((content or "").strip()), _MAX_OPENING_MESSAGE_CHARS) or None+ return _truncate(escape_slack_mrkdwn((content or "").strip()), _MAX_OPENING_MESSAGE_CHARS) or Nonedef _unfurl_payload(*, resource_label: str, title: str, description: str | None) -> dict:@@ -504,7 +503,7 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:unfurls[raw_url] = _ticket_unfurl_payload(url=raw_url,ticket=ticket,- requester=_escape_mrkdwn(_ticket_requester(team, ticket)),+ requester=escape_slack_mrkdwn(_ticket_requester(team, ticket)),opening_message=_ticket_opening_message(team.pk, ticket.id),)elif kind == "task":@@ -519,7 +518,9 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:skipped.append({"kind": kind, "ref": ref, "reason": "not_found_or_no_access"})continuelabel = "Task" if task.latest_run_status is None else f"Task · {task.latest_run_status}"- unfurls[raw_url] = _unfurl_payload(resource_label=label, title=_escape_mrkdwn(task.title), description=None)+ unfurls[raw_url] = _unfurl_payload(+ resource_label=label, title=escape_slack_mrkdwn(task.title), description=None+ )try:_attach_public_slack_thread_reference(slack=slack,diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.pyindex 073393f98ada..37816b1774d5 100644--- a/products/slack_app/backend/slack_thread.py+++ b/products/slack_app/backend/slack_thread.py@@ -6,8 +6,8 @@ import structlogfrom slack_sdk import WebClientfrom slack_sdk.errors import SlackApiError-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_blockfrom posthog.models.integration import Integration, SlackIntegration+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_blockfrom products.slack_app.backend.feature_flags import is_slack_app_forking_enabledfrom products.slack_app.backend.services.slack_messages import (diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.pyindex d8770c87bcd5..b77218ae0ecc 100644--- a/products/slack_app/backend/tests/test_slack_thread.py+++ b/products/slack_app/backend/tests/test_slack_thread.py@@ -6,8 +6,8 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom slack_sdk.errors import SlackApiError-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom posthog.models.integration import Integration+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom products.slack_app.backend.services.slack_messages import RunFooterfrom products.slack_app.backend.slack_thread import (diff --git a/products/stamphog/backend/logic/channel_resolution.py b/products/stamphog/backend/logic/channel_resolution.pyindex 5c46efed4662..3ea21b981dd2 100644--- a/products/stamphog/backend/logic/channel_resolution.py+++ b/products/stamphog/backend/logic/channel_resolution.py@@ -39,7 +39,7 @@ from posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priorityfrom posthog.models.integration import Integrationfrom posthog.ownership.github_files import AuthenticatedRepoFiles, GitHubFilesFetcher-from posthog.team_notifications.slack import SlackChannel, fetch_channel_map, find_channel+from posthog.slack.channels import SlackChannel, fetch_channel_map, find_channelfrom ..facade.enums import ChannelResolutionSourcefrom ..models import StamphogRepoConfigdiff --git a/products/stamphog/backend/logic/slack_digest.py b/products/stamphog/backend/logic/slack_digest.pyindex ad7a765c6bcc..265f5a229a0d 100644--- a/products/stamphog/backend/logic/slack_digest.py+++ b/products/stamphog/backend/logic/slack_digest.py@@ -7,6 +7,10 @@ record the run as failed and retry the PRs tomorrow.Shape: the channel gets one lead (the model's headline, or the scope line when it wrote none) and afooter. The per-change lines go in a thread under it. A daily bot post competes with the channel itlands in, so it spends one line there and keeps the rest where a reader can open it by choice.++Summaries are model-generated over contributor-authored PR text, so every summary or PR string goes+through `escape_slack_mrkdwn`. That stops a merged PR from smuggling `<!channel>` mentions or breaking+out of a link into the digest channel."""from __future__ import annotations@@ -16,7 +20,8 @@ from typing import TYPE_CHECKINGimport structlogfrom posthog.models.integration import Integration, SlackIntegration-from posthog.team_notifications.slack import SlackPostRefused, post_message, post_with_join+from posthog.slack.channels import SlackPostRefused, post_message, post_with_join+from posthog.slack.formatting import escape_slack_mrkdwnfrom .digest import as_channel_paragraph@@ -50,22 +55,12 @@ class DigestSlackError(Exception):"""The digest could not be posted to Slack (integration missing, mismatched, or API failure)."""-def _escape_mrkdwn(text: str) -> str:- """Neutralize Slack mrkdwn control characters in attacker-controlled text.-- Model-generated summaries are written over contributor-authored PR text. Escaping- ``&``/``<``/``>`` stops a merged PR from smuggling ``<!channel>`` mentions or breaking out of a link- into the digest channel; Slack renders the escaped entities back as the literal characters.- """- return text.replace("&", "&").replace("<", "<").replace(">", ">")--def _link(url: str, label: str) -> str:# url is trusted (built from the GitHub PR URL); the label is untrusted, so escape it and drop the# `|` that would otherwise split the link syntax. Clipping happens inside the label rather than# over the finished string: the label is now the whole line, so trimming the tail off the assembled# link would take the closing `>` with it and leave Slack rendering raw markup instead of a link.- body = _clip(_escape_mrkdwn(label).replace("|", "/"), _MAX_SECTION_CHARS - len(url) - len("<|>"))+ body = _clip(escape_slack_mrkdwn(label).replace("|", "/"), _MAX_SECTION_CHARS - len(url) - len("<|>"))return f"<{url}|{body}>"@@ -126,10 +121,10 @@ def _lead_text(summary: DigestSummary) -> str:line is built from counts and is safe as it stands."""if summary.headline:- return _clip(_escape_mrkdwn(summary.headline), _MAX_SECTION_CHARS)+ return _clip(escape_slack_mrkdwn(summary.headline), _MAX_SECTION_CHARS)change_line = _lead_change_line(summary)if change_line:- return _clip(_escape_mrkdwn(change_line), _MAX_SECTION_CHARS)+ return _clip(escape_slack_mrkdwn(change_line), _MAX_SECTION_CHARS)return _scope_line(len(summary.prs), summary.considered)@@ -172,7 +167,7 @@ def _build_fallback_text(summary: DigestSummary) -> str:the same sentence every morning pushes the change itself out of view."""# The top-level `text` fallback is parsed for mentions too, so escape it the same way.- lines = [_escape_mrkdwn(pr.summary) for pr in summary.prs]+ lines = [escape_slack_mrkdwn(pr.summary) for pr in summary.prs]return "\n".join(lines) or "No merged PRs worth a mention."diff --git a/products/stamphog/backend/tests/conftest.py b/products/stamphog/backend/tests/conftest.pyindex d42e258aef95..b3fdf01f43d1 100644--- a/products/stamphog/backend/tests/conftest.py+++ b/products/stamphog/backend/tests/conftest.py@@ -259,7 +259,7 @@ def stamphog_chain() -> Iterator[StamphogChain]:patch("products.stamphog.backend.tasks.tasks.transaction.on_commit", side_effect=_run_on_commit_immediately))stack.enter_context(patch("products.stamphog.backend.logic.slack_digest.SlackIntegration", fake_slack))- stack.enter_context(patch("posthog.team_notifications.slack.SlackIntegration", fake_slack))+ stack.enter_context(patch("posthog.slack.channels.SlackIntegration", fake_slack))stack.enter_context(patch("products.stamphog.backend.logic.digest.build_ai_gateway_anthropic_client",diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.pyindex 31227cbc7ec3..4c49c18757cc 100644--- a/products/stamphog/backend/tests/test_digest.py+++ b/products/stamphog/backend/tests/test_digest.py@@ -19,7 +19,7 @@ from structlog.testing import capture_logsfrom posthog.models.integration import Integrationfrom posthog.models.scoping import team_scope-from posthog.team_notifications.slack import SlackChannel+from posthog.slack.channels import SlackChannelfrom products.stamphog.backend.facade.enums import AudienceReason, ChannelResolutionSource, DigestRunStatusfrom products.stamphog.backend.logic.audiences import REPO_AUDIENCE_PREFIXdiff --git a/products/tasks/backend/logic/services/comment_slack_dm.py b/products/tasks/backend/logic/services/comment_slack_dm.pyindex 5338075aa6c1..1b7e158de7de 100644--- a/products/tasks/backend/logic/services/comment_slack_dm.py+++ b/products/tasks/backend/logic/services/comment_slack_dm.py@@ -20,15 +20,16 @@ from django.core.exceptions import ValidationErrorimport structlogfrom posthog.comment.access import task_comment_target_is_accessible-from posthog.comment.formatting import escape_slack_mrkdwn, rich_content_to_slack_payload+from posthog.comment.formatting import rich_content_to_slack_payloadfrom posthog.dataclasses import frozen-from posthog.helpers.slack_identity import resolve_slack_userfrom posthog.models.comment import Commentfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import NOTIFICATION_DEFAULTS, Userfrom posthog.models.user_integration import UserIntegration+from posthog.slack.formatting import escape_slack_mrkdwn+from posthog.slack.identity import resolve_slack_userfrom posthog.user_permissions import UserPermissionsfrom products.canvas.backend.models import Canvasdiff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.pyindex 883142d3ae97..536215f47565 100644--- a/products/tasks/backend/logic/services/living_artifacts.py+++ b/products/tasks/backend/logic/services/living_artifacts.py@@ -24,8 +24,9 @@ import structlogfrom slack_sdk.errors import SlackApiErrorfrom posthog.event_usage import groups-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_blockfrom posthog.ph_client import ph_scoped_capture+from posthog.slack.formatting import escape_slack_mrkdwn+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_blockfrom posthog.storage import object_storagefrom posthog.utils import absolute_uri@@ -1295,7 +1296,7 @@ def _artifact_display_title(artifact: TaskArtifact) -> str:def _artifact_fallback_text(artifact: TaskArtifact) -> str:# Slack parses a message's top-level text as mrkdwn, so an artifact named `<@U…>` or# `<!channel>` would notify from the PostHog bot — escape it like the title block does.- return _escape_slack_mrkdwn_text(_artifact_display_title(artifact))+ return escape_slack_mrkdwn(_artifact_display_title(artifact))def _chart_card_blocks(card: _SlackImageCard) -> list[dict[str, Any]]:@@ -1307,7 +1308,7 @@ def _chart_card_blocks(card: _SlackImageCard) -> list[dict[str, Any]]:else:image_block = {"type": "image", "slack_file": {"id": card.file_id}, "alt_text": title}blocks: list[dict[str, Any]] = [- {"type": "section", "text": {"type": "mrkdwn", "text": f"*{_escape_slack_mrkdwn_text(title)}*"}},+ {"type": "section", "text": {"type": "mrkdwn", "text": f"*{escape_slack_mrkdwn(title)}*"}},image_block,]posthog_url = metadata.get("posthog_url")@@ -1561,17 +1562,13 @@ def _slack_canvas_url(response: dict[str, Any] | None, workspace_id: str | None,return None-def _escape_slack_mrkdwn_text(text: str) -> str:- return text.replace("&", "&").replace("<", "<").replace(">", ">")--def _post_canvas_created_message(slack: Any, mapping: Any, name: str, canvas_id: str | None, canvas_url: str | None) -> None:if not canvas_id:return- escaped_name = _escape_slack_mrkdwn_text(name).replace("|", " ")- escaped_canvas_id = _escape_slack_mrkdwn_text(canvas_id)+ escaped_name = escape_slack_mrkdwn(name).replace("|", " ")+ escaped_canvas_id = escape_slack_mrkdwn(canvas_id)canvas_reference = f"<{canvas_url}|{escaped_name}>" if canvas_url else f"*{escaped_name}*"try:post_slack_thread_reply(diff --git a/products/tasks/backend/logic/services/tests/test_living_artifacts.py b/products/tasks/backend/logic/services/tests/test_living_artifacts.pyindex b095477a29db..2e3d193d127c 100644--- a/products/tasks/backend/logic/services/tests/test_living_artifacts.py+++ b/products/tasks/backend/logic/services/tests/test_living_artifacts.py@@ -9,11 +9,11 @@ from django.test import SimpleTestCase, TestCase, override_settingsfrom parameterized import parameterized-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.slack_app.backend.models import SlackThreadTaskMappingdiff --git a/products/tasks/backend/loop_notifications.py b/products/tasks/backend/loop_notifications.pyindex e14b14fd7fc0..c88fa7d06c32 100644--- a/products/tasks/backend/loop_notifications.py+++ b/products/tasks/backend/loop_notifications.py@@ -22,6 +22,7 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.email import EmailMessage, get_email_team_and_org_context, is_email_availablefrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.redis import get_client+from posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.tasks.push_notifications import send_user_pushfrom products.notifications.backend.facade.api import (@@ -195,7 +196,7 @@ def _send_slack(returnreport = payload.get("report")slack_body = str(report) if report else body- text = _truncate(f"*{_escape_slack_mrkdwn(title)}*\n{_escape_slack_mrkdwn(slack_body)}", _SLACK_BODY_MAX_CHARS)+ text = _truncate(f"*{escape_slack_mrkdwn(title)}*\n{escape_slack_mrkdwn(slack_body)}", _SLACK_BODY_MAX_CHARS)SlackIntegration(integration, source="loop_notifications").client.chat_postMessage(channel=channel, text=text, unfurl_links=False, unfurl_media=False)@@ -250,7 +251,3 @@ def _truncate(text: str, limit: int) -> str:if len(text) <= limit:return textreturn text[: limit - 1] + "…"---def _escape_slack_mrkdwn(text: str) -> str:- return text.replace("&", "&").replace("<", "<").replace(">", ">")diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.pyindex 4b7ed89ee5bb..017fe29e7964 100644--- a/products/tasks/backend/temporal/slack_relay/activities.py+++ b/products/tasks/backend/temporal/slack_relay/activities.py@@ -5,8 +5,8 @@ from typing import Anyfrom temporalio import activityfrom posthog.dataclasses import frozen-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, opens_with_line_anchored_markdownfrom posthog.object_tags.slack import rewrite_object_tags_for_slack+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, opens_with_line_anchored_markdownfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import close_db_connectionsdiff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.pyindex b322c5804835..96060e9b29ce 100644--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py@@ -10,11 +10,11 @@ from django.test import TestCase, override_settingsfrom parameterized import parameterizedfrom slack_sdk.errors import SlackApiError-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User+from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom products.slack_app.backend.models import SlackThreadTaskMappingfrom products.tasks.backend.logic.services.living_artifacts import SlackFileDeliveryResultdiff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.pyindex d9f9b97a3b18..b3cb6e202c40 100644--- a/products/visual_review/backend/logic/debt_digest.py+++ b/products/visual_review/backend/logic/debt_digest.py@@ -51,14 +51,13 @@ import structlogfrom owners_yaml.resolver import Purpose, team_channelfrom owners_yaml.schema import Producer, TeamEntry-from posthog.comment.formatting import escape_slack_mrkdwnfrom posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priorityfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.user import Userfrom posthog.ownership.github_files import fetcher_for_teamfrom posthog.ownership.paths import UNOWNED_TEAM, PathOwnership, resolve_path_owners-from posthog.team_notifications.slack import (+from posthog.slack.channels import (MAX_BLOCKS,MAX_BUTTON_URL_CHARS,MAX_SECTION_CHARS,@@ -78,6 +77,7 @@ from posthog.team_notifications.slack import (post_with_join,section_block,)+from posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.utils import human_list, pluralizefrom ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYS, TOLERATION_PILEUP_WINDOW_DAYSdiff --git a/products/visual_review/backend/tests/logic/test_debt_digest.py b/products/visual_review/backend/tests/logic/test_debt_digest.pyindex 3fad3a11b75c..53839c5cca39 100644--- a/products/visual_review/backend/tests/logic/test_debt_digest.py+++ b/products/visual_review/backend/tests/logic/test_debt_digest.py@@ -12,13 +12,7 @@ from owners_yaml.schema import TeamEntryfrom posthog.models.team.team import Teamfrom posthog.ownership.paths import UNOWNED_TEAM, PathOwnership-from posthog.team_notifications.slack import (- MAX_BLOCKS,- MAX_SECTION_CHARS,- MAX_TEXT_CHARS,- SlackChannel,- SlackPostRefused,-)+from posthog.slack.channels import MAX_BLOCKS, MAX_SECTION_CHARS, MAX_TEXT_CHARS, SlackChannel, SlackPostRefusedfrom products.visual_review.backend.facade.contracts import (FLAKINESS_EXPIRY_SOON_DAYS,