Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(commands): let commands act on more than pull requests (#117539)

Julian Bezb44b41a7574b
diff --git a/products/commands/README.md b/products/commands/README.md
index 336f850a4a7b..55b072418e38 100644
--- a/products/commands/README.md
+++ b/products/commands/README.md
@@ -14,6 +14,10 @@ People with write access to a repository can ask PostHog to do something on a pu
Each command dispatches into the product that owns the work.
This product owns the parsing, the checks and the replies, and owns no work of its own.
+A command comes in through a channel and acts on a subject.
+The channels are GitHub pull request comments and Slack mentions.
+Pull requests are the only kind of subject so far, and the core takes more kinds without changes to the channels.
+
[`COMMANDS.generated.md`](COMMANDS.generated.md) lists every command, and [`commands.generated.json`](commands.generated.json) is the same reference for tools.
Both are generated from `backend/logic/schema.py`, like the `@posthog help` reply.
@@ -52,16 +56,37 @@ The same commands run from a Slack message that mentions the PostHog app and nam
- 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.
+## Subjects
+
+The subject is the thing a command acts on, such as a pull request.
+A channel names it with a reference: a comment names the pull request it sits on, and a Slack message names one by its URL.
+`logic/subjects.py` owns everything that depends on the kind of subject:
+
+- The candidate projects a command may run in, before the rollout. For a pull request, the projects whose GitHub integration uses the installation.
+- How to reach the subject, such as a GitHub client for a pull request.
+- The facts a handler gets, and the refusals before it runs, such as a closed pull request or a fork.
+
+The dispatcher, the identity step and the access step only use the subject through that module.
+Each command declares the kinds it accepts in `subject_kinds`, and dispatch answers when a request names another kind.
+
+To add a kind of subject:
+
+1. Add its reference and facts types to `logic/commands.py`.
+2. Add a class that follows `Subject`, and a case in each function, in `logic/subjects.py`.
+3. Teach the channels that can name it to read it, for example a URL pattern in `channels/slack/parsing.py`.
+4. Add the kind to `subject_kinds` of the commands that accept it.
+
## Adding a command
Declare the command in `logic/schema.py`: an args dataclass built with `flag()`, `option()` and `text()`, and a `CommandDeclaration` in `COMMAND_DECLARATIONS`.
+Set `subject_kinds` to the kinds of subject the command acts on. The default is pull requests only.
Set `access` when the target product has a resource in PostHog access control, at the level its own API asks for the same action.
Leave `allows_forks` off unless the command reads nothing from the pull request head.
Write a handler in `logic/handlers.py` that takes the args dataclass and calls the target product's facade, then bind the two in `logic/registry.py`.
Run `hogli build:projections` and commit the regenerated command reference.
-A product that wants a command does not need Loops, and does not need to know about GitHub comments.
-It needs a facade function that takes a project, a user and the pull request identifiers.
+A product that wants a command does not need Loops, and does not need to know about GitHub comments or Slack.
+It needs a facade function that takes a project, a user and the subject's identifiers.
## Trust model
diff --git a/products/commands/backend/channels/github/comments.py b/products/commands/backend/channels/github/comments.py
index 82e85c19bd93..9ff03bc68c33 100644
--- a/products/commands/backend/channels/github/comments.py
+++ b/products/commands/backend/channels/github/comments.py
@@ -29,9 +29,10 @@ from posthog.models.user import User
from posthog.models.user_integration import UserIntegration
from ...logic.admission import claim, release, rolled_out_team_ids, within_rate_limit
-from ...logic.commands import CommandRequest, DispatchOutcome, PullRequestRef
+from ...logic.commands import Answer, CommandRequest, DispatchOutcome, PullRequestRef
from ...logic.dispatcher import Admission, CommandDispatcher
from ...logic.github import CommandGitHub, GitHubCallFailed, InstallationGitHub, Reaction
+from ...logic.subjects import open_subject
from .intake import CommentCommandRequest
logger = structlog.get_logger(__name__)
@@ -86,7 +87,7 @@ class GitHubCommentChannel:
comment = self._comment
# Before any GitHub call: the App is installed on repositories of organizations that never
# turned commands on, and the bot must stay silent there.
- team_ids = rolled_out_team_ids(ROLLOUT_FLAG, comment.installation_id)
+ team_ids = rolled_out_team_ids(ROLLOUT_FLAG, self.request.subject)
if not team_ids:
return "not_rolled_out"
claim_refusal = claim(_claim_key(comment.comment_id))
@@ -110,7 +111,10 @@ class GitHubCommentChannel:
if permission not in _WRITE_PERMISSIONS:
return "no_write_access"
self._react("eyes")
- return Admission(team_ids=team_ids, github=self._github)
+ subject = open_subject(self.request.subject, team_ids, github=self._github)
+ if isinstance(subject, Answer):
+ return subject.outcome
+ return Admission(team_ids=team_ids, subject=subject)
def linked_users(self) -> list[User]:
return _linked_users(self._comment.commenter_github_id)
diff --git a/products/commands/backend/channels/slack/mentions.py b/products/commands/backend/channels/slack/mentions.py
index 92340ab357f7..cf824ea4d702 100644
--- a/products/commands/backend/channels/slack/mentions.py
+++ b/products/commands/backend/channels/slack/mentions.py
@@ -1,4 +1,4 @@
-"""Commands from Slack mentions: which installation, who may ask, and how the answer goes back.
+"""Commands from Slack mentions: what they act on, 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
@@ -7,9 +7,11 @@ gives people the agent back. The rollout and the projects a command may reach ar
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.
+The message names its subject by URL. For a pull request, the GitHub App installation on the
+repository owner tells which projects may act on it. 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
@@ -24,12 +26,13 @@ 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.commands import Answer, CommandRequest, DispatchOutcome, PullRequestRef, SubjectRef
from ...logic.dispatcher import Admission, CommandDispatcher
-from ...logic.github import CommandGitHub, InstallationGitHub
+from ...logic.github import CommandGitHub
from ...logic.registry import COMMANDS
from ...logic.schema import ArgumentError, resolve_verb
-from .parsing import parse_slack_command
+from ...logic.subjects import open_subject
+from .parsing import SubjectUrl, parse_slack_command
logger = structlog.get_logger(__name__)
@@ -40,12 +43,10 @@ ROLLOUT_FLAG = "slack-commands"
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.
+ subject: SubjectRef
+ # The subject's projects in the rollout and in the organizations that connected the Slack
+ # workspace, in the subject's order.
team_ids: tuple[int, ...]
- repository: str
- pr_number: int
verb: str
argument: str
slack_team_id: str
@@ -72,8 +73,16 @@ def _installation_id(owner: str, organization_ids: Collection[str]) -> str | Non
return integration.integration_id if integration is not None else None
+def _subject_ref(url: SubjectUrl, organization_ids: Collection[str]) -> SubjectRef | None:
+ """Where the subject lives for PostHog, or None when no connected organization reaches it."""
+ installation_id = _installation_id(url.repository.split("/", 1)[0], organization_ids)
+ if installation_id is None:
+ return None
+ return PullRequestRef(installation_id=installation_id, repository=url.repository, number=url.number)
+
+
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."""
+ """The command a Slack mention runs, or None to leave the mention to the agent."""
parsed = parse_slack_command(mention.text)
if parsed is None:
return None
@@ -83,18 +92,15 @@ def read_slack_command(mention: SlackMention) -> SlackCommandRequest | None:
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:
+ subject = _subject_ref(parsed.subject, mention.organization_ids)
+ if subject is None:
return None
- team_ids = rolled_out_team_ids(ROLLOUT_FLAG, installation_id, mention.organization_ids, only_evaluate_locally=True)
+ team_ids = rolled_out_team_ids(ROLLOUT_FLAG, subject, mention.organization_ids, only_evaluate_locally=True)
if not team_ids:
return None
return SlackCommandRequest(
- installation_id=installation_id,
+ subject=subject,
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,
@@ -119,9 +125,7 @@ class SlackMentionChannel:
self._command = command
self._github = github
self.request = CommandRequest(
- subject=PullRequestRef(
- installation_id=command.installation_id, repository=command.repository, number=command.pr_number
- ),
+ subject=command.subject,
verb=command.verb,
argument=command.argument,
ambiguous=False,
@@ -144,13 +148,10 @@ class SlackMentionChannel:
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)
+ subject = open_subject(command.subject, command.team_ids, github=self._github)
+ if isinstance(subject, Answer):
+ return subject
+ return Admission(team_ids=command.team_ids, subject=subject)
def linked_users(self) -> list[User]:
user_ids = self._command.user_ids
diff --git a/products/commands/backend/channels/slack/parsing.py b/products/commands/backend/channels/slack/parsing.py
index 005f3791da72..bccce3b60864 100644
--- a/products/commands/backend/channels/slack/parsing.py
+++ b/products/commands/backend/channels/slack/parsing.py
@@ -1,12 +1,14 @@
-"""Reads one pull request command out of a Slack message that mentions the PostHog app.
+"""Reads one 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``
+and the URL of its subject, in either order. For a pull request: ``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.
+to hold a URL, such as "review this <URL>", never runs a command.
+
+A new kind of subject adds its URL type and a pattern in ``_read_subject_url``.
"""
import re
@@ -25,9 +27,17 @@ _OPTION_PREFIXES = ("-", "–", "—")
@frozen
-class SlackPullRequestCommand:
+class PullRequestUrl:
repository: str
- pr_number: int
+ number: int
+
+
+SubjectUrl = PullRequestUrl
+
+
+@frozen
+class SlackCommand:
+ subject: SubjectUrl
verb: str
argument: str
@@ -37,12 +47,24 @@ def may_hold_command(text: str) -> bool:
return _PULL_REQUEST_URL_RE.search(text) is not None
-def parse_slack_command(text: str) -> SlackPullRequestCommand | None:
+def _read_subject_url(word: str) -> SubjectUrl | None:
+ match = _PULL_REQUEST_URL_RE.fullmatch(word)
+ if match is None:
+ return None
+ repository = match.group("repository")
+ number = int(match.group("number"))
+ if not REPOSITORY_NAME_RE.fullmatch(repository) or number < 1:
+ return None
+ return PullRequestUrl(repository=repository, number=number)
+
+
+def parse_slack_command(text: str) -> SlackCommand | 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:]
+ first_url = _read_subject_url(words[0])
+ if first_url is not None:
+ subject, verb, argument_words = first_url, words[1], words[2:]
else:
verb = words[0]
url_index = next(
@@ -50,18 +72,11 @@ def parse_slack_command(text: str) -> SlackPullRequestCommand | None:
)
if url_index is None:
return None
- url = words[url_index]
+ url = _read_subject_url(words[url_index])
+ if url is None:
+ return None
+ subject = url
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:
+ if not _VERB_RE.fullmatch(verb):
return None
- return SlackPullRequestCommand(
- repository=repository,
- pr_number=pr_number,
- verb=verb.lower(),
- argument=sanitize_argument(" ".join(argument_words)),
- )
+ return SlackCommand(subject=subject, verb=verb.lower(), argument=sanitize_argument(" ".join(argument_words)))
diff --git a/products/commands/backend/facade/api.py b/products/commands/backend/facade/api.py
index 0d37aed0f435..3335ab1e7580 100644
--- a/products/commands/backend/facade/api.py
+++ b/products/commands/backend/facade/api.py
@@ -69,16 +69,15 @@ def accept_slack_mention(mention: SlackMention) -> str | None:
# 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 ..logic.subjects import subject_payload # 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,
+ subject=subject_payload(command.subject),
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,
diff --git a/products/commands/backend/logic/admission.py b/products/commands/backend/logic/admission.py
index 25a63a6030a5..95d74e3f57f7 100644
--- a/products/commands/backend/logic/admission.py
+++ b/products/commands/backend/logic/admission.py
@@ -9,12 +9,12 @@ from django.core.cache import cache
import structlog
-from posthog.models.integration import Integration
from posthog.models.team import Team
from posthog.permissions import posthog_feature_flag_enabled
from posthog.token_bucket import BucketDecision, Budget, consume
-from .commands import DispatchOutcome
+from .commands import DispatchOutcome, SubjectRef
+from .subjects import candidate_team_ids, rollout_key
logger = structlog.get_logger(__name__)
@@ -26,34 +26,29 @@ _REQUESTER_BUDGET = Budget(burst=5, per_hour=30)
def rolled_out_team_ids(
flag: str,
- installation_id: str,
+ subject: SubjectRef,
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.
+ """The subject's candidate projects whose organization is in the rollout, in the subject's order.
``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(
- Integration.objects.filter(kind="github", integration_id=installation_id)
- .order_by("id")
- .values_list("team_id", flat=True)
- )
- )
+ team_ids = candidate_team_ids(subject)
teams = Team.objects.filter(id__in=team_ids).only("id", "organization_id")
if organization_ids is not None:
teams = teams.filter(organization_id__in=organization_ids)
+ distinct_id = f"{flag}-{rollout_key(subject)}"
rolled_out = {
team.id
for team in teams
if posthog_feature_flag_enabled(
flag,
# The rollout targets organizations, so the person behind the request does not matter yet.
- f"{flag}-installation-{installation_id}",
+ distinct_id,
organization_id=team.organization_id,
team_id=team.id,
only_evaluate_locally=only_evaluate_locally,
diff --git a/products/commands/backend/logic/commands.py b/products/commands/backend/logic/commands.py
index 4c4636144e21..2e4715d79e2c 100644
--- a/products/commands/backend/logic/commands.py
+++ b/products/commands/backend/logic/commands.py
@@ -6,13 +6,16 @@ handler, so a new command inherits the full set of checks by being declared in `
"""
import re
-from typing import Literal
+from typing import ClassVar, Literal
from posthog.dataclasses import frozen
# The name goes into GitHub API paths, so it must be exactly `owner/name`.
REPOSITORY_NAME_RE = re.compile(r"[A-Za-z0-9-]{1,39}/[A-Za-z0-9._-]{1,100}")
+SubjectKind = Literal["pull_request"]
+SUBJECT_NAMES: dict[SubjectKind, str] = {"pull_request": "pull requests"}
+
DispatchOutcome = Literal[
"duplicate",
"claim_unavailable",
@@ -25,6 +28,7 @@ DispatchOutcome = Literal[
"help",
"unknown_command",
"invalid_arguments",
+ "wrong_subject",
"unlinked",
"account_refused",
"no_project",
@@ -51,10 +55,18 @@ class Answer:
class PullRequestRef:
"""A pull request as a channel names it, before anything about it is checked."""
+ kind: ClassVar[SubjectKind] = "pull_request"
+
installation_id: str
repository: str
number: int
+ def describe(self) -> str:
+ return f"{self.repository}#{self.number}"
+
+
+SubjectRef = PullRequestRef
+
@frozen
class CommandTarget:
@@ -72,7 +84,7 @@ class CommandRequest:
It holds identifiers and the requester's own command text only, never text other people wrote.
"""
- subject: PullRequestRef
+ subject: SubjectRef
verb: str
argument: str
ambiguous: bool
@@ -101,6 +113,9 @@ class PullRequestFacts:
is_fork: bool
+SubjectFacts = PullRequestFacts
+
+
@frozen
class ProjectMember:
"""A project the commenter may act in, and the commenter's PostHog account that acts there.
@@ -116,16 +131,21 @@ class ProjectMember:
@frozen
class CommandContext:
request: CommandRequest
- pull_request: PullRequestFacts
+ subject: SubjectFacts
# Best candidate first. Every entry passed the membership, rollout and resource-access checks
# for this command. A project appears once per linked account that is a member of it.
members: tuple[ProjectMember, ...]
+ @property
+ def pull_request(self) -> PullRequestFacts:
+ """The subject of a command that accepts only pull requests."""
+ return self.subject
+
@frozen
class CommandOutcome:
accepted: bool
- # Markdown posted back on the pull request. Handlers build it from fixed text and values
- # PostHog or GitHub produced, never from the comment, so a reply cannot be made to say
- # something the commenter wrote.
+ # Markdown posted back where the command came from. Handlers build it from fixed text and values
+ # PostHog or GitHub produced, never from the request, so a reply cannot be made to say
+ # something the requester wrote.
message: str
diff --git a/products/commands/backend/logic/dispatcher.py b/products/commands/backend/logic/dispatcher.py
index 32fce67a183c..5168d923ac1a 100644
--- a/products/commands/backend/logic/dispatcher.py
+++ b/products/commands/backend/logic/dispatcher.py
@@ -11,8 +11,8 @@ Every command passes the same steps, in this order, before its handler runs:
``review``, the project that owns the repository in PostHog Review. Membership and access are
checked only there, and the requester's linked accounts must include a member of one of them.
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 allows
- forks if the head is a fork.
+4. The command accepts the kind of subject, and the subject allows the command: for a pull request,
+ it is open, and the command allows forks if the head is a fork.
5. The account has the access the command declares on the project, in PostHog access control.
"""
@@ -29,12 +29,11 @@ from posthog.models.team import Team
from posthog.models.user import User
from posthog.permissions import UserAccessControl
-from .commands import Answer, CommandContext, CommandRequest, DispatchOutcome, ProjectMember
-from .github import CommandGitHub
+from .commands import SUBJECT_NAMES, Answer, CommandContext, CommandRequest, DispatchOutcome, ProjectMember
from .identity import Requester, resolve_requester
from .registry import COMMANDS, CommandSpec, Invocation, help_text
from .schema import HELP_VERB, ArgumentError, ResourceAccess, resolve_verb, usage
-from .subjects import PullRequestSubject
+from .subjects import Subject
logger = structlog.get_logger(__name__)
@@ -49,10 +48,10 @@ COMMANDS_TOTAL = Counter(
class Admission:
"""A request the channel let through, with what the shared steps need from it."""
- # Projects on the installation in the channel's rollout, oldest integration first. A command
- # runs only in one of them.
+ # The subject's projects in the channel's rollout, in the subject's order. A command runs only
+ # in one of them.
team_ids: tuple[int, ...]
- github: CommandGitHub
+ subject: Subject
class CommandChannel(Protocol):
@@ -92,8 +91,8 @@ class CommandDispatcher:
channel=self._channel.name,
verb=verb_label,
outcome=outcome,
- repository=request.subject.repository,
- pr_number=request.subject.number,
+ subject_kind=request.subject.kind,
+ subject=request.subject.describe(),
)
return outcome
@@ -110,7 +109,7 @@ class CommandDispatcher:
self._channel.reply(command.message)
return command.outcome
- return self._run(command, admission.team_ids, admission.github)
+ return self._run(command, admission)
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, and
@@ -122,19 +121,21 @@ class CommandDispatcher:
return Answer(outcome="help", message=help_text())
if spec is None:
return Answer(outcome="unknown_command", message="I don't know that command.\n\n" + help_text())
+ if request.subject.kind not in spec.declaration.subject_kinds:
+ return Answer(
+ outcome="wrong_subject",
+ message=f"`{spec.declaration.verb}` doesn't run on {SUBJECT_NAMES[request.subject.kind]}.",
+ )
invocation = spec.parse(request.argument)
if isinstance(invocation, ArgumentError):
return Answer(outcome="invalid_arguments", message=f"{invocation.reason} Use `{usage(spec.declaration)}`.")
return invocation
- def _command_context(
- self, spec: CommandSpec[Any], team_ids: tuple[int, ...], github: CommandGitHub
- ) -> CommandContext | Answer:
+ def _command_context(self, spec: CommandSpec[Any], admission: Admission) -> CommandContext | Answer:
request = self._channel.request
declaration = spec.declaration
- not_member_message = (
- "You aren't a member of a PostHog project that uses pull request commands on this repository."
- )
+ team_ids = admission.team_ids
+ not_member_message = admission.subject.not_member_message
# The command's product names the projects it acts in first, so membership and access are
# checked only there.
if spec.target is not None:
@@ -152,9 +153,9 @@ class CommandDispatcher:
if not members:
return Answer(outcome="no_project", message=not_member_message)
- pull_request = PullRequestSubject(request.subject, github).facts(declaration)
- if isinstance(pull_request, Answer):
- return pull_request
+ subject = admission.subject.facts(declaration)
+ if isinstance(subject, Answer):
+ return subject
access = declaration.access
if access is not None:
@@ -164,21 +165,19 @@ class CommandDispatcher:
outcome="access_denied",
message=f"You need {access.level} access to {access.resource} in PostHog to use `{declaration.verb}`.",
)
- return CommandContext(request=request, pull_request=pull_request, members=members)
+ return CommandContext(request=request, subject=subject, members=members)
- def _run(self, command: Invocation[Any], team_ids: tuple[int, ...], github: CommandGitHub) -> DispatchOutcome:
+ def _run(self, command: Invocation[Any], admission: Admission) -> DispatchOutcome:
"""Builds the context and runs the handler. A failure in either answers the requester."""
verb = command.spec.declaration.verb
try:
- context = self._command_context(command.spec, team_ids, github)
+ context = self._command_context(command.spec, admission)
if isinstance(context, Answer):
self._channel.reply(context.message)
return context.outcome
outcome = command.run(context)
except GitHubRateLimitError:
- self._channel.reply(
- "GitHub is limiting how fast PostHog can work on this repository. Try again in a few minutes."
- )
+ self._channel.reply("GitHub is limiting how fast PostHog can work right now. Try again in a few minutes.")
return "failed"
except Exception as error:
capture_exception(error)
diff --git a/products/commands/backend/logic/registry.py b/products/commands/backend/logic/registry.py
index e49b9dad97d1..a753ba19b7e6 100644
--- a/products/commands/backend/logic/registry.py
+++ b/products/commands/backend/logic/registry.py
@@ -9,7 +9,7 @@ from typing import Any
from posthog.dataclasses import frozen
-from .commands import Answer, CommandContext, CommandOutcome, CommandTarget, PullRequestRef
+from .commands import Answer, CommandContext, CommandOutcome, CommandTarget, SubjectRef
from .handlers import handle_loop, handle_qa, handle_review, handle_stamp, review_target, stamp_target
from .schema import (
COMMAND_DECLARATIONS,
@@ -41,7 +41,7 @@ class CommandSpec[A]:
handler: Callable[[CommandContext, A], CommandOutcome]
# Names the projects the command's product acts in, out of the rolled-out candidates, before
# dispatch checks membership and access. Without one, every candidate counts.
- target: Callable[[PullRequestRef, tuple[int, ...]], CommandTarget | Answer] | None = None
+ target: Callable[[SubjectRef, tuple[int, ...]], CommandTarget | Answer] | None = None
def parse(self, raw_argument: str) -> Invocation[A] | ArgumentError:
args = parse_arguments(self.declaration, raw_argument)
diff --git a/products/commands/backend/logic/schema.py b/products/commands/backend/logic/schema.py
index a78df02430b4..85d9125c5e52 100644
--- a/products/commands/backend/logic/schema.py
+++ b/products/commands/backend/logic/schema.py
@@ -29,6 +29,8 @@ from typing import Any, Literal, Union, get_args, get_origin, get_type_hints
from posthog.dataclasses import frozen
from posthog.scopes import APIScopeObject
+from .commands import SubjectKind
+
SCHEMA_VERSION = 1
MENTION = "@posthog"
@@ -238,6 +240,7 @@ class CommandDeclaration[A]:
dispatches_to: str | None
aliases: tuple[str, ...] = ()
access: ResourceAccess | None = None
+ subject_kinds: tuple[SubjectKind, ...] = ("pull_request",)
# A fork's head is code nobody with write access has vetted. Commands that run or approve it
# must refuse forks; only a command that reads nothing from the head may allow them.
allows_forks: bool = False
diff --git a/products/commands/backend/logic/subjects.py b/products/commands/backend/logic/subjects.py
index eb0e25d32afd..28316e941af4 100644
--- a/products/commands/backend/logic/subjects.py
+++ b/products/commands/backend/logic/subjects.py
@@ -1,18 +1,34 @@
-"""What a command acts on. Pull requests are the only kind, and dispatch builds this class directly.
+"""What a command acts on: the projects it may run in, and the checks before its handler runs.
-A channel names the pull request: a comment names the one it sits on, and a Slack message names one
-by its URL. The subject reads the facts a handler gets, and refuses a pull request no command may
-touch.
+A channel names the subject with a reference from ``commands.py``. A comment names the pull request
+it sits on, and a Slack message names one by its URL. Dispatch then works with the subject only
+through the functions here and the ``Subject`` protocol, so it never assumes a pull request.
+
+To add a kind of subject: add its reference and facts types to ``commands.py``, a class here that
+follows ``Subject``, a case in each function below, and the kind to the commands that accept it.
"""
-from typing import Any
+from typing import Any, Protocol
+
+from posthog.models.integration import Integration
-from .commands import Answer, PullRequestFacts, PullRequestRef
-from .github import CommandGitHub, GitHubCallFailed, UnsupportedPullRequest
+from .commands import Answer, PullRequestFacts, PullRequestRef, SubjectFacts, SubjectRef
+from .github import CommandGitHub, GitHubCallFailed, InstallationGitHub, UnsupportedPullRequest
from .schema import CommandDeclaration
+class Subject(Protocol):
+ # The answer when none of the requester's accounts is a member of the subject's projects.
+ not_member_message: str
+
+ def facts(self, declaration: CommandDeclaration[Any]) -> SubjectFacts | Answer:
+ """What the handler gets about the subject, or why this command must not run on it."""
+ ...
+
+
class PullRequestSubject:
+ not_member_message = "You aren't a member of a PostHog project that uses pull request commands on this repository."
+
def __init__(self, ref: PullRequestRef, github: CommandGitHub) -> None:
self._ref = ref
self._github = github
@@ -42,3 +58,58 @@ class PullRequestSubject:
outcome="fork_refused", message=f"`{declaration.verb}` doesn't run on pull requests from forks."
)
return pull_request
+
+
+def candidate_team_ids(ref: SubjectRef) -> tuple[int, ...]:
+ """The projects a command on the subject may run in, before the rollout, oldest first.
+
+ For a pull request: the projects whose GitHub integration uses the installation.
+ """
+ return tuple(
+ dict.fromkeys(
+ Integration.objects.filter(kind="github", integration_id=ref.installation_id)
+ .order_by("id")
+ .values_list("team_id", flat=True)
+ )
+ )
+
+
+def rollout_key(ref: SubjectRef) -> str:
+ """The flag's distinct id for the subject. The rollout targets organizations, not people."""
+ return f"installation-{ref.installation_id}"
+
+
+def open_subject(ref: SubjectRef, team_ids: tuple[int, ...], github: CommandGitHub | None = None) -> Subject | Answer:
+ """The subject, ready to read, or the answer when PostHog cannot reach it.
+
+ ``github`` is a client the channel already holds. Without one, the subject makes its own
+ through a row of one of ``team_ids``.
+ """
+ github = github or InstallationGitHub.for_installation(ref.installation_id, 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 PullRequestSubject(ref, github)
+
+
+def subject_payload(ref: SubjectRef) -> dict[str, str | int]:
+ """The reference as a task argument. ``subject_from_payload`` reads it back."""
+ return {
+ "kind": ref.kind,
+ "installation_id": ref.installation_id,
+ "repository": ref.repository,
+ "number": ref.number,
+ }
+
+
+def subject_from_payload(payload: dict[str, str | int]) -> SubjectRef:
+ kind = payload["kind"]
+ if kind == "pull_request":
+ return PullRequestRef(
+ installation_id=str(payload["installation_id"]),
+ repository=str(payload["repository"]),
+ number=int(payload["number"]),
+ )
+ raise ValueError(f"Unknown subject kind {kind!r}")
diff --git a/products/commands/backend/tasks/tasks.py b/products/commands/backend/tasks/tasks.py
index 755b0b61c556..34e6c01c7785 100644
--- a/products/commands/backend/tasks/tasks.py
+++ b/products/commands/backend/tasks/tasks.py
@@ -5,6 +5,7 @@ from celery import shared_task
from ..channels.github.comments import dispatch_comment_command
from ..channels.github.intake import CommentCommandRequest
from ..channels.slack.mentions import SlackCommandRequest, dispatch_slack_command
+from ..logic.subjects import subject_from_payload
# No retries: a command that fails tells the commenter so in a reply, and a silent second attempt
@@ -42,10 +43,8 @@ def run_comment_command(
@shared_task(ignore_result=True, max_retries=0)
def run_slack_command(
*,
- installation_id: str,
+ subject: dict[str, str | int],
team_ids: list[int],
- repository: str,
- pr_number: int,
verb: str,
argument: str,
slack_team_id: str,
@@ -59,10 +58,8 @@ def run_slack_command(
) -> None:
dispatch_slack_command(
SlackCommandRequest(
- installation_id=installation_id,
+ subject=subject_from_payload(subject),
team_ids=tuple(team_ids),
- repository=repository,
- pr_number=pr_number,
verb=verb,
argument=argument,
slack_team_id=slack_team_id,
diff --git a/products/commands/backend/tests/test_dispatch.py b/products/commands/backend/tests/test_dispatch.py
index 72684bf812e3..212664af3815 100644
--- a/products/commands/backend/tests/test_dispatch.py
+++ b/products/commands/backend/tests/test_dispatch.py
@@ -59,7 +59,7 @@ CLAIM_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_INSTALLATION_GITHUB = "products.commands.backend.logic.subjects.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.
@@ -347,7 +347,7 @@ class TestDispatchCommentCommand(BaseTest):
def test_loop_reports_retirement(self) -> None:
context = CommandContext(
request=self._command_request(verb="loop", argument="Triage PR"),
- pull_request=_pull_request(),
+ subject=_pull_request(),
members=(ProjectMember(team_id=self.team.id, user_id=self.user.id),),
)
@@ -367,7 +367,7 @@ class TestDispatchCommentCommand(BaseTest):
) -> None:
context = CommandContext(
request=self._command_request(verb="qa"),
- pull_request=_pull_request(),
+ subject=_pull_request(),
members=(ProjectMember(team_id=self.team.id, user_id=self.user.id),),
)
@@ -527,7 +527,7 @@ class TestDispatchCommentCommand(BaseTest):
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,))
+ assert (command.subject.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)
diff --git a/products/commands/backend/tests/test_slack_parsing.py b/products/commands/backend/tests/test_slack_parsing.py
index 7400b11b31a6..a9c3840ebfed 100644
--- a/products/commands/backend/tests/test_slack_parsing.py
+++ b/products/commands/backend/tests/test_slack_parsing.py
@@ -1,6 +1,6 @@
from parameterized import parameterized
-from products.commands.backend.channels.slack.parsing import SlackPullRequestCommand, parse_slack_command
+from products.commands.backend.channels.slack.parsing import PullRequestUrl, SlackCommand, parse_slack_command
URL = "https://github.com/acme/widgets/pull/7"
@@ -17,8 +17,8 @@ URL = "https://github.com/acme/widgets/pull/7"
]
)
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
+ assert parse_slack_command(text) == SlackCommand(
+ subject=PullRequestUrl(repository="acme/widgets", number=7), verb=verb, argument=argument
)