: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): resolve and assign error tracking issues from slack (#117542)
Julian Bez3ed47721cd5c
diff --git a/products/commands/COMMANDS.generated.md b/products/commands/COMMANDS.generated.mdindex c57b4fc93fb9..66f88314c05c 100644--- a/products/commands/COMMANDS.generated.md+++ b/products/commands/COMMANDS.generated.md@@ -1,9 +1,11 @@<!-- Generated from backend/logic/schema.py. Do not edit. Run `hogli build:projections`. -->-| Command | Also | What it does |-| ----------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `@posthog review [--deep] [--no-resolve]` | | Start a Standard review of this pull request. `--deep`: Run a Deep review instead of the default Standard review. `--no-resolve`: Don't resolve review comments after a Deep review. By default the pull request owner's setting decides. |-| `@posthog stamp` | `approve` | Ask Stamphog to review this pull request. Stamphog decides whether to approve. |-| `@posthog qa [<focus>]` | | Run frontend QA on this pull request in PostHog Code and post a report. `<focus>`: What to focus on. The agent gets it as your instruction. |-| `@posthog loop <name>` | | Run one of your own Loops with this pull request as its input. `<name>`: The loop's name. |-| `@posthog help` | | List these commands. |+| Command | Also | Works on | What it does |+| ----------------------------------------- | --------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `@posthog review [--deep] [--no-resolve]` | | pull requests | Start a Standard review of this pull request. `--deep`: Run a Deep review instead of the default Standard review. `--no-resolve`: Don't resolve review comments after a Deep review. By default the pull request owner's setting decides. |+| `@posthog stamp` | `approve` | pull requests | Ask Stamphog to review this pull request. Stamphog decides whether to approve. |+| `@posthog qa [<focus>]` | | pull requests | Run frontend QA on this pull request in PostHog Code and post a report. `<focus>`: What to focus on. The agent gets it as your instruction. |+| `@posthog loop <name>` | | pull requests | Run one of your own Loops with this pull request as its input. `<name>`: The loop's name. |+| `@posthog resolve` | | error tracking issues | Mark this error tracking issue as resolved. |+| `@posthog assign` | | error tracking issues | Assign this error tracking issue to yourself. |+| `@posthog help` | | pull requests, error tracking issues | List these commands. |diff --git a/products/commands/README.md b/products/commands/README.mdindex 694339a15403..97b6221652bc 100644--- a/products/commands/README.md+++ b/products/commands/README.md@@ -16,7 +16,7 @@ This product owns the parsing, the checks and the replies, and owns no work of iA 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.+The subjects are pull requests and, from Slack, PostHog error tracking issues.[`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.@@ -40,12 +40,15 @@ Both are generated from `backend/logic/schema.py`, like the `@posthog help` repl## 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:+The same commands run from a Slack message that mentions the PostHog app and names the subject by its URL, before or after the command.+A pull request is named by its GitHub URL, and an error tracking issue by its URL in this PostHog instance:```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+@PostHog resolve https://us.posthog.com/project/2/error_tracking/01890a5d-ac96-774b-b3f2-3e3c8a6d2b11+@PostHog https://us.posthog.com/project/2/error_tracking/01890a5d-ac96-774b-b3f2-3e3c8a6d2b11 assign```- 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.@@ -60,13 +63,17 @@ The same commands run from a Slack message that mentions the PostHog app and nam## SubjectsThe 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.+A channel names it with a reference: a comment names the pull request it sits on, and a Slack message names a pull request or an error tracking issue 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.+For an error tracking issue, the URL names the issue by id, or by fingerprint as error tracking's Slack alerts link it, and the fingerprint resolves to whichever issue owns it now.+The project is the one in the URL, and only a URL of this instance counts, because project ids repeat across regions.+Its reply never repeats the issue's name, because the name comes from captured exception text that people outside the organization can write.+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.diff --git a/products/commands/backend/channels/slack/mentions.py b/products/commands/backend/channels/slack/mentions.pyindex 91e6f5442312..511443f8007a 100644--- a/products/commands/backend/channels/slack/mentions.py+++ b/products/commands/backend/channels/slack/mentions.py@@ -8,13 +8,14 @@ once, and the task trusts them. The run happens in this product's task, and thethrough the Slack integration the mention came in on.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+repository owner tells which projects may act on it. An error tracking issue URL names its project. A Slack command needs no GitHub permissioncheck: it runs as a PostHog account that is a member of the project, the same as the reviewtrigger in the PostHog API and MCP. It reaches only projects of organizations that connected thisSlack workspace, the same scope the agent has."""from collections.abc import Collection+from typing import assert_neverimport structlog@@ -26,13 +27,21 @@ from posthog.slack.markdown import slack_markdown_blockfrom ...facade.contracts import SlackMentionfrom ...logic.admission import claim, rolled_out_team_ids, within_rate_limit-from ...logic.commands import Answer, CommandRequest, DispatchOutcome, FollowUpAddress, PullRequestRef, SubjectRef+from ...logic.commands import (+ Answer,+ CommandRequest,+ DispatchOutcome,+ ErrorTrackingIssueRef,+ FollowUpAddress,+ PullRequestRef,+ SubjectRef,+)from ...logic.dispatcher import Admission, CommandDispatcherfrom ...logic.github import CommandGitHubfrom ...logic.registry import COMMANDSfrom ...logic.schema import ArgumentError, resolve_verbfrom ...logic.subjects import open_subject-from .parsing import SubjectUrl, parse_slack_command+from .parsing import ErrorTrackingIssueUrl, PullRequestUrl, SubjectUrl, parse_slack_commandlogger = structlog.get_logger(__name__)@@ -74,11 +83,21 @@ def _installation_id(owner: str, organization_ids: Collection[str]) -> str | Nondef _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)+ """Where the subject lives for PostHog, or None when no connected organization reaches it.++ An issue URL names its project. The rollout check after this keeps only a project of a+ connected organization.+ """+ match url:+ case PullRequestUrl():+ 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)+ case ErrorTrackingIssueUrl():+ return ErrorTrackingIssueRef(team_id=url.team_id, issue_id=url.issue_id, fingerprint=url.fingerprint)+ case _:+ assert_never(url)def read_slack_command(mention: SlackMention) -> SlackCommandRequest | None:diff --git a/products/commands/backend/channels/slack/parsing.py b/products/commands/backend/channels/slack/parsing.pyindex bccce3b60864..84fe8913d03c 100644--- a/products/commands/backend/channels/slack/parsing.py+++ b/products/commands/backend/channels/slack/parsing.py@@ -1,7 +1,8 @@"""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 the URL of its subject, in either order. For a pull request: ``review --deep https://github.com/PostHog/posthog/pull/123``+and the URL of its subject, in either order: a pull request on GitHub, or an error tracking issue+in this PostHog instance. 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 freetext, such as the focus of ``qa``, may also follow the URL. With the verb first, every word beforethe URL must be an option, so a valued option takes the ``--name=value`` form there. Anything else is@@ -12,6 +13,9 @@ A new kind of subject adds its URL type and a pattern in ``_read_subject_url``."""import re+from urllib.parse import unquote, urlsplit++from django.conf import settingsfrom posthog.dataclasses import frozen@@ -21,6 +25,15 @@ 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*)?")+# The app's own URL for an issue. The origin is checked against this instance separately, because+# project ids repeat across regions.+_ERROR_TRACKING_ISSUE_URL_RE = re.compile(+ r"(?P<origin>https?://[^/\s]+)/project/(?P<team_id>[0-9]{1,12})/error[_-]tracking/"+ r"(?:(?P<issue_id>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})"+ r"|fingerprint/(?P<fingerprint>[^/\s?#]{1,512}))(?:[/#?]\S*)?"+)+# The US app answers on both hosts.+_ORIGIN_ALIASES = {"https://us.posthog.com": "https://app.posthog.com"}_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 = ("-", "–", "—")@@ -32,7 +45,14 @@ class PullRequestUrl:number: int-SubjectUrl = PullRequestUrl+@frozen+class ErrorTrackingIssueUrl:+ team_id: int+ issue_id: str = ""+ fingerprint: str = ""+++SubjectUrl = PullRequestUrl | ErrorTrackingIssueUrl@frozen@@ -44,10 +64,24 @@ class SlackCommand: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+ return _PULL_REQUEST_URL_RE.search(text) is not None or _ERROR_TRACKING_ISSUE_URL_RE.search(text) is not None+++def _instance_origins() -> set[str]:+ parts = urlsplit(settings.SITE_URL)+ origin = f"{parts.scheme}://{parts.netloc}".lower()+ return {origin, _ORIGIN_ALIASES[origin]} if origin in _ORIGIN_ALIASES else {origin}def _read_subject_url(word: str) -> SubjectUrl | None:+ issue = _ERROR_TRACKING_ISSUE_URL_RE.fullmatch(word)+ if issue is not None:+ if issue.group("origin").lower() not in _instance_origins():+ return None+ team_id = int(issue.group("team_id"))+ if issue.group("issue_id") is not None:+ return ErrorTrackingIssueUrl(team_id=team_id, issue_id=issue.group("issue_id").lower())+ return ErrorTrackingIssueUrl(team_id=team_id, fingerprint=unquote(issue.group("fingerprint")))match = _PULL_REQUEST_URL_RE.fullmatch(word)if match is None:return Nonediff --git a/products/commands/backend/logic/commands.py b/products/commands/backend/logic/commands.pyindex a44b26a157ab..2c4607af8424 100644--- a/products/commands/backend/logic/commands.py+++ b/products/commands/backend/logic/commands.py@@ -13,8 +13,11 @@ 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"}+SubjectKind = Literal["pull_request", "error_tracking_issue"]+SUBJECT_NAMES: dict[SubjectKind, str] = {+ "pull_request": "pull requests",+ "error_tracking_issue": "error tracking issues",+}DispatchOutcome = Literal["duplicate",@@ -35,6 +38,7 @@ DispatchOutcome = Literal["pull_request_unavailable","pull_request_unsupported","pull_request_closed",+ "issue_not_found","fork_refused","access_denied","accepted",@@ -65,7 +69,25 @@ class PullRequestRef:return f"{self.repository}#{self.number}"-SubjectRef = PullRequestRef+@frozen+class ErrorTrackingIssueRef:+ """An error tracking issue as a PostHog URL names it, before anything about it is checked.++ The URL names the issue by id, or by a fingerprint that follows the issue through merges, as the+ links in error tracking's Slack alerts do. Exactly one of the two is set.+ """++ kind: ClassVar[SubjectKind] = "error_tracking_issue"++ team_id: int+ issue_id: str = ""+ fingerprint: str = ""++ def describe(self) -> str:+ return f"error tracking issue {self.issue_id}" if self.issue_id else "error tracking issue by fingerprint"+++SubjectRef = PullRequestRef | ErrorTrackingIssueRef@frozen@@ -113,7 +135,21 @@ class PullRequestFacts:is_fork: bool-SubjectFacts = PullRequestFacts+@frozen+class ErrorTrackingIssueFacts:+ """The issue as error tracking reports it when the task read it.++ The issue's name is not kept: it comes from captured exception text, which people outside the+ organization can write, so no reply may repeat it.+ """++ team_id: int+ issue_id: str+ status: str+ url: str+++SubjectFacts = PullRequestFacts | ErrorTrackingIssueFacts# Where a channel wants the result of work that finishes after the command answered. Only the@@ -145,6 +181,15 @@ class CommandContext:@propertydef pull_request(self) -> PullRequestFacts:"""The subject of a command that accepts only pull requests."""+ if not isinstance(self.subject, PullRequestFacts):+ raise TypeError(f"Expected a pull request, got {type(self.subject).__name__}")+ return self.subject++ @property+ def issue(self) -> ErrorTrackingIssueFacts:+ """The subject of a command that accepts only error tracking issues."""+ if not isinstance(self.subject, ErrorTrackingIssueFacts):+ raise TypeError(f"Expected an error tracking issue, got {type(self.subject).__name__}")return self.subjectdiff --git a/products/commands/backend/logic/dispatcher.py b/products/commands/backend/logic/dispatcher.pyindex ff278eb62932..41ae76a77843 100644--- a/products/commands/backend/logic/dispatcher.py+++ b/products/commands/backend/logic/dispatcher.py@@ -128,9 +128,11 @@ class CommandDispatcher:if request.ambiguous: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())+ return Answer(outcome="help", message=help_text(request.subject.kind))if spec is None:- return Answer(outcome="unknown_command", message="I don't know that command.\n\n" + help_text())+ return Answer(+ outcome="unknown_command", message="I don't know that command.\n\n" + help_text(request.subject.kind)+ )if request.subject.kind not in spec.declaration.subject_kinds:return Answer(outcome="wrong_subject",diff --git a/products/commands/backend/logic/handlers.py b/products/commands/backend/logic/handlers.pyindex 347f6fb342b5..3a5f6cd821ac 100644--- a/products/commands/backend/logic/handlers.py+++ b/products/commands/backend/logic/handlers.py@@ -9,6 +9,7 @@ data."""from collections.abc import Collection+from uuid import UUIDimport structlog@@ -17,6 +18,7 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.utils import absolute_uri+from products.error_tracking.backend.facade import issues as error_tracking_issuesfrom products.review_hog.backend.facade import (github as review_hog_github,reviews as review_hog_facade,@@ -33,8 +35,8 @@ from products.tasks.backend.facade import ()from . import follow_ups-from .commands import Answer, CommandContext, CommandOutcome, CommandTarget, PullRequestRef-from .schema import LoopArgs, QaArgs, ReviewArgs, StampArgs+from .commands import Answer, CommandContext, CommandOutcome, CommandTarget, PullRequestRef, SubjectRef+from .schema import AssignArgs, LoopArgs, QaArgs, ResolveArgs, ReviewArgs, StampArgslogger = structlog.get_logger(__name__)@@ -45,8 +47,16 @@ def _project_ids(team_ids: Collection[int]) -> dict[int, int]:return {team_id: parent_team_id or team_id for team_id, parent_team_id in rows}-def review_target(ref: PullRequestRef, team_ids: tuple[int, ...]) -> CommandTarget | Answer:+def _pull_request_ref(ref: SubjectRef) -> PullRequestRef:+ # Dispatch runs a target hook only for a command that accepts the subject's kind.+ if not isinstance(ref, PullRequestRef):+ raise TypeError(f"Expected a pull request, got {type(ref).__name__}")+ return ref+++def review_target(subject: SubjectRef, team_ids: tuple[int, ...]) -> CommandTarget | Answer:"""The project that owns the repository in PostHog Review, and its environments."""+ ref = _pull_request_ref(subject)owner_team_id = review_hog_github.owning_team_id(ref.installation_id, ref.repository)if owner_team_id is None:return Answer(outcome="refused", message="PostHog Review isn't set up for this repository.")@@ -57,8 +67,9 @@ def review_target(ref: PullRequestRef, team_ids: tuple[int, ...]) -> CommandTarg)-def stamp_target(ref: PullRequestRef, team_ids: tuple[int, ...]) -> CommandTarget | Answer:+def stamp_target(subject: SubjectRef, team_ids: tuple[int, ...]) -> CommandTarget | Answer:"""The projects where Stamphog reviews the repository, and their environments."""+ ref = _pull_request_ref(subject)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.")@@ -196,5 +207,34 @@ def build_qa_instructions(context: CommandContext, focus: str) -> str:return "\n\n".join(lines)+def handle_resolve(context: CommandContext, args: ResolveArgs) -> CommandOutcome:+ """Resolve the error tracking issue as the requester, through the same write the issue API makes."""+ issue = context.issue+ member = context.members[0]+ user = User.objects.get(id=member.user_id)+ # The write reads the status under a lock, so it, not the earlier read, says whether anything changed.+ update = error_tracking_issues.update_issue(+ issue.team_id, UUID(issue.issue_id), fields={"status": "resolved"}, user=user, was_impersonated=False+ )+ if "status" not in update.changed_fields:+ return CommandOutcome(accepted=True, message=f"[The issue]({issue.url}) is already resolved.")+ return CommandOutcome(accepted=True, message=f"Resolved [the issue]({issue.url}).")+++def handle_assign(context: CommandContext, args: AssignArgs) -> CommandOutcome:+ """Assign the error tracking issue to the requester's account that acts in its project."""+ issue = context.issue+ member = context.members[0]+ user = User.objects.get(id=member.user_id)+ error_tracking_issues.assign_issue(+ issue.team_id,+ UUID(issue.issue_id),+ {"id": user.id, "type": "user"},+ user=user,+ was_impersonated=False,+ )+ return CommandOutcome(accepted=True, message=f"Assigned [the issue]({issue.url}) to you.")++def handle_loop(context: CommandContext, args: LoopArgs) -> CommandOutcome:return CommandOutcome(accepted=False, message="Legacy loops have been retired. Use workflows instead.")diff --git a/products/commands/backend/logic/registry.py b/products/commands/backend/logic/registry.pyindex a753ba19b7e6..546118d545a3 100644--- a/products/commands/backend/logic/registry.py+++ b/products/commands/backend/logic/registry.py@@ -9,12 +9,23 @@ from typing import Anyfrom posthog.dataclasses import frozen-from .commands import Answer, CommandContext, CommandOutcome, CommandTarget, SubjectRef-from .handlers import handle_loop, handle_qa, handle_review, handle_stamp, review_target, stamp_target+from .commands import SUBJECT_NAMES, Answer, CommandContext, CommandOutcome, CommandTarget, SubjectKind, SubjectRef+from .handlers import (+ handle_assign,+ handle_loop,+ handle_qa,+ handle_resolve,+ handle_review,+ handle_stamp,+ review_target,+ stamp_target,+)from .schema import (+ ASSIGN,COMMAND_DECLARATIONS,LOOP,QA,+ RESOLVE,REVIEW,STAMP,ArgumentError,@@ -65,9 +76,11 @@ COMMANDS: Mapping[str, CommandSpec[Any]] = _index(CommandSpec(declaration=STAMP, handler=handle_stamp, target=stamp_target),CommandSpec(declaration=QA, handler=handle_qa),CommandSpec(declaration=LOOP, handler=handle_loop),+ CommandSpec(declaration=RESOLVE, handler=handle_resolve),+ CommandSpec(declaration=ASSIGN, handler=handle_assign),))-def help_text() -> str:- return f"Commands you can use on a pull request:\n\n{help_table()}"+def help_text(subject_kind: SubjectKind) -> str:+ return f"Commands you can use on {SUBJECT_NAMES[subject_kind]}:\n\n{help_table(subject_kind)}"diff --git a/products/commands/backend/logic/schema.py b/products/commands/backend/logic/schema.pyindex 85d9125c5e52..fa3013e5d565 100644--- a/products/commands/backend/logic/schema.py+++ b/products/commands/backend/logic/schema.py@@ -29,7 +29,7 @@ from typing import Any, Literal, Union, get_args, get_origin, get_type_hintsfrom posthog.dataclasses import frozenfrom posthog.scopes import APIScopeObject-from .commands import SubjectKind+from .commands import SUBJECT_NAMES, SubjectKindSCHEMA_VERSION = 1@@ -101,6 +101,16 @@ class LoopArgs:name: str = text("The loop's name.", required=True)+@frozen+class ResolveArgs:+ pass+++@frozen+class AssignArgs:+ pass++@frozenclass HelpArgs:pass@@ -281,6 +291,22 @@ LOOP = CommandDeclaration(dispatches_to="Loops",access=ResourceAccess(resource="loop", level="editor"),)+RESOLVE = CommandDeclaration(+ verb="resolve",+ summary="Mark this error tracking issue as resolved.",+ args=ResolveArgs,+ dispatches_to="Error tracking",+ access=ResourceAccess(resource="error_tracking", level="editor"),+ subject_kinds=("error_tracking_issue",),+)+ASSIGN = CommandDeclaration(+ verb="assign",+ summary="Assign this error tracking issue to yourself.",+ args=AssignArgs,+ dispatches_to="Error tracking",+ access=ResourceAccess(resource="error_tracking", level="editor"),+ subject_kinds=("error_tracking_issue",),+)# Answered by dispatch itself: it needs no PostHog account, project or pull request state.HELP = CommandDeclaration(verb=HELP_VERB,@@ -288,9 +314,10 @@ HELP = CommandDeclaration(args=HelpArgs,dispatches_to=None,allows_forks=True,+ subject_kinds=get_args(SubjectKind),)-COMMAND_DECLARATIONS: tuple[CommandDeclaration[Any], ...] = (REVIEW, STAMP, QA, LOOP)+COMMAND_DECLARATIONS: tuple[CommandDeclaration[Any], ...] = (REVIEW, STAMP, QA, LOOP, RESOLVE, ASSIGN)def _canonical_verbs(declarations: tuple[CommandDeclaration[Any], ...]) -> Mapping[str, str]:@@ -411,6 +438,7 @@ def _command_signature(declaration: CommandDeclaration[Any]) -> dict[str, objectif text_field is not Noneelse None),+ "subject_kinds": list(declaration.subject_kinds),"refuses_forks": not declaration.allows_forks,"access": ({"resource": declaration.access.resource, "level": declaration.access.level}@@ -445,13 +473,25 @@ def _what_it_does(declaration: CommandDeclaration[Any]) -> str:return " ".join(parts)-def help_table() -> str:- """The command table for the help reply and `COMMANDS.generated.md`."""- rows = [- "| Command | Also | What it does |",- "| --- | --- | --- |",+def help_table(subject_kind: SubjectKind | None = None) -> str:+ """The command table for the help reply and `COMMANDS.generated.md`.++ With a kind, it lists only the commands that act on it. Without one, it lists every command+ and what each works on.+ """+ declarations = [+ declaration+ for declaration in (*COMMAND_DECLARATIONS, HELP)+ if subject_kind is None or subject_kind in declaration.subject_kinds]- for declaration in (*COMMAND_DECLARATIONS, HELP):- also = ", ".join(f"`{alias}`" for alias in declaration.aliases)- rows.append(f"| `{_table_cell(usage(declaration))}` | {also} | {_table_cell(_what_it_does(declaration))} |")+ if subject_kind is not None:+ rows = ["| Command | Also | What it does |", "| --- | --- | --- |"]+ else:+ rows = ["| Command | Also | Works on | What it does |", "| --- | --- | --- | --- |"]+ for declaration in declarations:+ cells = [f"`{_table_cell(usage(declaration))}`", ", ".join(f"`{alias}`" for alias in declaration.aliases)]+ if subject_kind is None:+ cells.append(", ".join(SUBJECT_NAMES[kind] for kind in declaration.subject_kinds))+ cells.append(_table_cell(_what_it_does(declaration)))+ rows.append(f"| {' | '.join(cells)} |")return "\n".join(rows)diff --git a/products/commands/backend/logic/subjects.py b/products/commands/backend/logic/subjects.pyindex 28316e941af4..91b0779484f6 100644--- a/products/commands/backend/logic/subjects.py+++ b/products/commands/backend/logic/subjects.py@@ -1,18 +1,29 @@"""What a command acts on: the projects it may run in, and the checks before its handler runs.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+it sits on, and a Slack message names a pull request or an error tracking issue by its URL. Dispatch then works with the subject onlythrough 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 thatfollows ``Subject``, a case in each function below, and the kind to the commands that accept it."""-from typing import Any, Protocol+from typing import Any, Protocol, assert_neverfrom posthog.models.integration import Integration--from .commands import Answer, PullRequestFacts, PullRequestRef, SubjectFacts, SubjectRef+from posthog.utils import absolute_uri++from products.error_tracking.backend.facade import api as error_tracking++from .commands import (+ Answer,+ ErrorTrackingIssueFacts,+ ErrorTrackingIssueRef,+ PullRequestFacts,+ PullRequestRef,+ SubjectFacts,+ SubjectRef,+)from .github import CommandGitHub, GitHubCallFailed, InstallationGitHub, UnsupportedPullRequestfrom .schema import CommandDeclaration@@ -60,48 +71,98 @@ class PullRequestSubject:return pull_request+class ErrorTrackingIssueSubject:+ not_member_message = "You aren't a member of the PostHog project this issue belongs to."++ def __init__(self, ref: ErrorTrackingIssueRef) -> None:+ self._ref = ref++ def facts(self, declaration: CommandDeclaration[Any]) -> ErrorTrackingIssueFacts | Answer:+ not_found = Answer(outcome="issue_not_found", message="I couldn't find this issue in error tracking.")+ issue_id = self._ref.issue_id+ if not issue_id:+ owner = error_tracking.get_issue_id_for_fingerprint(self._ref.team_id, self._ref.fingerprint)+ if owner is None:+ return not_found+ issue_id = str(owner)+ issue = error_tracking.get_issue_basics(self._ref.team_id, issue_id)+ if issue is None:+ return not_found+ return ErrorTrackingIssueFacts(+ team_id=self._ref.team_id,+ issue_id=issue_id,+ status=str(issue.status),+ url=absolute_uri(f"/project/{self._ref.team_id}/error_tracking/{issue_id}"),+ )++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.+ For a pull request: the projects whose GitHub integration uses the installation. For an error+ tracking issue: the project in its URL."""- return tuple(- dict.fromkeys(- Integration.objects.filter(kind="github", integration_id=ref.installation_id)- .order_by("id")- .values_list("team_id", flat=True)- )- )+ match ref:+ case PullRequestRef():+ return tuple(+ dict.fromkeys(+ Integration.objects.filter(kind="github", integration_id=ref.installation_id)+ .order_by("id")+ .values_list("team_id", flat=True)+ )+ )+ case ErrorTrackingIssueRef():+ return (ref.team_id,)+ case _:+ assert_never(ref)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}"+ match ref:+ case PullRequestRef():+ return f"installation-{ref.installation_id}"+ case ErrorTrackingIssueRef():+ return f"team-{ref.team_id}"+ case _:+ assert_never(ref)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+ ``github`` is a client the channel already holds. Without one, a pull request makes its ownthrough 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)+ match ref:+ case PullRequestRef():+ 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)+ case ErrorTrackingIssueRef():+ return ErrorTrackingIssueSubject(ref)+ case _:+ assert_never(ref)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,- }+ match ref:+ case PullRequestRef():+ return {+ "kind": ref.kind,+ "installation_id": ref.installation_id,+ "repository": ref.repository,+ "number": ref.number,+ }+ case ErrorTrackingIssueRef():+ return {"kind": ref.kind, "team_id": ref.team_id, "issue_id": ref.issue_id, "fingerprint": ref.fingerprint}+ case _:+ assert_never(ref)def subject_from_payload(payload: dict[str, str | int]) -> SubjectRef:@@ -112,4 +173,10 @@ def subject_from_payload(payload: dict[str, str | int]) -> SubjectRef:repository=str(payload["repository"]),number=int(payload["number"]),)+ if kind == "error_tracking_issue":+ return ErrorTrackingIssueRef(+ team_id=int(payload["team_id"]),+ issue_id=str(payload["issue_id"]),+ fingerprint=str(payload.get("fingerprint", "")),+ )raise ValueError(f"Unknown subject kind {kind!r}")diff --git a/products/commands/backend/tests/test_dispatch.py b/products/commands/backend/tests/test_dispatch.pyindex c1ba0d1c32f2..fc0c117b0a26 100644--- a/products/commands/backend/tests/test_dispatch.py+++ b/products/commands/backend/tests/test_dispatch.py@@ -10,12 +10,15 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from django.conf import settingsfrom django.core.cache import cachefrom django.utils import timezonefrom parameterized import parameterizedfrom social_django.models import UserSocialAuth+from posthog.schema import ErrorTrackingIssueStatus+from posthog.constants import AvailableFeaturefrom posthog.ingress.dispatch.loading import reset_consumer_registryfrom posthog.models.integration import Integration@@ -32,12 +35,20 @@ from products.commands.backend.channels.github.intake import CommentCommandRequefrom products.commands.backend.channels.slack.mentions import read_slack_commandfrom products.commands.backend.facade.api import accept_slack_mentionfrom products.commands.backend.facade.contracts import SlackMention-from products.commands.backend.logic.commands import CommandContext, CommandRequest, ProjectMember, PullRequestFacts+from products.commands.backend.logic.commands import (+ CommandContext,+ CommandRequest,+ ProjectMember,+ PullRequestFacts,+ PullRequestRef,+)from 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, QaArgsfrom products.commands.backend.receivers import on_review_finishedfrom products.commands.backend.tasks.tasks import deliver_follow_up, run_slack_command+from products.error_tracking.backend.facade.api import get_issue+from products.error_tracking.backend.facade.testing import create_issue, create_issue_fingerprintfrom products.review_hog.backend.facade.finished_review_hooks import FinishedReviewfrom products.review_hog.backend.facade.reviews import (RUN_MODE_FLASH,@@ -499,9 +510,15 @@ class TestDispatchCommentCommand(BaseTest):config={"account": {"name": account}})- def _slack_mention(self, text: str, organization_ids: tuple[str, ...], integration_id: int = 0) -> SlackMention:+ def _slack_mention(+ self,+ text: str,+ organization_ids: tuple[str, ...],+ integration_id: int = 0,+ url: str = f"https://github.com/{REPOSITORY}/pull/7",+ ) -> SlackMention:return SlackMention(- text=f"{text} https://github.com/{REPOSITORY}/pull/7",+ text=f"{text} {url}",slack_team_id="T1",slack_user_id="U1",channel="C1",@@ -535,7 +552,8 @@ class TestDispatchCommentCommand(BaseTest):assert (command.verb if command else None) == expected_verbif command is not None:- assert (command.subject.installation_id, command.team_ids) == (INSTALLATION_ID, (self.team.id,))+ assert command.subject == PullRequestRef(installation_id=INSTALLATION_ID, repository=REPOSITORY, number=7)+ assert command.team_ids == (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)@@ -609,6 +627,58 @@ class TestDispatchCommentCommand(BaseTest):else:follow_up_post.assert_not_called()+ @parameterized.expand(+ [+ ("resolve", "resolve", False, "active", "Resolved [the issue]", "resolved", None),+ ("assign", "assign", False, "active", "Assigned [the issue]", "active", "user"),+ # Error tracking's Slack alerts link the issue by its fingerprint.+ ("resolve_by_fingerprint", "resolve", True, "active", "Resolved [the issue]", "resolved", None),+ ("resolve_again", "resolve", False, "resolved", "[The issue](", "resolved", None),+ # A pull request command answers instead of acting on an issue.+ (+ "pull_request_command",+ "review",+ False,+ "active",+ "`review` doesn't run on error tracking issues.",+ "active",+ None,+ ),+ ]+ )+ def test_a_slack_command_acts_on_an_error_tracking_issue_url(+ self,+ _name: str,+ verb: str,+ by_fingerprint: bool,+ initial_status: str,+ expected_answer: str,+ expected_status: str,+ expected_assignee: str | None,+ ) -> None:+ issue_id = create_issue(+ team_id=self.team.id, name="TypeError: boom", status=ErrorTrackingIssueStatus(initial_status)+ )+ create_issue_fingerprint(team_id=self.team.id, issue_id=issue_id, fingerprint="fp-1")+ slack = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T1", config={}, sensitive_config={"access_token": "xoxb-x"}+ )+ path = "error-tracking/fingerprint/fp-1" if by_fingerprint else f"error_tracking/{issue_id}"+ url = f"{settings.SITE_URL}/project/{self.team.id}/{path}"+ mention = self._slack_mention(verb, (str(self.organization.id),), integration_id=slack.id, url=url)++ with (+ patch(RUN_SLACK_COMMAND, side_effect=lambda **kwargs: run_slack_command(**kwargs)),+ patch(SLACK_POST) as post,+ ):+ accepted = accept_slack_mention(mention)++ assert accepted == verb+ assert post.call_args.args[3].startswith(expected_answer)+ issue = get_issue(issue_id, self.team.id)+ assert issue.status == expected_status+ assert (issue.assignee.type if issue.assignee else None) == expected_assignee+@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_slack_parsing.py b/products/commands/backend/tests/test_slack_parsing.pyindex a9c3840ebfed..f4554228ba07 100644--- a/products/commands/backend/tests/test_slack_parsing.py+++ b/products/commands/backend/tests/test_slack_parsing.py@@ -1,6 +1,13 @@+from django.test import override_settings+from parameterized import parameterized-from products.commands.backend.channels.slack.parsing import PullRequestUrl, SlackCommand, parse_slack_command+from products.commands.backend.channels.slack.parsing import (+ ErrorTrackingIssueUrl,+ PullRequestUrl,+ SlackCommand,+ parse_slack_command,+)URL = "https://github.com/acme/widgets/pull/7"@@ -35,3 +42,31 @@ def test_reads_a_pull_request_command(_name: str, text: str, verb: str, argument)def test_anything_else_is_not_a_command(_name: str, text: str) -> None:assert parse_slack_command(text) is None+++ISSUE_ID = "01890a5d-ac96-774b-b3f2-3e3c8a6d2b11"+++ [+ ("this_instance", "https://us.posthog.com", True),+ ("us_alias_host", "https://app.posthog.com", True),+ # Project ids repeat across regions, so another region's link must not act here.+ ("other_region", "https://eu.posthog.com", False),+ ("lookalike_host", "https://us.posthog.com.example.com", False),+ ("userinfo_trick", "https://[email protected]", False),+ ]+)+@override_settings(SITE_URL="https://us.posthog.com")+def test_reads_an_issue_url_only_from_this_instance(_name: str, origin: str, accepted: bool) -> None:+ command = parse_slack_command(f"resolve {origin}/project/2/error_tracking/{ISSUE_ID}")++ expected = ErrorTrackingIssueUrl(team_id=2, issue_id=ISSUE_ID) if accepted else None+ assert (command.subject if command else None) == expected+++@override_settings(SITE_URL="https://us.posthog.com")+def test_reads_the_fingerprint_link_an_alert_posts() -> None:+ command = parse_slack_command("resolve https://us.posthog.com/project/2/error-tracking/fingerprint/abc%2Fdef")++ assert command is not None and command.subject == ErrorTrackingIssueUrl(team_id=2, fingerprint="abc/def")diff --git a/products/commands/commands.generated.json b/products/commands/commands.generated.jsonindex 4ee5c4489cd0..32d7fb43c5aa 100644--- a/products/commands/commands.generated.json+++ b/products/commands/commands.generated.json@@ -2,6 +2,21 @@"schema_version": 1,"prefix": "@posthog","commands": [+ {+ "verb": "assign",+ "aliases": [],+ "summary": "Assign this error tracking issue to yourself.",+ "dispatches_to": "Error tracking",+ "options": [],+ "text": null,+ "subject_kinds": ["error_tracking_issue"],+ "refuses_forks": true,+ "access": {+ "resource": "error_tracking",+ "level": "editor"+ },+ "usage": "@posthog assign"+ },{"verb": "help","aliases": [],@@ -9,6 +24,7 @@"dispatches_to": null,"options": [],"text": null,+ "subject_kinds": ["pull_request", "error_tracking_issue"],"refuses_forks": false,"access": null,"usage": "@posthog help"@@ -25,6 +41,7 @@"help": "The loop's name.","verbatim": true},+ "subject_kinds": ["pull_request"],"refuses_forks": true,"access": {"resource": "loop",@@ -44,6 +61,7 @@"help": "What to focus on. The agent gets it as your instruction.","verbatim": true},+ "subject_kinds": ["pull_request"],"refuses_forks": true,"access": {"resource": "task",@@ -51,6 +69,21 @@},"usage": "@posthog qa [<focus>]"},+ {+ "verb": "resolve",+ "aliases": [],+ "summary": "Mark this error tracking issue as resolved.",+ "dispatches_to": "Error tracking",+ "options": [],+ "text": null,+ "subject_kinds": ["error_tracking_issue"],+ "refuses_forks": true,+ "access": {+ "resource": "error_tracking",+ "level": "editor"+ },+ "usage": "@posthog resolve"+ },{"verb": "review","aliases": [],@@ -75,6 +108,7 @@}],"text": null,+ "subject_kinds": ["pull_request"],"refuses_forks": true,"access": {"resource": "review_hog",@@ -89,6 +123,7 @@"dispatches_to": "Stamphog","options": [],"text": null,+ "subject_kinds": ["pull_request"],"refuses_forks": true,"access": {"resource": "stamphog",diff --git a/tach.toml b/tach.tomlindex e123a291ebff..126d3905c031 100644--- a/tach.toml+++ b/tach.toml@@ -1754,9 +1754,16 @@ from = [[[modules]]path = "products.commands"-# Facade-only (enforced by each product's [[interfaces]] block): pull request comment commands-# dispatch into these products.-depends_on = ["posthog", "products.review_hog", "products.security", "products.stamphog", "products.tasks"]+# Facade-only (enforced by each product's [[interfaces]] block): commands dispatch into these+# products.+depends_on = [+ "posthog",+ "products.error_tracking",+ "products.review_hog",+ "products.security",+ "products.stamphog",+ "products.tasks",+]layer = "modules"[[interfaces]]