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.

32.9 KB
Raw Blame
import json
from collections import Counter, defaultdict
from datetime import UTC, datetime
from functools import lru_cache
from typing import Any, cast

from django.db import connection
from django.db.models import Count

import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
    OpenApiParameter,
    PolymorphicProxySerializer,
    extend_schema,
    extend_schema_field,
    extend_schema_serializer,
)
from rest_framework import request, serializers, viewsets
from rest_framework.decorators import action as drf_action
from rest_framework.renderers import BaseRenderer
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework_csv import renderers as csvrenderers

from posthog.hogql.errors import QueryError
from posthog.hogql.property import validate_regex

from posthog.api.documentation import (
    ArrayPropertyFilterSerializer,
    DatePropertyFilterSerializer,
    ExistencePropertyFilterSerializer,
    NumericPropertyFilterSerializer,
    StringPropertyFilterSerializer,
)
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.property_filter_access_gate import table_blocking_property_filters
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.constants import TREND_FILTER_TYPE_EVENTS
from posthog.dataclasses import frozen
from posthog.event_usage import report_user_action
from posthog.models import Team
from posthog.models.event.event import Selector
from posthog.models.property.util import build_selector_regex
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.taxonomy.hidden_events import HIDDEN_EVENT_REASON, added_hidden_event

from products.access_control.backend.presentation.access_control import (
    AccessControlViewSetMixin,
    UserAccessControlSerializerMixin,
)
from products.actions.backend.facade.contracts import ACTION_STEP_MATCHING_OPTIONS
from products.actions.backend.facade.enums import ACTION_REFERENCE_JSONPATH, ACTIONS_ARRAY_JSONPATH
from products.actions.backend.models.action import Action
from products.actions.backend.models.selector_match_change import ActionSelectorMatchChange
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.facade.actions import (
    count_experiments_referencing_actions,
    experiments_referencing_action,
)
from products.feature_flags.backend.facade.flags import hides_flag_calls_from_query_builders
from products.product_analytics.backend.facade.models import Insight

logger = structlog.get_logger(__name__)

_PropertyFilterUnion = PolymorphicProxySerializer(
    component_name="ActionStepPropertyFilter",
    serializers=[
        StringPropertyFilterSerializer,
        NumericPropertyFilterSerializer,
        ArrayPropertyFilterSerializer,
        DatePropertyFilterSerializer,
        ExistencePropertyFilterSerializer,
    ],
    resource_type_field_name=None,
)


@extend_schema_field(serializers.ListSerializer(child=_PropertyFilterUnion))
class _ActionStepPropertiesField(serializers.ListField):
    """ListField annotated with a typed OpenAPI schema via a oneOf property filter union.

    Runtime validation remains a simple ListField(child=DictField()) — the
    @extend_schema_field decorator only affects the generated OpenAPI spec.
    """

    pass


# An entry holds the selector plus its compiled regex, which is larger, for the life of
# the process. Nobody hand-writes a CSS selector this long, so cap what gets retained.
_MAX_CACHED_SELECTOR_LENGTH = 1_000


@frozen
class _CompiledSelector:
    regex: str | None
    warning: str | None


def _compile_selector_uncached(selector_str: str) -> _CompiledSelector:
    try:
        selector = Selector(selector_str, escape_slashes=False)
        warning = None
        if selector.has_unsupported_syntax():
            warning = "This selector uses CSS we cannot match on. Try matching on the element tag, id, or class."
        return _CompiledSelector(regex=build_selector_regex(selector), warning=warning)
    except Exception:
        logger.exception("Failed to compile action selector")
        return _CompiledSelector(
            regex=None,
            warning="This selector could not be read, so it will not match any events. Check that it is valid CSS.",
        )


@lru_cache(maxsize=2048)
def _compile_selector_cached(selector_str: str) -> _CompiledSelector:
    return _compile_selector_uncached(selector_str)


def _compile_selector(selector_str: str) -> _CompiledSelector:
    # Cached because the selector_regex and selector_warning fields both need it for
    # every serialized action step. An outsized or non-string selector skips the cache:
    # lru_cache hashes its argument before the body runs, so an unhashable one would
    # raise from the lookup itself.
    if not isinstance(selector_str, str) or len(selector_str) > _MAX_CACHED_SELECTOR_LENGTH:
        return _compile_selector_uncached(selector_str)
    return _compile_selector_cached(selector_str)


def _selector_str(obj) -> str | None:
    return obj.get("selector") if isinstance(obj, dict) else getattr(obj, "selector", None)


class ActionStepJSONSerializer(serializers.Serializer):
    event = serializers.CharField(
        required=False,
        allow_null=True,
        trim_whitespace=False,
        help_text="Event name to match (e.g. '$pageview', '$autocapture', or a custom event name).",
    )
    properties = _ActionStepPropertiesField(
        child=serializers.DictField(),
        required=False,
        allow_null=True,
        help_text="Event or person property filters. Each item should have 'key' (string), 'value' (string, number, boolean, or array), optional 'operator' (exact, is_not, is_set, is_not_set, icontains, not_icontains, regex, not_regex, gt, gte, lt, lte), and optional 'type' (event, person).",
    )
    selector = serializers.CharField(
        required=False,
        allow_null=True,
        help_text="CSS selector to match the target element (e.g. 'div > button.cta').",
    )
    selector_regex = serializers.SerializerMethodField(
        help_text="Compiled regex the selector matches against the event elements chain. Null when no selector is set."
    )
    selector_warning = serializers.SerializerMethodField(
        help_text="Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent."
    )
    tag_name = serializers.CharField(
        required=False,
        allow_null=True,
        trim_whitespace=False,
        help_text='HTML tag name to match (e.g. "button", "a", "input").',
    )
    text = serializers.CharField(
        required=False,
        allow_null=True,
        trim_whitespace=False,
        help_text="Element text content to match.",
    )
    text_matching = serializers.ChoiceField(
        choices=ACTION_STEP_MATCHING_OPTIONS,
        required=False,
        allow_null=True,
        help_text="How to match the text value. Defaults to exact.",
    )
    href = serializers.CharField(
        required=False,
        allow_null=True,
        trim_whitespace=False,
        help_text="Link href attribute to match.",
    )
    href_matching = serializers.ChoiceField(
        choices=ACTION_STEP_MATCHING_OPTIONS,
        required=False,
        allow_null=True,
        help_text="How to match the href value. Defaults to exact.",
    )
    url = serializers.CharField(
        required=False,
        allow_null=True,
        help_text="Page URL to match.",
    )
    url_matching = serializers.ChoiceField(
        choices=ACTION_STEP_MATCHING_OPTIONS,
        required=False,
        allow_null=True,
        help_text="How to match the URL value. Defaults to contains.",
    )

    def get_selector_regex(self, obj) -> str | None:
        selector_str = _selector_str(obj)
        return _compile_selector(selector_str).regex if selector_str else None

    def get_selector_warning(self, obj) -> str | None:
        selector_str = _selector_str(obj)
        return _compile_selector(selector_str).warning if selector_str else None


class ActionSerializer(
    TaggedItemSerializerMixin, UserAccessControlSerializerMixin, serializers.HyperlinkedModelSerializer
):
    steps = ActionStepJSONSerializer(
        many=True,
        required=False,
        help_text="Action steps defining trigger conditions. Each step matches events by name, properties, URL, or element attributes. Multiple steps are OR-ed together.",
    )
    created_by = UserBasicSerializer(read_only=True)
    is_calculating = serializers.SerializerMethodField()
    is_action = serializers.BooleanField(read_only=True, default=True)
    creation_context = serializers.SerializerMethodField()
    _create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)

    class Meta:
        model = Action
        fields = [
            "id",
            "name",
            "description",
            "tags",
            "post_to_slack",
            "slack_message_format",
            "steps",
            "created_at",
            "created_by",
            "deleted",
            "is_calculating",
            "last_calculated_at",
            "team_id",
            "is_action",
            "bytecode_error",
            "pinned_at",
            "creation_context",
            "_create_in_folder",
            "user_access_level",
        ]
        read_only_fields = [
            "team_id",
            "bytecode_error",
        ]
        extra_kwargs = {
            "team_id": {"read_only": True},
            "name": {"help_text": "Name of the action (must be unique within the project)."},
            "description": {"help_text": "Human-readable description of what this action represents."},
            "tags": {"help_text": "Tags for organizing and filtering actions."},
            "post_to_slack": {"help_text": "Whether to post a notification to Slack when this action is triggered."},
            "slack_message_format": {
                "help_text": "Custom Slack message format. Supports templates with event properties."
            },
            "pinned_at": {
                "help_text": "ISO 8601 timestamp when the action was pinned, or null if not pinned. Set any value to pin, null to unpin."
            },
        }

    def get_is_calculating(self, action: Action) -> bool:
        return False

    @extend_schema_field(serializers.CharField(allow_null=True))
    def get_creation_context(self, obj) -> None:
        return None

    def validate_steps(self, steps: list[dict[str, Any]] | None) -> list[dict[str, Any]] | None:
        # ClickHouse compiles these with RE2 at query time, so one pattern RE2 rejects fails
        # every insight that uses the action. steps_to_expr runs this same check on stored steps.
        # The check runs here and not on the step serializer because the error renderer turns an
        # error nested inside one list item into a Python repr instead of a readable message.
        for step in steps or []:
            for value_field, matching_field in (
                ("url", "url_matching"),
                ("href", "href_matching"),
                ("text", "text_matching"),
            ):
                value = step.get(value_field)
                if step.get(matching_field) != "regex" or not isinstance(value, str):
                    continue
                try:
                    validate_regex(value)
                except QueryError as err:
                    raise serializers.ValidationError(str(err)) from err
        return steps

    def validate(self, attrs):
        instance = cast(Action, self.instance)
        exclude_args = {}
        if instance:
            include_args = {"team": instance.team}
            exclude_args = {"id": instance.pk}
        else:
            attrs["team_id"] = self.context["view"].team_id
            include_args = {"team_id": attrs["team_id"]}
        if attrs.get("pinned_at") == "":
            attrs["pinned_at"] = None

        # Check for empty name - this must come before uniqueness check
        name = attrs.get("name")
        if name is not None and not name.strip():
            raise serializers.ValidationError(
                {"name": "This field may not be blank."},
                code="blank",
            )

        if "name" in attrs:
            colliding_action_ids = list(
                Action.objects.filter(name=attrs["name"], deleted=False, **include_args)
                .exclude(**exclude_args)[:1]
                .values_list("id", flat=True)
            )
            if colliding_action_ids:
                raise serializers.ValidationError(
                    {"name": f"This project already has an action with this name, ID {colliding_action_ids[0]}"},
                    code="unique",
                )

        if "steps" in attrs:
            step_filters = [prop for step in attrs["steps"] for prop in (step.get("properties") or [])]
            denied_table = table_blocking_property_filters(
                self.context["request"].user, self.context["get_team"](), step_filters
            )
            if denied_table:
                raise serializers.ValidationError(
                    {"steps": f"This filter uses the table '{denied_table}', which you don't have access to."},
                    code="permission_denied",
                )
            hidden_event = added_hidden_event(
                (step.get("event") for step in attrs["steps"]),
                instance.get_step_events() if instance else [],
            )
            if hidden_event and hides_flag_calls_from_query_builders(self.context["get_team"]().organization_id):
                raise serializers.ValidationError(
                    {"steps": f"You can't add a new step on {hidden_event}. {HIDDEN_EVENT_REASON}"},
                    code="hidden_event",
                )

        return attrs

    def create(self, validated_data: Any) -> Any:
        creation_context = self.context["request"].data.get("creation_context")
        validated_data["created_by"] = self.context["request"].user
        team = self.context["get_team"]()
        current_count = Action.objects.filter(team_id=team.id, deleted=False).count()
        check_count_limit(
            team=team,
            key=LimitKey.MAX_ACTIONS_PER_TEAM,
            current_count=current_count,
            user=self.context["request"].user,
        )
        instance = super().create(validated_data)

        report_user_action(
            validated_data["created_by"],
            "action created",
            {**instance.get_analytics_metadata(), "creation_context": creation_context},
            team=instance.team,
            request=self.context["request"],
        )

        return instance

    def update(self, instance: Any, validated_data: dict[str, Any]) -> Any:
        if validated_data.get("pinned_at"):
            if instance.pinned_at:
                # drop it from the update
                del validated_data["pinned_at"]
            else:
                # ignore the user-provided timestamp, generate our own
                validated_data["pinned_at"] = datetime.now(UTC).isoformat()

        instance = super().update(instance, validated_data)

        report_user_action(
            self.context["request"].user,
            "action updated",
            {
                **instance.get_analytics_metadata(),
                "updated_by_creator": self.context["request"].user == instance.created_by,
            },
            team=instance.team,
            request=self.context["request"],
        )
        return instance


class ActionReferenceSerializer(serializers.Serializer):
    type = serializers.CharField(help_text="Resource type: insight, experiment, cohort, or hog_function")
    id = serializers.CharField(help_text="Resource ID (integer or UUID depending on type)")
    name = serializers.CharField(help_text="Resource name")
    url = serializers.CharField(help_text="Relative URL to the resource")
    created_at = serializers.DateTimeField(help_text="When the resource was created", allow_null=True)
    created_by = UserBasicSerializer(help_text="User who created the resource", allow_null=True)


class ActionSelectorMatchChangesQuerySerializer(serializers.Serializer):
    action_ids = serializers.ListField(
        child=serializers.IntegerField(min_value=1),
        allow_empty=False,
        max_length=100,
        help_text="Action IDs used by the insight whose selector changes should be returned.",
    )


class ActionSelectorMatchChangeSerializer(serializers.Serializer):
    action_id = serializers.IntegerField(help_text="ID of an affected action.")
    action_name = serializers.CharField(
        allow_null=True,
        help_text="Name of the affected action, or null when it has no name.",
    )
    selectors = serializers.ListField(
        child=serializers.CharField(),
        help_text="CSS selectors whose matching behavior changed, in action step order.",
    )


def find_action_references(action_id: int, team: Team) -> list[dict[str, Any]]:
    """Find resources that reference a given action using database-level jsonb_path queries."""
    refs: list[dict[str, Any]] = []
    vars_json = json.dumps({"id": action_id, "id_str": str(action_id)})
    cap = 50

    # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
    insights = (
        Insight.objects.filter(team_id=team.pk, deleted=False)
        .select_related("created_by")
        .extra(
            where=[
                f"""
                jsonb_path_exists(query, '{ACTION_REFERENCE_JSONPATH}', %s::jsonb)
                OR jsonb_path_exists(filters, '{ACTION_REFERENCE_JSONPATH}', %s::jsonb)
                OR jsonb_path_exists(filters, '{ACTIONS_ARRAY_JSONPATH}', %s::jsonb)
                """
            ],
            params=[vars_json] * 3,
        )
    )
    for insight in insights[:cap]:
        refs.append(
            {
                "type": "insight",
                "id": str(insight.short_id),
                "name": insight.name or insight.derived_name or "Unnamed",
                "url": f"/insights/{insight.short_id}",
                "created_at": insight.created_at,
                "created_by": insight.created_by,
            }
        )

    remaining = cap - len(refs)
    if remaining <= 0:
        return refs

    for exp in experiments_referencing_action(team.pk, action_id, limit=remaining):
        refs.append(
            {
                "type": "experiment",
                "id": str(exp.id),
                "name": exp.name or "Unnamed",
                "url": f"/experiments/{exp.id}",
                "created_at": exp.created_at,
                "created_by": exp.created_by,
            }
        )

    remaining = cap - len(refs)
    if remaining <= 0:
        return refs

    # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
    cohorts = (
        Cohort.objects.filter(team__project_id=team.project_id, deleted=False)
        .select_related("created_by")
        .extra(
            where=[
                """
                jsonb_path_exists(filters, '$.** ? (@.event_type == "actions" && (@.key == $id || @.key == $id_str))', %s::jsonb)
                OR jsonb_path_exists(filters, '$.** ? (@.seq_event_type == "actions" && (@.seq_event == $id || @.seq_event == $id_str))', %s::jsonb)
                """
            ],
            params=[vars_json] * 2,
        )
    )
    for cohort in cohorts[:remaining]:
        refs.append(
            {
                "type": "cohort",
                "id": str(cohort.id),
                "name": cohort.name or "Unnamed",
                "url": f"/cohorts/{cohort.id}",
                "created_at": cohort.created_at,
                "created_by": cohort.created_by,
            }
        )

    remaining = cap - len(refs)
    if remaining <= 0:
        return refs

    # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
    hog_functions = (
        HogFunction.objects.filter(team_id=team.pk, deleted=False)
        .select_related("created_by")
        .extra(
            where=[f"jsonb_path_exists(filters, '{ACTIONS_ARRAY_JSONPATH}', %s::jsonb)"],
            params=[vars_json],
        )
    )
    for hf in hog_functions[:remaining]:
        refs.append(
            {
                "type": "hog_function",
                "id": str(hf.id),
                "name": hf.name or "Unnamed",
                "url": f"/functions/{hf.id}",
                "created_at": hf.created_at,
                "created_by": hf.created_by,
            }
        )

    return refs


def count_action_references_bulk(action_ids: list[int], team: Team) -> dict[int, int]:
    """Count references for multiple actions in bulk using the same jsonb_path patterns as find_action_references."""
    if not action_ids:
        return {}

    counts: Counter[int] = Counter()
    ids_array = list(action_ids)

    insight_table = Insight._meta.db_table
    cohort_table = Cohort._meta.db_table
    team_table = Team._meta.db_table
    hf_table = HogFunction._meta.db_table

    # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (parameterized via %s)
    with connection.cursor() as cursor:
        cursor.execute(
            f"""
            SELECT aid, count(*) FROM unnest(%s::int[]) AS aid
            CROSS JOIN LATERAL (
                SELECT 1 FROM {insight_table}
                WHERE team_id = %s AND NOT deleted
                AND (
                    jsonb_path_exists(query, '{ACTION_REFERENCE_JSONPATH}', jsonb_build_object('id', aid, 'id_str', aid::text))
                    OR jsonb_path_exists(filters, '{ACTION_REFERENCE_JSONPATH}', jsonb_build_object('id', aid, 'id_str', aid::text))
                    OR jsonb_path_exists(filters, '{ACTIONS_ARRAY_JSONPATH}', jsonb_build_object('id', aid, 'id_str', aid::text))
                )
            ) AS matched
            GROUP BY aid
            """,
            [ids_array, team.pk],
        )
        for aid, cnt in cursor.fetchall():
            counts[aid] += cnt

    counts.update(count_experiments_referencing_actions(team.pk, ids_array))

    # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (parameterized via %s)
    with connection.cursor() as cursor:
        cursor.execute(
            f"""
            SELECT aid, count(*) FROM unnest(%s::int[]) AS aid
            CROSS JOIN LATERAL (
                SELECT 1 FROM {cohort_table}
                WHERE team_id IN (SELECT id FROM {team_table} WHERE project_id = %s) AND NOT deleted
                AND (
                    jsonb_path_exists(filters, '$.** ? (@.event_type == "actions" && (@.key == $id || @.key == $id_str))', jsonb_build_object('id', aid, 'id_str', aid::text))
                    OR jsonb_path_exists(filters, '$.** ? (@.seq_event_type == "actions" && (@.seq_event == $id || @.seq_event == $id_str))', jsonb_build_object('id', aid, 'id_str', aid::text))
                )
            ) AS matched
            GROUP BY aid
            """,
            [ids_array, team.project_id],
        )
        for aid, cnt in cursor.fetchall():
            counts[aid] += cnt

    # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (parameterized via %s)
    with connection.cursor() as cursor:
        cursor.execute(
            f"""
            SELECT aid, count(*) FROM unnest(%s::int[]) AS aid
            CROSS JOIN LATERAL (
                SELECT 1 FROM {hf_table}
                WHERE team_id = %s AND NOT deleted
                AND jsonb_path_exists(filters, '{ACTIONS_ARRAY_JSONPATH}', jsonb_build_object('id', aid, 'id_str', aid::text))
            ) AS matched
            GROUP BY aid
            """,
            [ids_array, team.pk],
        )
        for aid, cnt in cursor.fetchall():
            counts[aid] += cnt

    return dict(counts)


class ActionListPagingQuerySerializer(serializers.Serializer):
    limit = serializers.IntegerField(
        required=False, min_value=0, help_text="Maximum number of actions to return. Omit to return all."
    )
    offset = serializers.IntegerField(
        required=False, default=0, min_value=0, help_text="Number of actions to skip before returning results."
    )


@extend_schema_serializer(many=False)
class ActionListResponseSerializer(serializers.Serializer):
    count = serializers.IntegerField(
        help_text="Number of actions that match the filters. Without `limit`, it is `offset` plus the number of actions returned."
    )
    results = ActionSerializer(many=True, help_text="Actions on this page, or every matching action without `limit`.")


class ActionViewSet(
    TeamAndOrgViewSetMixin,
    AccessControlViewSetMixin,
    TaggedItemViewSetMixin,
    ForbidDestroyModel,
    viewsets.ModelViewSet,
):
    scope_object = "action"
    renderer_classes = cast(
        tuple[type[BaseRenderer], ...],
        (*tuple(api_settings.DEFAULT_RENDERER_CLASSES), csvrenderers.PaginatedCSVRenderer),
    )
    queryset = Action.objects.select_related("created_by").all()
    serializer_class = ActionSerializer
    ordering = ["-last_calculated_at", "name"]

    def safely_get_queryset(self, queryset):
        if self.action == "list":
            queryset = queryset.filter(deleted=False)

        queryset = queryset.annotate(count=Count(TREND_FILTER_TYPE_EVENTS))
        return queryset.filter(team_id=self.team_id).order_by(*self.ordering)

    @extend_schema(
        parameters=[
            OpenApiParameter(
                "action_ids",
                OpenApiTypes.INT,
                location=OpenApiParameter.QUERY,
                required=True,
                many=True,
                description="Action IDs used by the insight. Accepts repeated or comma-separated values.",
            )
        ],
        responses={200: ActionSelectorMatchChangeSerializer(many=True)},
    )
    @drf_action(methods=["GET"], detail=False, required_scopes=["action:read"], pagination_class=None)
    def selector_match_changes(self, request: request.Request, **kwargs: Any) -> Response:
        raw_action_ids = [
            part.strip()
            for value in request.query_params.getlist("action_ids")
            for part in value.split(",")
            if part.strip()
        ]
        query = ActionSelectorMatchChangesQuerySerializer(data={"action_ids": raw_action_ids})
        query.is_valid(raise_exception=True)
        action_ids = list(dict.fromkeys(query.validated_data["action_ids"]))

        visible_actions = self.user_access_control.filter_queryset_by_access_level(
            Action.objects.filter(team_id=self.team_id, id__in=action_ids, deleted=False),
            resource="action",
        )
        actions_by_id = {action.id: action for action in visible_actions}
        selectors_by_action: dict[int, list[str]] = defaultdict(list)
        stored_changes = (
            ActionSelectorMatchChange.objects.for_team(self.team_id)
            .filter(action_id__in=actions_by_id)
            .order_by("action_id", "step_index")
        )
        for change in stored_changes:
            if change.describes(actions_by_id[change.action_id]):
                selectors_by_action[change.action_id].append(change.selector)

        changes = [
            {
                "action_id": action_id,
                "action_name": actions_by_id[action_id].name,
                "selectors": selectors,
            }
            for action_id, selectors in sorted(selectors_by_action.items())
        ]
        return Response(ActionSelectorMatchChangeSerializer(changes, many=True).data)

    @extend_schema(responses={200: ActionReferenceSerializer(many=True)})
    @drf_action(methods=["GET"], detail=True, required_scopes=["action:read"], pagination_class=None)
    def references(self, request: request.Request, **kwargs: Any) -> Response:
        action_obj = self.get_object()
        refs = find_action_references(action_obj.id, action_obj.team)
        return Response(ActionReferenceSerializer(refs, many=True).data)

    _ORDERING_WHITELIST = {"name", "created_at", "pinned_at", "created_by"}

    def _ordering_from_request(self, request: request.Request) -> list[str] | None:
        raw = request.query_params.get("ordering")
        if not raw:
            return None
        field = raw.lstrip("-")
        if field not in self._ORDERING_WHITELIST:
            return None
        prefix = "-" if raw.startswith("-") else ""
        # created_by is a FK, so sort by the creator's full name rather than the raw id.
        ordering: list[str]
        if field == "created_by":
            ordering = [f"{prefix}created_by__first_name", f"{prefix}created_by__last_name"]
        else:
            ordering = [f"{prefix}{field}"]
        if field != "name":
            ordering.append("name")  # stable tiebreak within equal values
        return ordering

    @extend_schema(
        parameters=[
            OpenApiParameter(
                "limit", OpenApiTypes.INT, description="Maximum number of actions to return. Omit to return all."
            ),
            OpenApiParameter(
                "offset", OpenApiTypes.INT, description="Number of actions to skip before returning results."
            ),
            OpenApiParameter(
                "search", OpenApiTypes.STR, description="Case-insensitive substring match on the action name."
            ),
            OpenApiParameter(
                "created_by",
                OpenApiTypes.STR,
                description="Comma-separated list of creator user ids. Returns only actions created by these users.",
            ),
            OpenApiParameter(
                "tags",
                OpenApiTypes.STR,
                description='JSON-encoded array of tag names, e.g. ["billing","beta"]. Returns actions having any of these tags.',
            ),
            OpenApiParameter(
                "ordering",
                OpenApiTypes.STR,
                description="Field to order by (name, created_at, pinned_at, created_by). Prefix with '-' for descending.",
            ),
        ],
        responses={200: ActionListResponseSerializer(many=False)},
    )
    def list(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:
        # :HACKY: we need to override this viewset method until actions support
        # better pagination in the taxonomic filter and on the actions page.
        #
        # `limit`/`offset`/`search`/`created_by`/`tags`/`ordering` are opt-in: with
        # no params we still return the full, ordered list so the taxonomic filter
        # and other in-memory consumers of the shared actions list keep working
        # unchanged. The actions page and API/MCP consumers pass them to avoid
        # pulling every action at once (a project can have thousands), which
        # otherwise overflows the context window of LLM clients calling the
        # `actions-get-all` MCP tool.
        actions = self.filter_queryset(self.get_queryset())

        search = request.query_params.get("search")
        if search:
            actions = actions.filter(name__icontains=search)

        created_by = request.query_params.get("created_by")
        if created_by:
            creator_ids = [int(v) for v in created_by.split(",") if v.strip().isdigit()]
            if creator_ids:
                actions = actions.filter(created_by_id__in=creator_ids)

        tags = request.query_params.get("tags")
        if tags:
            try:
                tags_list = json.loads(tags)
            except (json.JSONDecodeError, TypeError):
                tags_list = None
            if tags_list:
                actions = actions.filter(tagged_items__tag__name__in=tags_list).distinct()

        ordering = self._ordering_from_request(request)
        if ordering:
            actions = actions.order_by(*ordering)

        paging = ActionListPagingQuerySerializer(data=request.query_params)
        paging.is_valid(raise_exception=True)
        offset: int = paging.validated_data["offset"]
        limit: int | None = paging.validated_data.get("limit")
        # Only pay for a COUNT query when actually paginating. The full-list default
        # (no `limit`) is a hot path shared with the taxonomic filter, so we derive the
        # count from the serialized results there instead of hitting the DB again.
        count = actions.count() if limit is not None else None
        if limit is not None:
            actions = actions[offset : offset + limit]
        elif offset:
            actions = actions[offset:]

        actions_list: list[dict[Any, Any]] = self.serializer_class(
            actions, many=True, context={"request": request, "view": self}
        ).data  # type: ignore

        if request.query_params.get("include_reference_count"):
            action_ids = [a["id"] for a in actions_list]
            ref_counts = count_action_references_bulk(action_ids, self.team)
            for a in actions_list:
                a["reference_count"] = ref_counts.get(a["id"], 0)

        if count is None:
            count = offset + len(actions_list)

        return Response({"count": count, "results": actions_list})