: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
feat(stamphog): post a team's first digest without a manual enable (#85257)
Julian Bezd4c2a9dd68ed
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.mdindex 8abe6955d499..4246be8575fe 100644--- a/products/stamphog/AGENTS.md+++ b/products/stamphog/AGENTS.md@@ -140,14 +140,19 @@ narrow:- A manually-created repo config (blank `installation_id`) binds **disabled** when a sync adoptsit: its flags were set by someone who never proved GitHub access. Reinstall rebinds keepsettings — those were configured under a verified binding.-- Name-matched Slack digest channels provision **disabled** pending a human enable (a workspace- member can squat a channel named like a team slug). Channels named by a declaration — the repo's- `digest:` config, or a team's entry in the root `owners.yaml` registry — auto-enable, because- somebody typed that name on a protected branch. The derived `#<slug>` is not a declaration: the- registry step returns nothing when a team has no entry, so it falls through to the name match and- its disabled-pending-human rule rather than laundering a guess into a declaration. Only the- repo's own `digest:` channel skips the shared-channel exclusion; the registry can name a channel- for a team the declaring repo does not own, so that path keeps the leak guard.+- Auto-provisioned digest channels arrive **enabled**, a bare Slack name match included. Only+ workspace members can create a channel, and a digest carries merged PR titles and summaries those+ same people can read on the PRs, so gating a name match behind a human enable bought a silent+ no-op — a channel row, no run row, no post, and an info log in a worker pod — rather than+ protection. The exclusion that stays is the shared-channel one, the only path where a digest+ leaves the workspace: only the repo's own `digest:` channel skips it, because the `owners.yaml`+ registry can name a channel for a team the declaring repo does not own.+- The app is not a member of a channel it only matched by name, so `post_digest` joins on+ `not_in_channel` and retries the post once. The join is attempted, never gated on the scope:+ `conversations.join` needs `channels:join`, and whether an install granted it is invisible to the+ person who set the digest up, so asking Slack is the only way to find out. A refused join fails+ the run with an error naming the invite, which is a signal in the digests scene and self-heals the+ moment somebody adds the app.- A declared channel that does not resolve is a dead end, never a retry with the audience slug —the slug is the wrong name the declaration exists to correct.- PR content — title, body, diff, comments, reactions — is untrusted input everywhere, includingdiff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex f1b7e99311c9..cf7bc3eb54df 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -19,7 +19,7 @@ On top of reviews, a repo can enable a daily Slack digest of its merged PRs (`baA merge fans out to every audience it belongs to (`backend/logic/audiences.py`): the author's GitHub team (or the channel the repo declares under `digest:` in `.stamphog/policy.yml`), plus every team owning a file it changed, read back from the ownership the review already resolved. So a team hears both what it shipped and what changed in its area, and a `PullRequestAudience` row per audience is what the daily run claims — one channel failing to post never strands the merge for another.-Each audience resolves to a Slack channel in three steps (`backend/logic/channel_resolution.py`): the repo's declared channel, then the team's entry in the repo's root `owners.yaml` registry (read through `posthog_owners`, which is what routes a team whose channel isn't named after its slug), then a plain name match.+Each audience resolves to a Slack channel in three steps (`backend/logic/channel_resolution.py`): the repo's declared channel, then the team's entry in the repo's root `owners.yaml` registry (read through `posthog_owners`, which is what routes a team whose channel isn't named after its slug), then a plain name match. A resolved channel is enabled straight away and the app joins it on the first post, so a team's digest starts without anyone wiring it up — channels shared outside the workspace are skipped, and disabling one in the Stamphog scene is a permanent opt-out.Summaries are written where the diff is. The reviewer emits a one-line `change_summary` alongside its verdict, which is stamped onto the merged PR; the daily run condenses those rather than guessing from PR titles, and for an owning team it also sees which of the changed files are theirs, so a repo-wide sweep that grazed two of them can be dropped as noise.diff --git a/products/stamphog/backend/logic/channel_resolution.py b/products/stamphog/backend/logic/channel_resolution.pyindex a38c0aab8c6a..d0e03939a2f3 100644--- a/products/stamphog/backend/logic/channel_resolution.py+++ b/products/stamphog/backend/logic/channel_resolution.py@@ -288,16 +288,14 @@ def resolve_slack_destination(def auto_provision_channel(team_id: int, audience_key: str) -> DigestChannel | None:"""Create a DigestChannel for (team, audience_key) if a Slack destination resolves.- Repo-declared channels (``digest:`` in .stamphog config, read from the default branch) are the- maintainer's explicit pick and provision enabled. A bare name match provisions DISABLED, pending- a human enable in the UI: any workspace member can create a public channel named after a GitHub- team slug, so auto-posting to a name-matched channel would let a squatter receive private repo- titles and summaries.+ Every resolution source provisions enabled, a bare name match included. Only workspace members+ can create a Slack channel, and a digest carries merged PR titles and summaries the same people+ can already read on the PRs themselves. The exclusion that does matter is the shared-channel one+ (see _SHARED_CHANNEL_FLAGS), which is the only path where a digest leaves the workspace.No-op (returns None, logged) when: the team has no Slack integration, no channel namematches, or a row already exists for this (team, audience_key) — including a disabled one,- since disabled means a human opted out (or hasn't confirmed a name match yet) and- auto-provisioning must never resurrect it.+ since disabled means a human opted out and auto-provisioning must never resurrect it."""if DigestChannel.objects.for_team(team_id).filter(audience_key=audience_key).exists():logger.info("stamphog_channel_resolution_row_exists", team_id=team_id, audience_key=audience_key)@@ -316,7 +314,7 @@ def auto_provision_channel(team_id: int, audience_key: str) -> DigestChannel | Nslack_integration_id=slack_integration_id,slack_channel_id=channel["id"],slack_channel_name=channel["name"],- enabled=resolution_source != ChannelResolutionSource.SLACK_NAME_MATCH,+ enabled=True,resolution_source=resolution_source,)except IntegrityError:diff --git a/products/stamphog/backend/logic/slack_digest.py b/products/stamphog/backend/logic/slack_digest.pyindex ca99f514a36e..483961d3cf71 100644--- a/products/stamphog/backend/logic/slack_digest.py+++ b/products/stamphog/backend/logic/slack_digest.py@@ -10,6 +10,8 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGimport structlog+from slack_sdk.errors import SlackApiError+from slack_sdk.web import SlackResponsefrom posthog.models.integration import Integration, SlackIntegration@@ -101,22 +103,68 @@ def _build_fallback_text(summary: DigestSummary) -> str:return "\n".join(lines) or "Merged PRs digest"-def post_digest(team_id: int, digest_channel: DigestChannel, summary: DigestSummary) -> str | None:- """Post the digest to the channel's Slack destination. Returns the message ts, or None."""- integration = Integration.objects.filter(- id=digest_channel.slack_integration_id, team_id=team_id, kind="slack"- ).first()- if integration is None:- raise DigestSlackError(f"No slack integration {digest_channel.slack_integration_id} for team {team_id}")-+def _post_message(slack: SlackIntegration, digest_channel: DigestChannel, summary: DigestSummary) -> SlackResponse:# No unfurls: the summary text is LLM output over untrusted PR content, so a prompt-injected# URL must not make Slack's unfurler fetch an attacker's server from inside the workspace.- response = SlackIntegration(integration).client.chat_postMessage(+ return slack.client.chat_postMessage(channel=digest_channel.slack_channel_id,blocks=_build_blocks(summary),text=_build_fallback_text(summary),unfurl_links=False,unfurl_media=False,)+++def _join_channel(slack: SlackIntegration, digest_channel: DigestChannel) -> str | None:+ """Join the channel so the retried post lands. Returns Slack's error code when it refused.++ A channel resolved by name match is one the app was never invited to, which is the normal state+ for an auto-provisioned row, so joining is what saves every team a manual ``/invite``. Tried+ rather than gated on the scope: ``conversations.join`` needs ``channels:join``, and whether an+ install granted it is not something the person who set up the digest can see or change. Slack+ answers ``missing_scope`` in under a second, and the caller turns that into an error naming the+ invite.++ ``already_in_channel`` counts as joined: two audiences can resolve to the same channel, so+ another worker may join between this one's failed post and its join, and treating that as a+ refusal would fail a digest whose retry would have gone through.+ """+ try:+ slack.client.conversations_join(channel=digest_channel.slack_channel_id)+ except SlackApiError as e:+ error = str(e.response.get("error") or "unknown_error")+ if error == "already_in_channel":+ return None+ logger.warning("stamphog_digest_join_failed", digest_channel_id=str(digest_channel.id), error=error)+ return error+ return None+++def post_digest(team_id: int, digest_channel: DigestChannel, summary: DigestSummary) -> str | None:+ """Post the digest to the channel's Slack destination. Returns the message ts, or None."""+ integration = Integration.objects.filter(+ id=digest_channel.slack_integration_id, team_id=team_id, kind="slack"+ ).first()+ if integration is None:+ raise DigestSlackError(f"No slack integration {digest_channel.slack_integration_id} for team {team_id}")++ slack = SlackIntegration(integration)+ try:+ response = _post_message(slack, digest_channel, summary)+ except SlackApiError as e:+ if e.response.get("error") != "not_in_channel":+ raise+ # Retry once behind the join. A refusal names both Slack's reason and the fix: the run is what+ # a human reads, and neither "invite the app" nor why the join failed is derivable from a+ # raw Slack error code.+ join_error = _join_channel(slack, digest_channel)+ if join_error is not None:+ channel = digest_channel.slack_channel_name or digest_channel.slack_channel_id+ raise DigestSlackError(+ f"Couldn't post to #{channel}. PostHog isn't in the channel and couldn't join it: Slack said "+ f"{join_error}. Invite the app with /invite @PostHog."+ ) from e+ response = _post_message(slack, digest_channel, summary)+ts = response.get("ts")return str(ts) if ts else Nonediff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.pyindex 0273d672042e..04f87ecc8aa7 100644--- a/products/stamphog/backend/tests/fakes.py+++ b/products/stamphog/backend/tests/fakes.py@@ -17,9 +17,12 @@ import reimport hmacimport jsonimport hashlib+from collections.abc import Iterablefrom dataclasses import dataclassfrom typing import Any+from slack_sdk.errors import SlackApiError+# --- Webhook payload + signing (mirrors what GitHub sends) ---_RELEVANT_PR_FIELDS = ("number", "title", "body")@@ -392,15 +395,27 @@ def noop_raise_if_github_rate_limited(*args: Any, **kwargs: Any) -> None:class FakeSlackClient:- """Records ``chat_postMessage`` calls; returns a Slack-shaped ``{"ok", "ts"}``."""+ """Records ``chat_postMessage`` calls; returns a Slack-shaped ``{"ok", "ts"}``.++ A channel in ``needs_join`` rejects the post with ``not_in_channel`` until ``conversations_join``+ lands, which is what Slack does for a public channel the app was never invited to.+ """- def __init__(self, posted: list[dict[str, Any]]) -> None:+ def __init__(self, posted: list[dict[str, Any]], needs_join: set[str], joined: list[str]) -> None:self._posted = posted+ self._needs_join = needs_join+ self._joined = joineddef chat_postMessage(self, *, channel: str, blocks: list[dict], text: str, **kwargs: Any) -> dict[str, Any]:+ if channel in self._needs_join and channel not in self._joined:+ raise SlackApiError("not_in_channel", {"ok": False, "error": "not_in_channel"})self._posted.append({"channel": channel, "blocks": blocks, "text": text})return {"ok": True, "ts": "1234.5678"}+ def conversations_join(self, *, channel: str) -> dict[str, Any]:+ self._joined.append(channel)+ return {"ok": True}+class FakeSlackIntegration:"""Stand-in for ``posthog.models.integration.SlackIntegration``.@@ -412,21 +427,30 @@ class FakeSlackIntegration:posted_messages: list[dict[str, Any]] = []workspace_channels: list[dict[str, str]] = []+ # Channels the app has not been invited to, and the ones it joined by itself during the run.+ channels_needing_join: set[str] = set()+ joined_channels: list[str] = []def __init__(self, integration: Any) -> None:self.integration = integration@propertydef client(self) -> FakeSlackClient:- return FakeSlackClient(FakeSlackIntegration.posted_messages)+ return FakeSlackClient(+ FakeSlackIntegration.posted_messages,+ FakeSlackIntegration.channels_needing_join,+ FakeSlackIntegration.joined_channels,+ )def list_channels(self, should_include_private_channels: bool = False, authed_user: str = "") -> list[dict]:return sorted(FakeSlackIntegration.workspace_channels, key=lambda c: c["name"])@classmethod- def reset(cls, channels: list[dict[str, str]]) -> None:+ def reset(cls, channels: list[dict[str, str]], *, needs_join: Iterable[str] = ()) -> None:cls.posted_messages = []cls.workspace_channels = list(channels)+ cls.channels_needing_join = set(needs_join)+ cls.joined_channels = []# --- Sandbox fake at the ``get_sandbox_class_for_backend`` seam ---diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.pyindex 7e2a80617388..dcc24b5a69a1 100644--- a/products/stamphog/backend/tests/test_digest.py+++ b/products/stamphog/backend/tests/test_digest.py@@ -12,7 +12,9 @@ from django.db.models import QuerySetfrom django.utils import timezonefrom parameterized import parameterized+from slack_sdk.errors import SlackApiError+from posthog.models.integration import Integrationfrom posthog.models.scoping import team_scopefrom products.stamphog.backend.facade.enums import AudienceReason, DigestRunStatus@@ -22,6 +24,7 @@ from products.stamphog.backend.logic.digest import (_parse_llm_response,summarize_merged_prs,)+from products.stamphog.backend.logic.slack_digest import DigestSlackError, post_digestfrom products.stamphog.backend.models import (DigestChannel,DigestRun,@@ -442,3 +445,90 @@ def test_only_a_genuinely_empty_result_posts_nothing(_name: str, content: str, aelse:with pytest.raises(ValueError):_parse_llm_response(content, prs_by_index)+++def _slack_stub(post_error: str, join_error: str | None, joined: list[str]) -> MagicMock:+ """SlackIntegration stand-in whose post fails with ``post_error`` until the app has joined."""+ stub = MagicMock()++ def post(**kwargs: Any) -> dict[str, Any]:+ if not joined:+ raise SlackApiError(post_error, {"ok": False, "error": post_error})+ return {"ok": True, "ts": "9999.1"}++ def join(channel: str) -> dict[str, Any]:+ if join_error:+ # already_in_channel means somebody else already put the app in there, so the retried+ # post has to succeed — the stub records the membership before raising.+ if join_error == "already_in_channel":+ joined.append(channel)+ raise SlackApiError(join_error, {"ok": False, "error": join_error})+ joined.append(channel)+ return {"ok": True}++ stub.client.chat_postMessage.side_effect = post+ stub.client.conversations_join.side_effect = join+ return stub+++ "post_error,join_error,expected_error,joined",+ [+ ("not_in_channel", None, None, ["C1"]),+ ("not_in_channel", "already_in_channel", None, ["C1"]),+ ("not_in_channel", "missing_scope", DigestSlackError, []),+ ("channel_not_found", None, SlackApiError, []),+ ],+ ids=[+ "joins_then_posts",+ "already_in_channel_counts_as_joined",+ "refused_join_names_the_reason_and_the_invite",+ "other_slack_errors_propagate",+ ],+)[email protected]_db(databases=PRODUCT_DATABASES)+def test_post_digest_joins_a_channel_the_app_was_never_invited_to(+ team, post_error: str, join_error: str | None, expected_error: type[Exception] | None, joined: list[str]+) -> None:+ # An auto-provisioned channel is matched off the workspace list, so the app is not a member of it+ # and the first post comes back not_in_channel. Joining is what makes that post land, and a+ # concurrent worker joining first (already_in_channel) must not fail a digest whose retry would+ # have gone through. A genuine refusal names Slack's reason and the invite, because neither is+ # derivable from an error code by the person reading the run.+ integration = Integration.objects.create(+ team_id=team.id, kind="slack", config={}, sensitive_config={"access_token": "x"}+ )+ channel = DigestChannel.objects.for_team(team.id).create(+ team_id=team.id,+ audience_key=AUDIENCE,+ slack_integration_id=integration.id,+ slack_channel_id="C1",+ slack_channel_name="team-devex",+ )+ summary = DigestSummary(+ intro="1 merged.",+ prs=[+ DigestPRSummary(+ pr_number=1,+ title="Add util helper",+ url="https://github.com/acme/widgets/pull/1",+ author_login="devex-dev",+ summary="Add util helper",+ repository=REPO,+ )+ ],+ )+ actually_joined: list[str] = []+ stub = _slack_stub(post_error, join_error, actually_joined)++ with patch("products.stamphog.backend.logic.slack_digest.SlackIntegration", return_value=stub):+ if expected_error is None:+ assert post_digest(team.id, channel, summary) == "9999.1"+ else:+ with pytest.raises(expected_error) as caught:+ post_digest(team.id, channel, summary)+ if expected_error is DigestSlackError:+ assert "/invite @PostHog" in str(caught.value)+ assert str(join_error) in str(caught.value)++ assert actually_joined == joineddiff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.pyindex 22165e255598..d480851278af 100644--- a/products/stamphog/backend/tests/test_integration.py+++ b/products/stamphog/backend/tests/test_integration.py@@ -1256,7 +1256,7 @@ _OWNERS_YAML_HEAD = "version: 1\nowners: []\n"(_OWNERS_YAML_HEAD + "teams:\n other-team:\n slack: '#elsewhere'\n",[{"id": "C-LOGS", "name": "logs"}],- ("C-LOGS", False, ChannelResolutionSource.SLACK_NAME_MATCH),+ ("C-LOGS", True, ChannelResolutionSource.SLACK_NAME_MATCH),),(_OWNERS_YAML_HEAD + "teams:\n logs:\n slack: '#team-apm'\n", [{"id": "C-LOGS", "name": "logs"}], None),],@@ -1436,13 +1436,12 @@ def test_unreadable_repo_behind_the_winner_still_provisions(team, stamphog_chain@pytest.mark.django_db(databases=PRODUCT_DATABASES)-def test_daily_digest_provisions_name_matched_channel_disabled(team, stamphog_chain: StamphogChain) -> None:- # A bare Slack name match provisions the channel DISABLED and posts nothing: any workspace- # member can pre-create a public channel named after a GitHub team slug, so auto-posting to a- # name-matched channel would hand a squatter private repo titles and summaries. A human enables- # the channel in the UI; the merged PR stays unlinked so the next run after enabling picks it- # up. Repo-declared channels (maintainer's explicit pick) still provision enabled — see the- # STAMPHOG_CONFIG test below.+def test_daily_digest_provisions_name_matched_channel_and_posts_the_same_run(+ team, stamphog_chain: StamphogChain+) -> None:+ # A team's first digest must land without anyone wiring it up: the name match provisions the+ # channel enabled, the app joins a channel it was never invited to, and the merged PR goes out+ # on that same run rather than waiting on a human to flip a toggle nobody is watching.repo_config = _repo_config(team.id)integration = Integration.objects.create(team_id=team.id, kind="slack", config={"authed_user": {"id": "U1"}}, sensitive_config={"access_token": "x"}@@ -1459,23 +1458,15 @@ def test_daily_digest_provisions_name_matched_channel_disabled(team, stamphog_chPullRequestAudience.objects.for_team(team.id).create(team_id=team.id, pull_request=pr, audience_key="team-devex", reason=AudienceReason.AUTHORED)- fakes.FakeSlackIntegration.reset(channels=[{"id": "C-DEVEX", "name": "team-devex"}])+ fakes.FakeSlackIntegration.reset(channels=[{"id": "C-DEVEX", "name": "team-devex"}], needs_join=["C-DEVEX"])send_daily_digests()channel = DigestChannel.objects.for_team(team.id).get(audience_key="team-devex")- assert channel.enabled is False+ assert channel.enabled is Trueassert channel.resolution_source == ChannelResolutionSource.SLACK_NAME_MATCHassert channel.slack_integration_id == integration.id-- assert not DigestRun.objects.for_team(team.id).filter(digest_channel=channel).exists()- assert fakes.FakeSlackIntegration.posted_messages == []- pr.refresh_from_db()- assert pr.digest_run_id is None-- # A human enabling the channel is the confirmation step — the next daily run then posts.- DigestChannel.objects.for_team(team.id).filter(id=channel.id).update(enabled=True)- send_daily_digests()+ assert fakes.FakeSlackIntegration.joined_channels == ["C-DEVEX"]run = DigestRun.objects.for_team(team.id).get(digest_channel=channel)assert run.status == DigestRunStatus.COMPLETED