: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(commands): run pull request commands from slack mentions (#116859)
Julian Bezb535c121ad8e
diff --git a/products/commands/README.md b/products/commands/README.mdindex 11c6ebdd661c..336f850a4a7b 100644--- a/products/commands/README.md+++ b/products/commands/README.md@@ -34,6 +34,24 @@ Both are generated from `backend/logic/schema.py`, like the `@posthog help` repl3. `channels/github/comments.py` runs in the task. It applies the comment's silent checks (listed in its module docstring), then hands the command to `logic/dispatcher.py`, which runs the steps every channel shares and calls the command's handler.4. `logic/handlers.py` calls the target product's facade and returns the text of the reply.+## Commands from Slack++The same commands run from a Slack message that mentions the PostHog app and names the pull request by its URL, before or after the command:++```text+@PostHog review --deep https://github.com/PostHog/posthog/pull/123+@PostHog https://github.com/PostHog/posthog/pull/123 review --deep+@PostHog qa https://github.com/PostHog/posthog/pull/123 check the signup form+```++- Only a message that opens with the app's mention and reads exactly as a command runs one. Free text, such as "can you review this deeply", and a mistyped option go to the agent as before.+- The `slack-commands` flag decides the rollout per organization, once, inside the Slack webhook. Outside it, the message also goes to the agent.+- Every command that ran gets an answer in the thread, refusals included, because the message no longer reaches the agent.+- The Slack app asks `may_hold_command` first, a check with no queries, so most mentions never reach this product. It hands the rest to `accept_slack_mention` inside its webhook, as plain text. This product reads it (`channels/slack/`), runs it in its own task like a pull request comment, and answers in the thread through the Slack integration the mention came in on.+- A Slack command has no GitHub permission check. It runs as a PostHog account that is a member of the project, like the review trigger in the PostHog API and MCP.+- It may run as the accounts the Slack app resolves for the person, the ones its agent acts as: first their linked PostHog account, else the member of a connected organization with their Slack email, then every other account linked to their Slack user. The command picks the project first, and the first of these accounts that is a member of it acts there.+- It reaches only projects of organizations that connected that Slack workspace, the same scope the agent has. In a shared channel that has not approved PostHog, the message goes to the agent, whose approval gate applies.+## Adding a commandDeclare the command in `logic/schema.py`: an args dataclass built with `flag()`, `option()` and `text()`, and a `CommandDeclaration` in `COMMAND_DECLARATIONS`.diff --git a/products/commands/backend/channels/github/parsing.py b/products/commands/backend/channels/github/parsing.pyindex 779e90a83f17..bd4c6036b6d0 100644--- a/products/commands/backend/channels/github/parsing.py+++ b/products/commands/backend/channels/github/parsing.py@@ -9,16 +9,14 @@ command text they answer."""import re-import unicodedatafrom markdown_it import MarkdownItfrom markdown_it.token import Tokenfrom posthog.dataclasses import frozen-from ...logic.schema import HELP_VERB, MENTION+from ...logic.schema import HELP_VERB, MENTION, sanitize_argument-MAX_ARGUMENT_LENGTH = 200# A command comment is short, and the CommonMark parse of the largest comment GitHub allows costs# most of a second inside the webhook request.MAX_BODY_LENGTH = 10_000@@ -83,18 +81,6 @@ def parse_command(body: str) -> ParseResult:return commands[0] if commands else None-def sanitize_argument(raw: str) -> str:- """Make the free text after the verb safe to store, log and hand to a product.-- Drops control and format characters, which removes bidirectional overrides and zero-width- characters that can make text read differently than it runs. Collapses whitespace and caps- the length, so an argument stays one short line.- """- kept = "".join(char for char in raw if unicodedata.category(char)[0] != "C" or char in " \t")- collapsed = " ".join(kept.split())- return collapsed[:MAX_ARGUMENT_LENGTH]--def _paragraph_lines(inline: Token) -> list[str]:lines = [""]for child in inline.children or []:diff --git a/products/commands/backend/channels/slack/__init__.py b/products/commands/backend/channels/slack/__init__.pynew file mode 100644index 000000000000..307674c58dc1--- /dev/null+++ b/products/commands/backend/channels/slack/__init__.py@@ -0,0 +1 @@+"""Commands from Slack messages that mention the PostHog app."""diff --git a/products/commands/backend/channels/slack/mentions.py b/products/commands/backend/channels/slack/mentions.pynew file mode 100644index 000000000000..92340ab357f7--- /dev/null+++ b/products/commands/backend/channels/slack/mentions.py@@ -0,0 +1,183 @@+"""Commands from Slack mentions: which installation, who may ask, and how the answer goes back.++The Slack app hands every mention it would give its agent to ``accept_slack_mention``, inside the+Slack webhook. ``read_slack_command`` takes it only when it reads exactly as a command and its+organization is in the rollout. Everything else stays with the agent, so turning the rollout off+gives people the agent back. The rollout and the projects a command may reach are decided there,+once, and the task trusts them. The run happens in this product's task, and the answer goes out+through the Slack integration the mention came in on.++A Slack command needs no GitHub permission check: it runs as a PostHog account that is a member+of the project, the same as the review trigger in the PostHog API and MCP. It reaches only+projects of organizations that connected this Slack workspace, the same scope the agent has.+"""++from collections.abc import Collection++import structlog++from posthog.dataclasses import frozen+from posthog.models.integration import Integration, SlackIntegration+from posthog.models.user import User+from posthog.slack.channels import post_message+from posthog.slack.markdown import slack_markdown_block++from ...facade.contracts import SlackMention+from ...logic.admission import claim, rolled_out_team_ids, within_rate_limit+from ...logic.commands import Answer, CommandRequest, DispatchOutcome, PullRequestRef+from ...logic.dispatcher import Admission, CommandDispatcher+from ...logic.github import CommandGitHub, InstallationGitHub+from ...logic.registry import COMMANDS+from ...logic.schema import ArgumentError, resolve_verb+from .parsing import parse_slack_command++logger = structlog.get_logger(__name__)++ROLLOUT_FLAG = "slack-commands"+++@frozen+class SlackCommandRequest:+ """Everything the task needs: the command, where it may run, and the thread it answers in."""++ installation_id: str+ # Projects on the installation, in the rollout and in the organizations that connected the+ # Slack workspace, oldest integration first.+ team_ids: tuple[int, ...]+ repository: str+ pr_number: int+ verb: str+ argument: str+ slack_team_id: str+ slack_user_id: str+ channel: str+ thread_ts: str+ message_ts: str+ integration_id: int+ integration_team_id: int+ user_ids: tuple[int, ...]+++def _installation_id(owner: str, organization_ids: Collection[str]) -> str | None:+ """The PostHog GitHub App installation on the repository owner, in one of these organizations."""+ # nosemgrep: github-installation-first-team -- only the installation id is read; the newest row wins over one left from an earlier install+ integration = (+ Integration.objects.filter(+ kind="github", config__account__name__iexact=owner, team__organization_id__in=organization_ids+ )+ .order_by("-id")+ .only("integration_id")+ .first()+ )+ return integration.integration_id if integration is not None else None+++def read_slack_command(mention: SlackMention) -> SlackCommandRequest | None:+ """The command a Slack mention runs on a pull request, or None to leave the mention to the agent."""+ parsed = parse_slack_command(mention.text)+ if parsed is None:+ return None+ # Only a message that reads exactly as a command skips the agent. "can you review this deeply"+ # and a mistyped option are requests the agent can still answer.+ verb = resolve_verb(parsed.verb)+ spec = COMMANDS.get(verb) if verb is not None else None+ if spec is None or isinstance(spec.parse(parsed.argument), ArgumentError):+ return None+ owner = parsed.repository.split("/", 1)[0]+ installation_id = _installation_id(owner, mention.organization_ids)+ if installation_id is None:+ return None+ team_ids = rolled_out_team_ids(ROLLOUT_FLAG, installation_id, mention.organization_ids, only_evaluate_locally=True)+ if not team_ids:+ return None+ return SlackCommandRequest(+ installation_id=installation_id,+ team_ids=team_ids,+ repository=parsed.repository,+ pr_number=parsed.pr_number,+ verb=parsed.verb,+ argument=parsed.argument,+ slack_team_id=mention.slack_team_id,+ slack_user_id=mention.slack_user_id,+ channel=mention.channel,+ thread_ts=mention.thread_ts,+ message_ts=mention.message_ts,+ integration_id=mention.integration_id,+ integration_team_id=mention.integration_team_id,+ user_ids=mention.user_ids,+ )+++class SlackMentionChannel:+ name = "slack"+ unlinked_message = (+ "Your Slack account is not linked to a PostHog account, so I can't tell who to run this as. "+ "Connect Slack in your PostHog personal settings, then try again."+ )++ def __init__(self, command: SlackCommandRequest, github: CommandGitHub | None = None) -> None:+ self._command = command+ self._github = github+ self.request = CommandRequest(+ subject=PullRequestRef(+ installation_id=command.installation_id, repository=command.repository, number=command.pr_number+ ),+ verb=command.verb,+ argument=command.argument,+ ambiguous=False,+ # A Slack user has no GitHub login, and a display name is text they choose.+ requester="The requester",+ requested_via="Slack",+ )++ def admit(self) -> Admission | Answer | DispatchOutcome:+ # The message already skipped the agent, so a refusal that stays silent on GitHub answers+ # here. A duplicate stays silent: the first run answers.+ command = self._command+ claim_refusal = claim(f"commands:slack_message:{command.slack_team_id}:{command.channel}:{command.message_ts}")+ if claim_refusal == "claim_unavailable":+ return Answer(outcome=claim_refusal, message="I couldn't start this command. Try again in a few minutes.")+ if claim_refusal is not None:+ return claim_refusal+ if not within_rate_limit(f"commands:slack_user:{command.slack_team_id}:{command.slack_user_id}"):+ return Answer(+ outcome="rate_limited",+ message="You've sent a lot of commands in a short time. Try again in a few minutes.",+ )+ github = self._github or InstallationGitHub.for_installation(command.installation_id, command.team_ids)+ if github is None:+ return Answer(+ outcome="no_installation",+ message="I couldn't reach GitHub for this repository. Try again in a few minutes.",+ )+ return Admission(team_ids=command.team_ids, github=github)++ def linked_users(self) -> list[User]:+ user_ids = self._command.user_ids+ users = User.objects.in_bulk(user_ids)+ return [users[user_id] for user_id in user_ids if user_id in users and users[user_id].is_active]++ def reply(self, message: str) -> None:+ command = self._command+ integration = Integration.objects.filter(+ id=command.integration_id, team_id=command.integration_team_id, kind="slack"+ ).first()+ if integration is None:+ logger.warning("slack_command_reply_integration_missing", integration_id=command.integration_id)+ return+ try:+ post_message(+ SlackIntegration(integration),+ command.channel,+ [slack_markdown_block(message)],+ message,+ thread_ts=command.thread_ts,+ )+ except Exception:+ # Best effort, as for pull request comments: a lost answer must not turn a run that+ # started into a failure.+ logger.warning("slack_command_reply_failed", exc_info=True)+++def dispatch_slack_command(command: SlackCommandRequest, *, github: CommandGitHub | None = None) -> DispatchOutcome:+ return CommandDispatcher(SlackMentionChannel(command, github)).dispatch()diff --git a/products/commands/backend/channels/slack/parsing.py b/products/commands/backend/channels/slack/parsing.pynew file mode 100644index 000000000000..005f3791da72--- /dev/null+++ b/products/commands/backend/channels/slack/parsing.py@@ -0,0 +1,67 @@+"""Reads one pull request command out of a Slack message that mentions the PostHog app.++The Slack app removes its own mention and hands over plain text. What is left must be the command+and a pull request URL, in either order: ``review --deep https://github.com/PostHog/posthog/pull/123``+as in a shell, or ``https://github.com/PostHog/posthog/pull/123 review --deep``. Options and free+text, such as the focus of ``qa``, may also follow the URL. With the verb first, every word before+the URL must be an option, so a valued option takes the ``--name=value`` form there. Anything else is+not a command and stays with the agent, so this parser is strict on purpose: a sentence that happens+to hold a pull request URL, such as "review this <URL>", never runs a command.+"""++import re++from posthog.dataclasses import frozen++from ...logic.commands import REPOSITORY_NAME_RE+from ...logic.schema import sanitize_argument++_PULL_REQUEST_URL_RE = re.compile(+ r"https://github\.com/(?P<repository>[^/\s]+/[^/\s]+)/pull/(?P<number>[0-9]{1,9})(?:[/#?]\S*)?"+)+_VERB_RE = re.compile(r"[A-Za-z][\w-]{0,31}")+# The grammar reads an en or em dash as `--`, because macOS autocorrect types one.+_OPTION_PREFIXES = ("-", "–", "—")+++@frozen+class SlackPullRequestCommand:+ repository: str+ pr_number: int+ verb: str+ argument: str+++def may_hold_command(text: str) -> bool:+ """False when the message names nothing a command acts on. No queries, any message format."""+ return _PULL_REQUEST_URL_RE.search(text) is not None+++def parse_slack_command(text: str) -> SlackPullRequestCommand | None:+ words = text.split()+ if len(words) < 2:+ return None+ if _PULL_REQUEST_URL_RE.fullmatch(words[0]):+ url, verb, argument_words = words[0], words[1], words[2:]+ else:+ verb = words[0]+ url_index = next(+ (index for index, word in enumerate(words[1:], start=1) if not word.startswith(_OPTION_PREFIXES)), None+ )+ if url_index is None:+ return None+ url = words[url_index]+ argument_words = [*words[1:url_index], *words[url_index + 1 :]]+ match = _PULL_REQUEST_URL_RE.fullmatch(url)+ if match is None or not _VERB_RE.fullmatch(verb):+ return None+ repository = match.group("repository")+ pr_number = int(match.group("number"))+ if not REPOSITORY_NAME_RE.fullmatch(repository) or pr_number < 1:+ return None+ return SlackPullRequestCommand(+ repository=repository,+ pr_number=pr_number,+ verb=verb.lower(),+ argument=sanitize_argument(" ".join(argument_words)),+ )diff --git a/products/commands/backend/facade/api.py b/products/commands/backend/facade/api.pyindex d8817334ef7a..0d37aed0f435 100644--- a/products/commands/backend/facade/api.py+++ b/products/commands/backend/facade/api.py@@ -11,10 +11,12 @@ from collections.abc import Mappingimport structlogfrom ..channels.github.intake import CommentCommandRequest, Dropped, read_comment_command+from ..channels.slack.parsing import may_hold_command as _may_hold_command+from .contracts import SlackMentionlogger = structlog.get_logger(__name__)-__all__ = ["accept_issue_comment"]+__all__ = ["SlackMention", "accept_issue_comment", "accept_slack_mention", "may_hold_command"]def accept_issue_comment(payload: Mapping[str, object]) -> None:@@ -47,3 +49,45 @@ def _enqueue(request: CommentCommandRequest) -> None:argument=request.argument,ambiguous=request.ambiguous,)+++def may_hold_command(text: str) -> bool:+ """False when a message names nothing a command acts on, so the caller can skip it for free.++ It runs no query, so a webhook that sees every message can call it first. True does not mean+ the message is a command: ``accept_slack_mention`` decides that.+ """+ return _may_hold_command(text)+++def accept_slack_mention(mention: SlackMention) -> str | None:+ """Queue the command in a Slack mention, if it holds one, and return its verb.++ Runs inside the Slack webhook. None leaves the mention to the agent: free text, a mistyped+ command, or an organization outside the rollout.+ """+ # Deferred: the Slack channel imports the dispatcher, and the GitHub consumer imports this module+ # inside the request for every pull request comment.+ from ..channels.slack.mentions import read_slack_command # noqa: PLC0415+ from ..tasks.tasks import run_slack_command # noqa: PLC0415++ command = read_slack_command(mention)+ if command is None:+ return None+ run_slack_command.delay(+ installation_id=command.installation_id,+ team_ids=list(command.team_ids),+ repository=command.repository,+ pr_number=command.pr_number,+ verb=command.verb,+ argument=command.argument,+ slack_team_id=command.slack_team_id,+ slack_user_id=command.slack_user_id,+ channel=command.channel,+ thread_ts=command.thread_ts,+ message_ts=command.message_ts,+ integration_id=command.integration_id,+ integration_team_id=command.integration_team_id,+ user_ids=list(command.user_ids),+ )+ return command.verbdiff --git a/products/commands/backend/facade/contracts.py b/products/commands/backend/facade/contracts.pyindex 362011b2881c..7922a7c6bafd 100644--- a/products/commands/backend/facade/contracts.py+++ b/products/commands/backend/facade/contracts.py@@ -1,5 +1,30 @@"""Contract types for commands.-The product exposes no data to other products yet: its only cross-product surface is the webhook-consumer's entry point in ``api.py``.+Other products reach commands through ``api.py``: the GitHub webhook consumer hands over comments,+and the Slack app hands over mentions with the type below."""++from posthog.dataclasses import frozen+++@frozen+class SlackMention:+ """A Slack message that mentions the PostHog app, as the Slack app hands it over."""++ # The text after the app's own mention, as plain text: links unwrapped to their URLs and+ # Slack's entities decoded.+ text: str+ slack_team_id: str+ slack_user_id: str+ channel: str+ thread_ts: str+ message_ts: str+ # The Slack integration the mention came in on. The answer goes out through it.+ integration_id: int+ integration_team_id: int+ # The PostHog accounts the requester may act as. First the one the Slack app resolved for them,+ # the account its agent acts as: their linked account, else the member of a connected+ # organization with their Slack email. Then every other account linked to their Slack user.+ user_ids: tuple[int, ...]+ # Organizations that connected this Slack workspace. A command reaches only their projects.+ organization_ids: tuple[str, ...]diff --git a/products/commands/backend/logic/admission.py b/products/commands/backend/logic/admission.pyindex e76e43f1fd7c..25a63a6030a5 100644--- a/products/commands/backend/logic/admission.py+++ b/products/commands/backend/logic/admission.py@@ -25,11 +25,17 @@ _REQUESTER_BUDGET = Budget(burst=5, per_hour=30)def rolled_out_team_ids(- flag: str, installation_id: str, organization_ids: Collection[str] | None = None+ flag: str,+ installation_id: str,+ organization_ids: Collection[str] | None = None,+ *,+ only_evaluate_locally: bool = False,) -> tuple[int, ...]:"""Projects on the installation whose organization is in the rollout, oldest integration first.- ``organization_ids`` narrows them, for a channel that may reach only some organizations.+ ``organization_ids`` narrows them, for a channel that may reach only some organizations. A caller+ inside a webhook passes ``only_evaluate_locally``, so a flag that cannot be evaluated locally+ reads as off instead of costing a remote call per project."""team_ids = list(dict.fromkeys(@@ -50,6 +56,7 @@ def rolled_out_team_ids(f"{flag}-installation-{installation_id}",organization_id=team.organization_id,team_id=team.id,+ only_evaluate_locally=only_evaluate_locally,)}return tuple(team_id for team_id in team_ids if team_id in rolled_out)diff --git a/products/commands/backend/logic/dispatcher.py b/products/commands/backend/logic/dispatcher.pyindex c53268c1924a..32fce67a183c 100644--- a/products/commands/backend/logic/dispatcher.py+++ b/products/commands/backend/logic/dispatcher.py@@ -3,13 +3,14 @@Every command passes the same steps, in this order, before its handler runs:1. The channel admits the request: its rollout, deduplication, rate limit and its own check of who- may ask. People who fail it get no answer at all, so the bot gives outsiders nothing to probe- and no way to make it post. Everyone past it gets a reply that says what happened.+ may ask. A refusal here gets no answer, so the bot gives outsiders nothing to probe and no way+ to make it post, unless the channel answers it: a Slack command that skipped the agent must+ not leave the person waiting. Everyone past it gets a reply that says what happened.2. The request holds exactly one command, the command exists, and its arguments match its grammar.3. The command's product names the projects it acts in, out of the rolled-out candidates: for``review``, the project that owns the repository in PostHog Review. Membership and access arechecked only there, and the requester's linked accounts must include a member of one of them.- With several linked accounts, the most recently linked member acts.+ With several linked accounts, the member the channel lists first acts.4. The subject allows the command, for example the pull request is open, and the command allowsforks if the head is a fork.5. The account has the access the command declares on the project, in PostHog access control.@@ -29,7 +30,7 @@ from posthog.models.user import Userfrom posthog.permissions import UserAccessControlfrom .commands import Answer, CommandContext, CommandRequest, DispatchOutcome, ProjectMember-from .github import CommandGitHub, InstallationGitHub+from .github import CommandGitHubfrom .identity import Requester, resolve_requesterfrom .registry import COMMANDS, CommandSpec, Invocation, help_textfrom .schema import HELP_VERB, ArgumentError, ResourceAccess, resolve_verb, usage@@ -51,8 +52,7 @@ class Admission:# Projects on the installation in the channel's rollout, oldest integration first. A command# runs only in one of them.team_ids: tuple[int, ...]- # A channel that already called GitHub passes its client. Otherwise dispatch makes one.- github: CommandGitHub | None = None+ github: CommandGitHubclass CommandChannel(Protocol):@@ -62,12 +62,13 @@ class CommandChannel(Protocol):request: CommandRequestunlinked_message: str- def admit(self) -> Admission | DispatchOutcome:- """The checks that stay silent: nobody who fails one hears from the bot."""+ def admit(self) -> Admission | Answer | DispatchOutcome:+ """The channel's own checks. A bare outcome refuses in silence, and an ``Answer`` refuses+ with a reply."""...def linked_users(self) -> list[User]:- """The active PostHog users linked to the requester, most recently linked first."""+ """The active PostHog users the requester may act as, the channel's first choice first."""...def reply(self, message: str) -> None: ...@@ -98,27 +99,25 @@ class CommandDispatcher:def _dispatch(self, spec: CommandSpec[Any] | None) -> DispatchOutcome:admission = self._channel.admit()+ if isinstance(admission, Answer):+ self._channel.reply(admission.message)+ return admission.outcomeif not isinstance(admission, Admission):return admission- github = admission.github or InstallationGitHub.for_installation(- self._channel.request.subject.installation_id, admission.team_ids- )- if github is None:- return "no_installation"command = self._runnable_command(spec)if isinstance(command, Answer):self._channel.reply(command.message)return command.outcome- return self._run(command, admission.team_ids, github)+ return self._run(command, admission.team_ids, admission.github)def _runnable_command(self, spec: CommandSpec[Any] | None) -> Invocation[Any] | Answer:"""The command to run, or the answer to a request that needs no PostHog account: help, andrequests with no runnable command."""request = self._channel.requestif request.ambiguous:- return Answer(outcome="ambiguous", message="Put one command in a comment, so it is clear which one to run.")+ return Answer(outcome="ambiguous", message="Send one command at a time, so it is clear which one to run.")if request.verb == HELP_VERB:return Answer(outcome="help", message=help_text())if spec is None:diff --git a/products/commands/backend/logic/handlers.py b/products/commands/backend/logic/handlers.pyindex 1fd5ef761e2e..a52f48844642 100644--- a/products/commands/backend/logic/handlers.py+++ b/products/commands/backend/logic/handlers.py@@ -12,7 +12,6 @@ from collections.abc import Collectionimport structlog-from posthog.models.scoping.manager import resolve_effective_team_idfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.utils import absolute_uri@@ -57,13 +56,11 @@ def review_target(ref: PullRequestRef, team_ids: tuple[int, ...]) -> CommandTargdef stamp_target(ref: PullRequestRef, team_ids: tuple[int, ...]) -> CommandTarget | Answer:"""The projects where Stamphog reviews the repository, and their environments."""- # Stamphog keeps its repositories on the parent project.- project_ids = _project_ids(team_ids)- reviewing = set(stamphog_requests.reviewing_team_ids(ref.repository, set(project_ids.values())))+ reviewing = stamphog_requests.reviewing_team_ids(ref.repository, team_ids)if not reviewing:return Answer(outcome="refused", message="Stamphog is not set up for this repository.")return CommandTarget(- team_ids=tuple(team_id for team_id in team_ids if project_ids.get(team_id) in reviewing),+ team_ids=tuple(reviewing),not_member_message="You aren't a member of the PostHog project where Stamphog reviews this repository.",)@@ -74,7 +71,7 @@ def handle_stamp(context: CommandContext, args: StampArgs) -> CommandOutcome:member = context.members[0]try:result = stamphog_requests.request_review(- resolve_effective_team_id(member.team_id),+ member.team_id,user_id=member.user_id,repository=pull_request.repository,pr_number=pull_request.number,diff --git a/products/commands/backend/logic/identity.py b/products/commands/backend/logic/identity.pyindex 01fd84b0695c..31de7f97203d 100644--- a/products/commands/backend/logic/identity.py+++ b/products/commands/backend/logic/identity.py@@ -29,7 +29,7 @@ logger = structlog.get_logger(__name__)@frozenclass Requester:# The candidate projects, each with a linked account that is a member of it. In the order of the- # candidates, and within a project the most recently linked account first. Empty when no linked+ # candidates, and within a project the channel's first choice first. Empty when no linked# account belongs to any of them.members: tuple[ProjectMember, ...]@@ -72,8 +72,8 @@ def _project_members(users: list[User], team_ids: Sequence[int]) -> tuple[Projecteams_by_id = Team.objects.select_related("organization", "parent_team__organization").in_bulk(team_ids)teams = [teams_by_id[team_id] for team_id in team_ids if team_id in teams_by_id]member_team_ids = {user.id: _member_team_ids(user, teams) for user in users}- # When two linked accounts are members of the same project, the most recently linked one acts- # there, as in the Slack app: the person linked it last, so it is the one they use.+ # When two linked accounts are members of the same project, the one the channel lists first acts+ # there: on GitHub the most recently linked one, because the person linked it last.return tuple(ProjectMember(team_id=team.id, user_id=user.id)for team in teams@@ -83,7 +83,7 @@ def _project_members(users: list[User], team_ids: Sequence[int]) -> tuple[Projecdef resolve_requester(users: list[User], team_ids: Sequence[int]) -> Requester | UnresolvedRequester:- """The members among ``users`` (most recently linked first) of the candidate ``team_ids``."""+ """The members among ``users`` (the channel's first choice first) of the candidate ``team_ids``."""if not users:return UnresolvedRequester(reason="unlinked")# The same rule that refuses an account's logins and API keys refuses its commands. Anotherdiff --git a/products/commands/backend/logic/schema.py b/products/commands/backend/logic/schema.pyindex 08855ad73193..a78df02430b4 100644--- a/products/commands/backend/logic/schema.py+++ b/products/commands/backend/logic/schema.py@@ -10,6 +10,8 @@ Grammar:- Option scanning stops at the first token that does not start with `--`. The rest of the commentline is the command's one free-text field, kept as typed.- A lone `--` also stops option scanning, so free text can start with `--`.+- An option typed with one dash, such as `—deep`, counts as `--deep`: text editors such as macOS+ autocorrect turn a typed `--` into a dash.- Comment text is never split with `shlex`, because apostrophes and unbalanced quotes are normalin prose.@@ -20,6 +22,7 @@ outside Django.import reimport typesimport dataclasses+import unicodedatafrom collections.abc import Mappingfrom typing import Any, Literal, Union, get_args, get_origin, get_type_hints@@ -31,6 +34,7 @@ SCHEMA_VERSION = 1MENTION = "@posthog"# A line with the bare mention asks for help, so the grammar owns this verb.HELP_VERB = "help"+MAX_ARGUMENT_LENGTH = 200AccessLevel = Literal["viewer", "editor", "manager"]OptionKind = Literal["flag", "value"]@@ -42,6 +46,7 @@ _NAME_RE = re.compile(r"[a-z][a-z0-9_]*")_VERB_RE = re.compile(r"[a-z][a-z0-9-]*")_TOKEN_RE = re.compile(r"\S+")_END_OF_OPTIONS = "--"+_DASHED_OPTION_RE = re.compile(r"^[\u2013\u2014](?=[a-z])")def flag(help: str) -> Any:@@ -59,6 +64,18 @@ def text(help: str, *, required: bool = False) -> Any:return dataclasses.field(default="", metadata={_ROLE: "text", _HELP: help, _REQUIRED: required})+def sanitize_argument(raw: str) -> str:+ """Make the free text after the verb safe to store, log and hand to a product.++ Drops control and format characters, which removes bidirectional overrides and zero-width+ characters that can make text read differently than it runs. Collapses whitespace and caps+ the length, so an argument stays one short line.+ """+ kept = "".join(char for char in raw if unicodedata.category(char)[0] != "C" or char in " \t\r\n")+ collapsed = " ".join(kept.split())+ return collapsed[:MAX_ARGUMENT_LENGTH]++@frozenclass StampArgs:pass@@ -310,7 +327,7 @@ def parse_arguments[A](declaration: CommandDeclaration[A], raw: str) -> A | Arguindex = 0while index < len(tokens):token = tokens[index]- word = token.group()+ word = _DASHED_OPTION_RE.sub(_END_OF_OPTIONS, token.group())if word == _END_OF_OPTIONS:remainder = raw[token.end() :].strip()breakdiff --git a/products/commands/backend/tasks/tasks.py b/products/commands/backend/tasks/tasks.pyindex 3b8cb022264f..755b0b61c556 100644--- a/products/commands/backend/tasks/tasks.py+++ b/products/commands/backend/tasks/tasks.py@@ -4,6 +4,7 @@ from celery import shared_taskfrom ..channels.github.comments import dispatch_comment_commandfrom ..channels.github.intake import CommentCommandRequest+from ..channels.slack.mentions import SlackCommandRequest, dispatch_slack_command# No retries: a command that fails tells the commenter so in a reply, and a silent second attempt@@ -36,3 +37,41 @@ def run_comment_command(ambiguous=ambiguous,))+++@shared_task(ignore_result=True, max_retries=0)+def run_slack_command(+ *,+ installation_id: str,+ team_ids: list[int],+ repository: str,+ pr_number: int,+ verb: str,+ argument: str,+ slack_team_id: str,+ slack_user_id: str,+ channel: str,+ thread_ts: str,+ message_ts: str,+ integration_id: int,+ integration_team_id: int,+ user_ids: list[int],+) -> None:+ dispatch_slack_command(+ SlackCommandRequest(+ installation_id=installation_id,+ team_ids=tuple(team_ids),+ repository=repository,+ pr_number=pr_number,+ verb=verb,+ argument=argument,+ slack_team_id=slack_team_id,+ slack_user_id=slack_user_id,+ channel=channel,+ thread_ts=thread_ts,+ message_ts=message_ts,+ integration_id=integration_id,+ integration_team_id=integration_team_id,+ user_ids=tuple(user_ids),+ )+ )diff --git a/products/commands/backend/tests/test_dispatch.py b/products/commands/backend/tests/test_dispatch.pyindex d4487e3deb4e..72684bf812e3 100644--- a/products/commands/backend/tests/test_dispatch.py+++ b/products/commands/backend/tests/test_dispatch.py@@ -28,10 +28,14 @@ from posthog.token_bucket import BucketDecisionfrom products.access_control.backend.facade.testing import create_access_controlfrom products.commands.backend.channels.github.comments import GitHubCommentChannel, dispatch_comment_commandfrom products.commands.backend.channels.github.intake import CommentCommandRequest+from products.commands.backend.channels.slack.mentions import read_slack_command+from products.commands.backend.facade.api import accept_slack_mention+from products.commands.backend.facade.contracts import SlackMentionfrom products.commands.backend.logic.commands import CommandContext, CommandRequest, ProjectMember, PullRequestFactsfrom products.commands.backend.logic.github import InstallationGitHub, Reaction, UnsupportedPullRequestfrom products.commands.backend.logic.handlers import handle_loop, handle_qafrom products.commands.backend.logic.schema import LoopArgs, QaArgs+from products.commands.backend.tasks.tasks import run_slack_commandfrom products.review_hog.backend.facade.reviews import (RUN_MODE_FLASH,RUN_MODE_REVIEW,@@ -54,6 +58,9 @@ OWNING_TEAM_ID = "products.commands.backend.logic.handlers.review_hog_github.ownCLAIM_CACHE = "products.commands.backend.logic.admission.cache"CONSUME_BUDGET = "products.commands.backend.logic.admission.consume"RUN_COMMENT_COMMAND = "products.commands.backend.tasks.tasks.run_comment_command.delay"+RUN_SLACK_COMMAND = "products.commands.backend.tasks.tasks.run_slack_command.delay"+SLACK_INSTALLATION_GITHUB = "products.commands.backend.channels.slack.mentions.InstallationGitHub.for_installation"+SLACK_POST = "products.commands.backend.channels.slack.mentions.post_message"# Each test gets its own commenter, so the per-commenter rate limit in Redis never carries over._github_ids = count(10_000)@@ -479,6 +486,90 @@ class TestDispatchCommentCommand(BaseTest):assert outcome == "no_project"request_review.assert_not_called()+ def _connect_github_account(self, account: str) -> None:+ Integration.objects.filter(team=self.team, kind="github", integration_id=INSTALLATION_ID).update(+ config={"account": {"name": account}}+ )++ def _slack_mention(self, text: str, organization_ids: tuple[str, ...], integration_id: int = 0) -> SlackMention:+ return SlackMention(+ text=f"{text} https://github.com/{REPOSITORY}/pull/7",+ slack_team_id="T1",+ slack_user_id="U1",+ channel="C1",+ thread_ts="100.1",+ message_ts=str(self.github_id),+ integration_id=integration_id,+ integration_team_id=self.team.id,+ user_ids=(self.user.id,),+ organization_ids=organization_ids,+ )++ @parameterized.expand(+ [+ ("exact_command", "review --deep", True, True, "review"),+ ("free_text", "can you review this deeply", True, True, None),+ ("mistyped_option", "review --depp", True, True, None),+ ("outside_the_rollout", "review", True, False, None),+ ("organization_without_this_workspace", "review", False, True, None),+ ]+ )+ def test_a_slack_message_skips_the_agent_only_for_an_exact_rolled_out_command(+ self, _name: str, command_text: str, connected: bool, rolled_out: bool, expected_verb: str | None+ ) -> None:+ self._connect_github_account("acme")+ self.flag.return_value = rolled_out+ organization_ids = (+ (str(self.organization.id),) if connected else (str(Organization.objects.create(name="Else").id),)+ )++ command = read_slack_command(self._slack_mention(command_text, organization_ids))++ assert (command.verb if command else None) == expected_verb+ if command is not None:+ assert (command.installation_id, command.team_ids) == (INSTALLATION_ID, (self.team.id,))+ # Inside the Slack webhook, a flag that needs a remote call reads as off.+ assert all(call.kwargs["only_evaluate_locally"] for call in self.flag.call_args_list)++ @parameterized.expand(+ [+ ("accepted", True, True, "PostHog Review is reviewing this pull request."),+ # The message already skipped the agent, so a refusal must still answer.+ ("over_the_rate_limit", False, True, "You've sent a lot of commands in a short time."),+ ("github_unreachable", True, False, "I couldn't reach GitHub for this repository."),+ ]+ )+ def test_a_slack_command_answers_in_the_thread_it_came_from(+ self, _name: str, within_budget: bool, github_reachable: bool, expected_answer: str+ ) -> None:+ self._connect_github_account("acme")+ slack = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T1", config={}, sensitive_config={"access_token": "xoxb-x"}+ )+ mention = self._slack_mention("review", (str(self.organization.id),), integration_id=slack.id)+ started = PRReviewRequestOutcome(status=PRReviewRequestStatus.STARTED, workflow_id="wf-1")+ budget = BucketDecision(allowed=within_budget, remaining=0, limit=5, retry_after=60, reset=600)++ with (+ # The task runs in place, so the test covers the facade, the task and the channel together.+ patch(RUN_SLACK_COMMAND, side_effect=lambda **kwargs: run_slack_command(**kwargs)),+ patch(SLACK_INSTALLATION_GITHUB, return_value=FakeGitHub() if github_reachable else None),+ patch(SLACK_POST) as post,+ patch(CONSUME_BUDGET, return_value=budget),+ patch(OWNING_TEAM_ID, return_value=self.team.id),+ patch(REQUEST_PR_REVIEW, return_value=started) as request_pr_review,+ ):+ verb = accept_slack_mention(mention)++ assert verb == "review"+ assert post.call_args.kwargs["thread_ts"] == "100.1"+ answer = post.call_args.args[3]+ assert answer.startswith(expected_answer)+ if within_budget and github_reachable:+ assert request_pr_review.call_args.kwargs["requester_id"] == self.user.id+ else:+ request_pr_review.assert_not_called()+@patch("posthog.ingress.github.provider.get_instance_setting", return_value="test-webhook-secret")def test_a_signed_comment_with_a_command_is_queued(self, _secret: MagicMock) -> None:reset_consumer_registry()diff --git a/products/commands/backend/tests/test_intake.py b/products/commands/backend/tests/test_intake.pyindex dbd5adbb35e6..505c35ef03e6 100644--- a/products/commands/backend/tests/test_intake.py+++ b/products/commands/backend/tests/test_intake.py@@ -5,12 +5,12 @@ import pytestfrom products.commands.backend.channels.github.intake import CommentCommandRequest, Dropped, read_comment_commandfrom products.commands.backend.channels.github.parsing import (- MAX_ARGUMENT_LENGTH,MAX_BODY_LENGTH,AmbiguousCommand,ParsedCommand,parse_command,)+from products.commands.backend.logic.schema import MAX_ARGUMENT_LENGTHdef _payload(body: str = "@posthog stamp", **overrides: Any) -> dict[str, Any]:diff --git a/products/commands/backend/tests/test_schema.py b/products/commands/backend/tests/test_schema.pyindex f0cbc53ed2bf..cffa91ba73da 100644--- a/products/commands/backend/tests/test_schema.py+++ b/products/commands/backend/tests/test_schema.py@@ -39,6 +39,7 @@ _MODE = CommandDeclaration(verb="mode", summary="Test command.", args=_ModeArgs,[(REVIEW, "", ReviewArgs(deep=False)),(REVIEW, "--deep", ReviewArgs(deep=True)),+ (REVIEW, "\u2014deep", ReviewArgs(deep=True)),(STAMP, "", StampArgs()),# Prose keeps its apostrophes and words, because nothing splits it like a shell.(diff --git a/products/commands/backend/tests/test_slack_parsing.py b/products/commands/backend/tests/test_slack_parsing.pynew file mode 100644index 000000000000..7400b11b31a6--- /dev/null+++ b/products/commands/backend/tests/test_slack_parsing.py@@ -0,0 +1,37 @@+from parameterized import parameterized++from products.commands.backend.channels.slack.parsing import SlackPullRequestCommand, parse_slack_command++URL = "https://github.com/acme/widgets/pull/7"+++ [+ ("options_then_url", f"review --deep {URL}", "review", "--deep"),+ ("url_with_a_path", f"stamp {URL}/files", "stamp", ""),+ ("focus_text_after_url", f"qa {URL} the signup form", "qa", "the signup form"),+ ("options_on_two_lines", f"review --deep\n--no-resolve {URL}", "review", "--deep --no-resolve"),+ ("dashed_option", f"review \u2014deep {URL}", "review", "\u2014deep"),+ ("url_first", f"{URL} review --deep", "review", "--deep"),+ ("option_after_url", f"review {URL} --deep", "review", "--deep"),+ ]+)+def test_reads_a_pull_request_command(_name: str, text: str, verb: str, argument: str) -> None:+ assert parse_slack_command(text) == SlackPullRequestCommand(+ repository="acme/widgets", pr_number=7, verb=verb, argument=argument+ )+++ [+ ("text_before_url", f"review this {URL}"),+ ("url_alone", URL),+ ("no_url", "review --deep"),+ ("issue_url", "review https://github.com/acme/widgets/issues/7"),+ ("other_host", "review https://gitlab.com/acme/widgets/pull/7"),+ ("prose_first", f"please look at {URL}"),+ ("someone_else_mentioned_first", f"<@UALICE> qa {URL} the signup form"),+ ]+)+def test_anything_else_is_not_a_command(_name: str, text: str) -> None:+ assert parse_slack_command(text) is Nonediff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex f70a64890731..6a582cdf1ffb 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -35,6 +35,7 @@ from posthog.models.integration import (validate_slack_request,)from posthog.models.organization import OrganizationMembership+from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.temporal.ai.slack_app import (@@ -55,6 +56,7 @@ from posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import get_instance_region+from products.commands.backend.facade import api as commands_apifrom products.slack_app.backend import inbox_channelfrom products.slack_app.backend.analytics import capture_slack_event, slack_session_idfrom products.slack_app.backend.discussion_replies import try_ingest_discussion_reply@@ -107,9 +109,11 @@ from products.slack_app.backend.services.slack_messages import (TURN_FEEDBACK_ACTION_ID,SlackThreadMessage,app_home_url,+ decode_slack_entities,parse_slack_file_refs,post_slack_ephemeral,post_slack_thread_reply,+ unwrap_slack_links,)from products.slack_app.backend.services.slack_scopes import REQUIRED_SLACK_SCOPESfrom products.slack_app.backend.services.slack_settings import (@@ -127,6 +131,7 @@ from products.slack_app.backend.services.slack_user_info import (from products.slack_app.backend.services.slack_user_oauth import (build_invite_url,find_linked_posthog_user,+ linked_posthog_user_ids,post_link_invite_message,)from products.slack_app.backend.services.slack_welcome_messages import (@@ -2875,6 +2880,16 @@ def route_posthog_code_event_to_relevant_region(# Recognised but not run: unrecognised, ``@PostHog project 452770`` becomes a task about# its own syntax. Only a message addressed to the app can be a command.if untagged_followup_mapping is None:+ command_probe = resolution.resolved_or_first()+ if command_probe is not None and _hand_off_command(+ event,+ workspace_result.candidates,+ slack_team_id,+ probe=command_probe,+ posthog_user=posthog_user,+ is_ext_shared_channel=is_ext_shared_channel,+ ):+ return ROUTE_HANDLED_LOCALLYmention_command = parse_rules_command(event.get("text", ""))if mention_command is not None:# The redirect reply is static, but its analytics event attributes to whichever@@ -3169,6 +3184,94 @@ def _redirect_mention_command(return ROUTE_HANDLED_LOCALLY+def _connected_organization_ids(candidates: list[Integration]) -> tuple[str, ...]:+ team_ids = {candidate.team_id for candidate in candidates}+ organization_ids = Team.objects.filter(id__in=team_ids).values_list("organization_id", flat=True).distinct()+ return tuple(str(organization_id) for organization_id in organization_ids)+++def _hand_off_command(+ event: dict[str, Any],+ candidates: list[Integration],+ slack_team_id: str,+ *,+ probe: Integration,+ posthog_user: User,+ is_ext_shared_channel: bool,+) -> bool:+ """Hand a mention such as ``@PostHog review --deep <PR URL>`` to the commands product.++ Commands decides whether it is a command, runs it without the agent and answers in the thread.+ False leaves the mention to the agent: free text, a mistyped command, or an organization outside+ the commands rollout.+ """+ text = event.get("text")+ channel = event.get("channel")+ slack_user_id = event.get("user")+ message_ts = event.get("ts")+ if event.get("type") != "app_mention" or not (+ isinstance(text, str)+ and isinstance(channel, str)+ and isinstance(slack_user_id, str)+ and isinstance(message_ts, str)+ ):+ return False+ # Nearly every mention is free text for the agent, and this keeps their path free of queries.+ if not commands_api.may_hold_command(text):+ return False+ # The answer is visible in the thread, which would announce PostHog in a shared channel that has+ # not approved it yet. The agent path has the approval gate for that.+ if is_ext_shared_channel and not _channel_is_approved(slack_team_id, channel):+ return False+ # A command is addressed to the app: a message that opens with someone else's mention is not.+ bot_user_id = get_cached_bot_user_id(SlackIntegration(probe), probe)+ bot_mention = f"<@{bot_user_id}>"+ text = text.strip()+ if bot_user_id is None or not text.startswith(bot_mention):+ return False+ thread_ts_value = event.get("thread_ts")+ thread_ts = thread_ts_value if isinstance(thread_ts_value, str) else message_ts+ # A broken command lookup must not cost the person their agent run. That includes the linked+ # accounts, whose lookup the user resolver also survives by falling back to the email match.+ try:+ # The account the resolver picked comes first. Every other linked account joins, so the+ # project the command runs in picks the account rather than the order of linking.+ user_ids = (+ posthog_user.id,+ *linked_posthog_user_ids(slack_user_id=slack_user_id, slack_team_id=slack_team_id),+ )+ mention = commands_api.SlackMention(+ text=decode_slack_entities(unwrap_slack_links(text.removeprefix(bot_mention).strip())),+ slack_team_id=slack_team_id,+ slack_user_id=slack_user_id,+ channel=channel,+ thread_ts=thread_ts,+ message_ts=message_ts,+ integration_id=probe.id,+ integration_team_id=probe.team_id,+ user_ids=tuple(dict.fromkeys(user_ids)),+ organization_ids=_connected_organization_ids(candidates),+ )+ verb = commands_api.accept_slack_mention(mention)+ except Exception:+ logger.warning("slack_app_command_failed", slack_team_id=slack_team_id, exc_info=True)+ return False+ if verb is None:+ return False+ # The command is the request a bare mention in this thread waited for, so a later "thanks"+ # must not start an agent run.+ bare_mention.clear_awaited_request(slack_team_id, channel, thread_ts)+ capture_slack_event(+ probe,+ "slack app command used",+ slack_user_id=slack_user_id,+ posthog_user=posthog_user,+ action=f"command_{verb}",+ source="mention",+ )+ return True++def _start_command_workflow(event: dict,integrations: list[Integration],diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pyindex 616a01c56941..27a79547b7ac 100644--- a/products/slack_app/backend/services/slack_messages.py+++ b/products/slack_app/backend/services/slack_messages.py@@ -136,6 +136,18 @@ def decode_slack_entities(text: str) -> str:return text.replace(">", ">").replace("&", "&")+_RE_SLACK_LINK = re.compile(r"<(https?://[^|>\s]+)(?:\|[^>]*)?>")+++def unwrap_slack_links(text: str) -> str:+ """Rewrite Slack's `<url>` and `<url|label>` link tokens to the bare URL, for a reader that wants plain text.++ Run it on wire text, before ``decode_slack_entities``: only there are `<` and `>` Slack's own+ delimiters and never text the user typed.+ """+ return _RE_SLACK_LINK.sub(r"\1", text)++def _resolve_and_decode(slack: SlackIntegration,integration: Integration,diff --git a/products/slack_app/backend/services/slack_user_oauth.py b/products/slack_app/backend/services/slack_user_oauth.pyindex bb7c6cdd32e6..5189e958f9a1 100644--- a/products/slack_app/backend/services/slack_user_oauth.py+++ b/products/slack_app/backend/services/slack_user_oauth.py@@ -27,6 +27,7 @@ from uuid import UUIDfrom django.conf import settingsfrom django.core import signing+from django.db.models import QuerySetimport structlogfrom pydantic import BaseModel, ValidationError@@ -41,6 +42,27 @@ from posthog.models.user_integration import UserIntegrationlogger = structlog.get_logger(__name__)+def _slack_links(*, slack_user_id: str, slack_team_id: str) -> QuerySet[UserIntegration]:+ """Links of active PostHog users to this Slack identity, most recently linked first."""+ return UserIntegration.objects.filter(+ kind=UserIntegration.IntegrationKind.SLACK,+ integration_id=slack_user_id,+ config__slack_team_id=slack_team_id,+ user__is_active=True,+ ).order_by("-created_at")+++def linked_posthog_user_ids(*, slack_user_id: str, slack_team_id: str) -> list[int]:+ """Active PostHog users linked to this Slack identity, most recently linked first.++ Unlike ``find_linked_posthog_user`` this keeps every link, for a caller that picks the account+ by project, such as a pull request command.+ """+ return list(+ _slack_links(slack_user_id=slack_user_id, slack_team_id=slack_team_id).values_list("user_id", flat=True)+ )++def find_linked_posthog_user(*,slack_user_id: str,@@ -73,16 +95,7 @@ def find_linked_posthog_user(# a different database (which `User` does in PostHog's deployment), so a# straight-line equivalent keeps the query portable across routers.try:- links = list(- UserIntegration.objects.filter(- kind=UserIntegration.IntegrationKind.SLACK,- integration_id=slack_user_id,- config__slack_team_id=slack_team_id,- user__is_active=True,- )- .select_related("user")- .order_by("-created_at")- )+ links = list(_slack_links(slack_user_id=slack_user_id, slack_team_id=slack_team_id).select_related("user"))if not links:return None# Org-scope filter as a set lookup so we keep the per-row iterationdiff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.pyindex 74950fa2a136..22764efa51c3 100644--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py@@ -5,6 +5,7 @@ from typing import Any, castfrom unittest.mock import MagicMock, patchfrom django.core.cache import cache+from django.db import OperationalErrorfrom django.test import SimpleTestCase, TestCase, override_settingsfrom django.test.client import RequestFactory@@ -815,6 +816,79 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):mock_asyncio_run.assert_not_called()assert expected_pointer in mock_ephemeral.call_args.args[4]+ @parameterized.expand(+ [+ (+ "pull_request_command",+ "<@UBOT123> review --deep <https://github.com/acme/widgets/pull/7|acme/widgets#7>",+ "review",+ True,+ ),+ ("anything_else", "<@UBOT123> review --deep <https://github.com/acme/widgets/pull/7>", None, True),+ ("no_subject", "<@UBOT123> can you review this deeply", "review", False),+ ("addressed_to_someone_else", "<@UALICE> review <https://github.com/acme/widgets/pull/7>", "review", False),+ ]+ )+ @patch("products.slack_app.backend.api.bare_mention.clear_awaited_request")+ @patch("products.slack_app.backend.api.get_cached_bot_user_id", return_value="UBOT123")+ @patch("products.slack_app.backend.api.commands_api.accept_slack_mention")+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def test_mention_with_a_pull_request_command_runs_it_without_the_agent(+ self,+ _name,+ text,+ accepted_verb,+ reaches_commands,+ mock_sync_connect,+ mock_asyncio_run,+ mock_accept,+ _bot,+ mock_clear_awaited,+ ):+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ mock_accept.return_value = accepted_verb+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")++ result = route_posthog_code_event_to_relevant_region(request, {**self.event, "text": text}, "T12345")++ if reaches_commands:+ mention = mock_accept.call_args.args[0]+ assert mention.text == "review --deep https://github.com/acme/widgets/pull/7"+ assert mention.organization_ids == (str(self.organization.id),)+ assert mention.user_ids[0] == self.user.id+ assert (mention.channel, mention.thread_ts, mention.message_ts) == ("C001", "1234.5678", "1234.5678")+ else:+ mock_accept.assert_not_called()+ if accepted_verb and reaches_commands:+ assert result == ROUTE_HANDLED_LOCALLY+ mock_sync_connect.assert_not_called()+ # A bare mention earlier in the thread waited for this request, so a later reply is not one.+ mock_clear_awaited.assert_called_once_with("T12345", "C001", "1234.5678")+ else:+ mock_sync_connect.return_value.start_workflow.assert_called_once()++ @patch("products.slack_app.backend.api.linked_posthog_user_ids", side_effect=OperationalError("statement timeout"))+ @patch("products.slack_app.backend.api.get_cached_bot_user_id", return_value="UBOT123")+ @patch("products.slack_app.backend.api.commands_api.accept_slack_mention")+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def test_a_failed_linked_account_lookup_leaves_the_mention_to_the_agent(+ self, mock_sync_connect, _asyncio_run, mock_accept, _bot, _linked+ ):+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region++ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ text = "<@UBOT123> review <https://github.com/acme/widgets/pull/7>"++ route_posthog_code_event_to_relevant_region(request, {**self.event, "text": text}, "T12345")++ mock_accept.assert_not_called()+ mock_sync_connect.return_value.start_workflow.assert_called_once()+@parameterized.expand([("top_level", {}, None),diff --git a/products/stamphog/backend/facade/review_requests.py b/products/stamphog/backend/facade/review_requests.pyindex 335717c46cb8..3dd45e6ba4f1 100644--- a/products/stamphog/backend/facade/review_requests.py+++ b/products/stamphog/backend/facade/review_requests.py@@ -7,6 +7,8 @@ serializer imports on every request.from collections.abc import Collection+from posthog.models.scoping.manager import resolve_effective_team_id+from products.stamphog.backend.facade import contractsfrom products.stamphog.backend.facade.api import _review_run_to_dtofrom products.stamphog.backend.tasks.tasks import (@@ -18,7 +20,8 @@ __all__ = ["request_review", "reviewing_team_ids"]def reviewing_team_ids(repository: str, team_ids: Collection[int]) -> list[int]:- """The projects among ``team_ids`` where stamphog reviews ``repository``, by the rule ``request_review`` applies."""+ """The teams among ``team_ids``, environments included, where stamphog reviews ``repository``, by+ the rule ``request_review`` applies."""return _reviewing_team_ids(repository, team_ids)@@ -27,8 +30,8 @@ def request_review() -> contracts.ReviewRequestResultDTO:"""Queue a stamphog review of a PR, or return the run already covering its current head.- Raises ``contracts.ReviewRequestRefusedError`` when the request is refused. The review itself+ ``team_id`` may be an environment: the review runs in its project. Raises ``contracts.ReviewRequestRefusedError`` when the request is refused. The review itselfruns asynchronously, and whether it approves is stamphog's decision."""- queued = request_manual_review(team_id, user_id, repository, pr_number)+ queued = request_manual_review(resolve_effective_team_id(team_id), user_id, repository, pr_number)return contracts.ReviewRequestResultDTO(run=_review_run_to_dto(queued.run), created=queued.created)diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.pyindex 4fcdf49638d0..1c92b4055b87 100644--- a/products/stamphog/backend/tasks/tasks.py+++ b/products/stamphog/backend/tasks/tasks.py@@ -24,6 +24,7 @@ from celery import Task, shared_taskfrom posthog.dataclasses import frozenfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.instance_setting import get_instance_setting+from posthog.models.team import Teamfrom products.stamphog.backend.activity_logging import DISABLED_FIELDS, log_repo_configs_disabled_by_webhookfrom products.stamphog.backend.facade.contracts import ReviewRequestRefusedError, StamphogGitHubError@@ -1390,11 +1391,15 @@ def _reviewable_repo_config(team_id: int, repository: str) -> StamphogRepoConfigdef reviewing_team_ids(repository: str, team_ids: Collection[int]) -> list[int]:- """The projects among ``team_ids`` where a manual review of ``repository`` would find its config."""- # One query for every candidate project, so the caller's choice of project costs no loop.- configs = StamphogRepoConfig.objects.unscoped().filter(team_id__in=team_ids)+ """The teams among ``team_ids``, environments included, where a manual review of ``repository``+ would find its config."""+ # Configs live on the parent project. One query for the projects and one for every candidate+ # config, so the caller's choice of project costs no loop.+ rows = Team.objects.filter(id__in=team_ids).values_list("id", "parent_team_id")+ project_ids = {team_id: parent_team_id or team_id for team_id, parent_team_id in rows}+ configs = StamphogRepoConfig.objects.unscoped().filter(team_id__in=set(project_ids.values()))reviewing = set(_reviewable(configs, repository).values_list("team_id", flat=True))- return [team_id for team_id in team_ids if team_id in reviewing]+ return [team_id for team_id in team_ids if project_ids.get(team_id) in reviewing]def _reviewed_base_ref(run: ReviewRun) -> str:diff --git a/products/stamphog/backend/tests/test_tasks.py b/products/stamphog/backend/tests/test_tasks.pyindex b2913bc5a031..0dfa43bff1f3 100644--- a/products/stamphog/backend/tests/test_tasks.py+++ b/products/stamphog/backend/tests/test_tasks.py@@ -785,6 +785,7 @@ def _make_second_team(organization) -> Team:)def test_reviewing_team_ids_applies_the_manual_request_rule(team, enabled, connected_by_user_id, expected_reviewing):other_team = _make_second_team(team.organization)+ environment = Team.objects.create(organization=team.organization, parent_team=team, name="env")with team_scope(team.id):StamphogRepoConfig.objects.create(team_id=team.id,@@ -794,7 +795,10 @@ def test_reviewing_team_ids_applies_the_manual_request_rule(team, enabled, conneconnected_by_user_id=connected_by_user_id,)- assert reviewing_team_ids(REPO.upper(), [team.id, other_team.id]) == ([team.id] if expected_reviewing else [])+ # An environment reviews where its project does.+ assert reviewing_team_ids(REPO.upper(), [environment.id, team.id, other_team.id]) == (+ [environment.id, team.id] if expected_reviewing else []+ )@pytest.mark.django_db(databases=PRODUCT_DATABASES)diff --git a/tach.toml b/tach.tomlindex b01c05ec7d8c..87c3deb3f227 100644--- a/tach.toml+++ b/tach.toml@@ -952,6 +952,8 @@ depends_on = ["products.tasks", "products.access_control",# Slack triggers emit internal events through products.cdp.backend.internal_events."products.cdp",+ # Mentions that name a pull request and a command run through the commands facade.+ "products.commands",]layer = "modules"