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.

feat(replay-vision): migrate legacy vision actions onto alerts and scouts (#90182)

Tue Haulunde1dfacacc0e9
diff --git a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
index 0aca07e729c0..862343296e0b 100644
--- a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
+++ b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
@@ -61,6 +61,8 @@ rules:
# Migrations mutate historical models from apps.get_model, so they
# cannot call the state machine.
- '/products/replay_vision/backend/migrations/**'
+ # Retires legacy VisionAction rows, which have no state machine to route through.
+ - '/products/replay_vision/backend/management/commands/migrate_vision_actions.py'
- id: billing-alert-state-direct-mutation
patterns:
diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.py
index b8f82ab2a49e..8d6fd5b4d7c7 100644
--- a/products/feature_flags/backend/facade/api.py
+++ b/products/feature_flags/backend/facade/api.py
@@ -287,3 +287,33 @@ def serialize_flags(flags: Any, *, context: dict) -> Any:
access-control-derived fields, so it can only be built for a real request.
"""
return FeatureFlagSerializer(flags, many=True, context=context).data
+
+
+def add_group_to_flag_targeting(*, team: Team, key: str, group_key: str) -> bool:
+ """Add one group key to a flag's group-targeting condition, for a product rolling itself out.
+
+ A product that migrates its own data organization by organization needs to widen the flag as
+ each one lands, and it should not have to know how release conditions are stored to do it.
+ Returns False when no such flag exists on the team, or when its conditions carry no
+ `$group_key` filter to widen — both mean the caller's rollout assumption no longer holds, so
+ they are reported rather than silently repaired.
+ """
+ flag = FeatureFlag.objects.filter(team=team, key=key, deleted=False).first()
+ if flag is None:
+ return False
+ conditions = [
+ prop
+ for group in (flag.filters or {}).get("groups") or []
+ for prop in group.get("properties", [])
+ if prop.get("key") == "$group_key"
+ ]
+ if not conditions:
+ return False
+ condition = conditions[0]
+ values = condition.get("value")
+ if not isinstance(values, list):
+ return False
+ if group_key not in values:
+ values.append(group_key)
+ flag.save(update_fields=["filters"])
+ return True
diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.py
index bb1a71b9d223..561325752374 100644
--- a/products/replay_vision/backend/api/vision_actions.py
+++ b/products/replay_vision/backend/api/vision_actions.py
@@ -1,4 +1,5 @@
import uuid
+from functools import cached_property
from typing import Any, NoReturn, cast, get_args
from urllib.parse import urlparse
@@ -27,11 +28,17 @@ from rest_framework.serializers import BaseSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import UserBasicSerializer
+from posthog.models import User
from posthog.models.integration import Integration
+from products.replay_vision.backend.api import vision_actions_shim
from products.replay_vision.backend.api.delivery import archive_delivery, provision_delivery
from products.replay_vision.backend.api.errors import ReplayVisionErrorSerializer
from products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_process_vision_action_workflow
+from products.replay_vision.backend.api.vision_actions_shim import (
+ MAX_ENABLED_ALERTS_PER_SCANNER,
+ redact_webhook_url as _redact_webhook_url,
+)
from products.replay_vision.backend.digest import digest_name_for_scanner, unique_digest_name
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
@@ -49,6 +56,7 @@ from products.replay_vision.backend.rrule import validate_rrule, validate_timezo
from products.replay_vision.backend.scanner_access import readable_scanner_ids, selection_target_ids
from products.replay_vision.backend.scanner_config import acting_user
from products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdict
+from products.signals.backend.scout_harness.views import ScoutCanonicalTeamAccessPermission
logger = structlog.get_logger(__name__)
@@ -239,26 +247,12 @@ class DeliveryTargetSerializer(serializers.Serializer):
# Alerts ride the scanner's sweep, so each enabled alert adds evaluation work to every sweep tick —
# cap the fan-out one scanner can accumulate.
-MAX_ENABLED_ALERTS_PER_SCANNER = 10
# Each delivery target provisions one enabled HogFunction that POSTs to its destination on every run,
# so cap the list to stop a single action from being turned into a webhook fan-out to many hosts.
MAX_DELIVERY_TARGETS = 5
-def _redact_webhook_url(url: str) -> str:
- # Show the scheme + host so a viewer can see *where* it delivers, but drop everything a credential
- # can hide in: the path, the query, AND any `user:pass@` userinfo (which `netloc` would carry, so
- # rebuild the authority from hostname/port only). IPv6 hosts keep their brackets. Falls back to a
- # fully-opaque marker if the URL can't be parsed.
- parsed = urlparse(url)
- if parsed.scheme and parsed.hostname:
- host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
- authority = f"{host}:{parsed.port}" if parsed.port else host
- return f"{parsed.scheme}://{authority}/…"
- return "(hidden)"
-
-
class VisionActionSerializer(serializers.ModelSerializer):
"""A Replay Vision action: a scheduled "and then…" automation over a scanner's observations."""
@@ -510,6 +504,9 @@ class VisionActionSerializer(serializers.ModelSerializer):
duplicates = VisionAction.objects.for_team(team.id).filter(name=name)
if self.instance is not None:
duplicates = duplicates.exclude(pk=self.instance.pk)
+ # A migrated row is invisible to every read path, so holding its name against a new one
+ # rejects a name nothing shows the caller.
+ duplicates = vision_actions_shim.unmigrated(duplicates)
if duplicates.exists():
raise serializers.ValidationError({"name": "An action with this name already exists in this team."})
@@ -641,7 +638,13 @@ class RunActionResponseSerializer(serializers.Serializer):
)
)
class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- """CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations."""
+ """CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+
+ Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ rows anymore. The runs endpoints keep serving the pre-migration run history.
+ """
# Deliberately NOT an AccessControlViewSetMixin: vision_action inherits its access level
# from replay_scanner (see RESOURCE_INHERITANCE_MAP) so the product is configured via a
@@ -669,8 +672,132 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"session_recording", required_level="viewer"
):
raise PermissionDenied("Configuring a Replay Vision action requires session_recording read access.")
+ if self._serves_new_systems:
+ # One gate for every shim-served action: scouts canonicalize to the parent team, so a
+ # key scoped only to a child environment must not reach them through this surface.
+ self._require_canonical_team_access()
+
+ def _accessible_scanner_ids(self) -> list[str]:
+ scanners = self.user_access_control.filter_queryset_by_access_level(
+ ReplayScanner.objects.filter(team_id=self.team_id)
+ )
+ return [str(scanner_id) for scanner_id in scanners.values_list("id", flat=True)]
+
+ def _shim_entities(self) -> list[tuple[str, Any]]:
+ """The entities this request operates on, resolved and authorized exactly once.
+
+ `get_object()` runs the resolution through `safely_get_object` below, so every shim-served
+ write acts on the objects that were checked. Resolving separately for the check and for
+ the write is what once left a fanned-out alert's later successors unchecked.
+ """
+ self.get_object()
+ return self._resolved_entries
+
+ def _can_edit_scanner(self, scanner: ReplayScanner) -> bool:
+ return self.user_access_control.check_access_level_for_object(scanner, required_level="editor")
+
+ def _validated_legacy_payload(self, request: Request, *, partial: bool) -> dict[str, Any]:
+ """Run the incoming payload through the legacy serializer without saving a legacy row.
+
+ This is what keeps the shim's writes as safe as the legacy path: the serializer team-scopes
+ `scanner`, checks Slack integrations belong to this team, rejects non-https and userinfo
+ webhook URLs, and applies the selection allowlist.
+ """
+ serializer = VisionActionSerializer(data=request.data, partial=partial, context=self.get_serializer_context())
+ serializer.is_valid(raise_exception=True)
+ return dict(serializer.validated_data)
+
+ def _require_canonical_team_access(self) -> None:
+ """Scouts canonicalize to the parent team, so authorize against the team that owns them.
+
+ The shim reads and writes scouts on `team.parent_team or team`, while this viewset's
+ default gate only checks the URL team. Without this, a key scoped solely to a child
+ environment is authorized against one team while touching another's rows. The native
+ scout endpoints carry the same permission for the same reason.
+ """
+ permission = ScoutCanonicalTeamAccessPermission()
+ if not permission.has_permission(self.request, self):
+ raise PermissionDenied(permission.message)
+
+ @cached_property
+ def _serves_new_systems(self) -> bool:
+ # One switch for the whole surface, shared with the UI: while the org is flagged onto the
+ # new alerts product, the legacy contract is served from the new systems.
+ from posthog.ph_client import (
+ feature_enabled_or_false, # noqa: PLC0415 — keeps the analytics client off the import path
+ )
+
+ user = self.request.user
+ return feature_enabled_or_false(
+ "replay-vision-alerts",
+ getattr(user, "distinct_id", str(getattr(user, "id", "server"))),
+ groups={"organization": str(self.team.organization_id)},
+ send_feature_flag_events=False,
+ )
+
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ if not self._serves_new_systems:
+ return super().list(request, *args, **kwargs)
+ scanner_ids = self._accessible_scanner_ids()
+ requested = request.query_params.get("scanner")
+ if requested:
+ scanner_ids = [scanner_id for scanner_id in scanner_ids if scanner_id == requested]
+ editable = {
+ scanner_id
+ for scanner_id in scanner_ids
+ if self._can_edit_scanner(ReplayScanner(id=scanner_id, team_id=self.team_id))
+ }
+ actions = vision_actions_shim.list_actions(self.team, scanner_ids, editable_scanner_ids=editable)
+ return Response({"count": len(actions), "next": None, "previous": None, "results": actions})
+
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ if not self._serves_new_systems:
+ return super().retrieve(request, *args, **kwargs)
+ entries = self._shim_entities()
+ return Response(
+ vision_actions_shim.render_entity(entries[0], can_edit=self._can_edit_scanner(self._resolved_scanner))
+ )
- def safely_get_object(self, queryset: QuerySet[VisionAction]) -> VisionAction:
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ if not self._serves_new_systems:
+ return super().create(request, *args, **kwargs)
+ validated = self._validated_legacy_payload(request, partial=False)
+ # Same object-level check `perform_create` makes, against the scanner the payload names and
+ # every scanner its selection reads from.
+ _check_action_scanner_access(self, validated["scanner"], validated.get("selection"))
+ return Response(vision_actions_shim.create_action(self.team, cast(User, request.user), validated), status=201)
+
+ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ if not self._serves_new_systems:
+ return super().partial_update(request, *args, **kwargs)
+ entries = self._shim_entities()
+ validated = self._validated_legacy_payload(request, partial=True)
+ if "scanner" in validated:
+ _check_action_scanner_access(self, validated["scanner"], validated.get("selection"))
+ return Response(vision_actions_shim.update_action(self.team, entries, validated, cast(User, request.user)))
+
+ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ if not self._serves_new_systems:
+ return super().destroy(request, *args, **kwargs)
+ vision_actions_shim.destroy_action(self.team, self._shim_entities())
+ return Response(status=204)
+
+ def safely_get_object(self, queryset: QuerySet[VisionAction]) -> Any:
+ if self._serves_new_systems:
+ entries = vision_actions_shim.resolve_entities(self.team, str(self.kwargs["pk"]))
+ if not entries:
+ raise NotFound()
+ scanner_ids = vision_actions_shim.scanner_ids_for_entities(entries)
+ scanners = list(ReplayScanner.objects.filter(team_id=self.team_id, id__in=scanner_ids))
+ if len(scanners) != len(scanner_ids):
+ raise NotFound()
+ for scanner in scanners:
+ _check_action_scanner_access(self, scanner, None)
+ self._resolved_entries = entries
+ self._resolved_scanner = scanners[0]
+ # The scanner is what access is inherited from, so it is also the right object for the
+ # base `get_object` to run `check_object_permissions` against.
+ return scanners[0]
action = get_object_or_404(queryset, pk=self.kwargs["pk"])
# Per-scanner object-level grants are stored against `replay_scanner` + the scanner's id, not
# `vision_action` + the action's id — the generic check_object_permissions() call the base
@@ -765,6 +892,11 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""Run this summary now, without waiting for its schedule — synthesizes a group summary over the
observations since the last summary (or the last 24h). The recurring schedule is untouched: the
engine advances next_run_at only at scheduled claim time, never in the run itself."""
+ if self._serves_new_systems:
+ # safely_get_object returns the scanner in shim mode, and there is no legacy run to
+ # start: scouts run on their own schedule and from the scout surface.
+ self.get_object()
+ raise ValidationError("On-demand runs moved to the scout that replaced this summary.")
# get_object() runs safely_get_object, which object-checks the bound scanner's access.
action_obj = self.get_object()
# The summary reads recording-derived observations and delivers off-platform, so require
diff --git a/products/replay_vision/backend/api/vision_actions_shim.py b/products/replay_vision/backend/api/vision_actions_shim.py
new file mode 100644
index 000000000000..cc6caafd0179
--- /dev/null
+++ b/products/replay_vision/backend/api/vision_actions_shim.py
@@ -0,0 +1,706 @@
+"""Serve the legacy vision-actions API surface from the new alerts and scouts systems.
+
+Once an organization is on the `replay-vision-alerts` flag, the legacy endpoints stop touching
+`VisionAction` rows: creates become alerts or scouts, reads synthesize legacy-shaped responses
+from the new entities, and updates and deletes resolve ids across all three id spaces (new alert
+uuids, scout config ids, and migrated legacy row ids via their `migrated_to` stamps). Existing
+MCP and agent callers keep their contract without knowing anything moved.
+"""
+
+import re
+import uuid
+from types import SimpleNamespace
+from typing import Any, cast
+from urllib.parse import urlparse
+
+from django.db import transaction
+from django.utils import timezone
+
+from rest_framework.exceptions import NotFound, ValidationError
+
+from posthog.api.shared import UserBasicSerializer
+from posthog.models import Team, User
+
+from products.alerts.backend.destination_configs import AlertDestinationData, DestinationType
+from products.alerts.backend.destinations import owned_alert_destinations_qs
+from products.alerts.backend.facade.api import (
+ build_alert_destination_config,
+ create_alert_destination_hog_functions,
+ soft_delete_all_alert_destinations,
+)
+from products.alerts.backend.state_machine import apply_disable, apply_enable, apply_threshold_change
+from products.replay_vision.backend.alert_destinations import (
+ EVENT_KIND_CONFIG,
+ MATCH_EVENT_KINDS,
+ METRIC_EVENT_KINDS,
+ VISION_ALERT_EVENT_IDS,
+ VISION_ALERT_SLACK_CONTEXT_ELEMENTS,
+)
+from products.replay_vision.backend.alert_state_machine import apply_outcome
+from products.replay_vision.backend.models.vision_action import ActionMode, VisionAction
+from products.replay_vision.backend.models.vision_alert import (
+ VisionAlertConfiguration,
+ VisionAlertEvent,
+ VisionAlertKind,
+)
+from products.replay_vision.backend.scout_source import SCOUT_SOURCE_PRODUCT
+from products.signals.backend.facade import api as signals_facade
+from products.signals.backend.facade.api import ScoutSummary
+
+MAX_ENABLED_ALERTS_PER_SCANNER = 10
+
+_CRON_DAY_TO_RRULE = {"0": "SU", "1": "MO", "2": "TU", "3": "WE", "4": "TH", "5": "FR", "6": "SA", "7": "SU"}
+
+
+def redact_webhook_url(url: str) -> str:
+ # Show the scheme + host so a viewer can see *where* it delivers, but drop everything a credential
+ # can hide in: the path, the query, AND any `user:pass@` userinfo (which `netloc` would carry, so
+ # rebuild the authority from hostname/port only). IPv6 hosts keep their brackets. Falls back to a
+ # fully-opaque marker if the URL can't be parsed.
+ parsed = urlparse(url)
+ if parsed.scheme and parsed.hostname:
+ host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
+ authority = f"{host}:{parsed.port}" if parsed.port else host
+ return f"{parsed.scheme}://{authority}/…"
+ return "(hidden)"
+
+
+def unmigrated(queryset: Any) -> Any:
+ """Legacy rows the migration has not moved.
+
+ A migrated row is disabled and its successor is live, so listing it invites someone to
+ re-enable it, which re-arms the legacy sweep and its destinations alongside the new alert.
+ """
+ return (
+ queryset.exclude(alert_config__has_key="migrated_to")
+ .exclude(synthesis_config__has_key="migrated_to")
+ .exclude(synthesis_config__has_key="retired")
+ )
+
+
+def _is_uuid(value: str) -> bool:
+ try:
+ uuid.UUID(str(value))
+ except (ValueError, AttributeError, TypeError):
+ return False
+ return True
+
+
+def _user_basic(user_id: int | None) -> dict[str, Any] | None:
+ """The legacy surface rendered `created_by` through UserBasicSerializer, not as a bare id."""
+ if user_id is None:
+ return None
+ user = User.objects.filter(id=user_id).first()
+ return UserBasicSerializer(user).data if user is not None else None
+
+
+_DAY_TO_CRON = {"SU": 0, "MO": 1, "TU": 2, "WE": 3, "TH": 4, "FR": 5, "SA": 6}
+
+
+def _parse_rrule(rrule: str) -> dict[str, str]:
+ return dict(part.split("=", 1) for part in rrule.split(";") if "=" in part)
+
+
+def rrule_to_cron(rrule: str) -> str:
+ """Convert the legacy schedule rrules seen in production to cron.
+
+ Covers FREQ=DAILY/WEEKLY(+BYDAY)+BYHOUR/BYMINUTE, FREQ=HOURLY, and FREQ=MINUTELY;INTERVAL=n.
+ Anything else raises so the caller can surface it instead of storing a wrong schedule.
+ """
+ parts = _parse_rrule(rrule)
+ freq = parts.get("FREQ")
+ minute = parts.get("BYMINUTE", "0")
+ hour = parts.get("BYHOUR", "8")
+ if freq == "MINUTELY":
+ interval = int(parts.get("INTERVAL", "15"))
+ return f"*/{max(interval, 15)} * * * *"
+ if freq == "HOURLY":
+ return "0 * * * *"
+ if freq == "DAILY":
+ if parts.get("INTERVAL", "1") != "1":
+ raise ValueError(f"Cron cannot express a multi-day interval: {rrule}")
+ return f"{minute} {hour} * * *"
+ if freq == "WEEKLY":
+ # cron repeats every week, so an INTERVAL would silently double the cadence.
+ if parts.get("INTERVAL", "1") != "1":
+ raise ValueError(f"Cron cannot express a multi-week interval: {rrule}")
+ days = parts.get("BYDAY")
+ if not days:
+ return f"{minute} {hour} * * 1"
+ tokens = days.split(",")
+ # rrule accepts ordinal tokens like 1MO ("first Monday"); cron has no equivalent.
+ unknown = [token for token in tokens if token not in _DAY_TO_CRON]
+ if unknown:
+ raise ValueError(f"Unsupported BYDAY token(s) {unknown} in rrule: {rrule}")
+ return f"{minute} {hour} * * {','.join(str(_DAY_TO_CRON[token]) for token in tokens)}"
+ raise ValueError(f"Unsupported rrule: {rrule}")
+
+
+def compose_scout_body(
+ name: str, scanner_name: str, selection: dict[str, Any], synthesis_config: dict[str, Any]
+) -> str:
+ lines = [
+ f'You are producing the recurring digest previously configured as "{name}" for the scanner "{scanner_name}".',
+ "",
+ "Summarize the scanner's new observations since the previous report.",
+ ]
+ filters: list[str] = []
+ if selection.get("verdict"):
+ verdicts = selection["verdict"] if isinstance(selection["verdict"], list) else [selection["verdict"]]
+ filters.append(f"verdict in {verdicts}")
+ if selection.get("tags"):
+ filters.append(f"tags any of {selection['tags']}")
+ if selection.get("min_score") is not None:
+ filters.append(f"score >= {selection['min_score']}")
+ if selection.get("max_score") is not None:
+ filters.append(f"score <= {selection['max_score']}")
+ if filters:
+ lines += ["", "Only include observations matching: " + "; ".join(filters) + "."]
+ guide = synthesis_config.get("prompt_guide")
+ if guide:
+ lines += ["", "Follow this guidance from the digest's author:", "", str(guide)]
+ return "\n".join(lines)
+
+
+def cron_to_rrule(cron: str | None) -> str:
+ """Best-effort inverse of the migration's rrule->cron conversion, for representation only."""
+ if not cron:
+ return "FREQ=DAILY;BYHOUR=8;BYMINUTE=0"
+ parts = cron.split()
+ if len(parts) != 5:
+ return "FREQ=DAILY;BYHOUR=8;BYMINUTE=0"
+ minute, hour, _dom, _month, dow = parts
+ if minute.startswith("*/"):
+ return f"FREQ=MINUTELY;INTERVAL={minute[2:]}"
+ if hour == "*":
+ return "FREQ=HOURLY"
+ if dow == "*":
+ return f"FREQ=DAILY;BYHOUR={hour};BYMINUTE={minute}"
+ days = ",".join(_CRON_DAY_TO_RRULE.get(day, "MO") for day in dow.split(","))
+ return f"FREQ=WEEKLY;BYDAY={days};BYHOUR={hour};BYMINUTE={minute}"
+
+
+def _delivery_configs_for_alerts(
+ team_id: int, alert_ids: list[str], *, can_edit: bool
+) -> dict[str, list[dict[str, Any]]]:
+ """Delivery targets for many alerts in one query, keyed by alert id.
+
+ The list endpoint renders every alert on the team, so a per-alert query here is one round trip
+ per row.
+ """
+ by_alert: dict[str, list[dict[str, Any]]] = {alert_id: [] for alert_id in alert_ids}
+ if not alert_ids:
+ return by_alert
+ seen: set[tuple[Any, ...]] = set()
+ hog_functions = owned_alert_destinations_qs(
+ team_id=team_id, alert_ids=alert_ids, allowed_event_ids=VISION_ALERT_EVENT_IDS
+ ).filter(enabled=True)
+ for hog_function in hog_functions:
+ properties = (hog_function.filters or {}).get("properties") or []
+ alert_id = next((p.get("value") for p in properties if p.get("key") == "alert_id"), None)
+ if alert_id not in by_alert:
+ continue
+ target = _render_destination(hog_function, seen, can_edit=can_edit)
+ if target is not None:
+ by_alert[str(alert_id)].append(target)
+ return by_alert
+
+
+def _render_destination(hog_function: Any, seen: set[tuple[Any, ...]], *, can_edit: bool) -> dict[str, Any] | None:
+ """One legacy delivery target, or None when it duplicates one already rendered.
+
+ A webhook URL can carry a bearer token, so it stays redacted for readers without edit access,
+ the same bar the legacy representation applied.
+ """
+ inputs = hog_function.inputs or {}
+ template_id = hog_function.template_id or ""
+ if "slack" in template_id:
+ channel = (inputs.get("channel") or {}).get("value")
+ integration = (inputs.get("slack_workspace") or {}).get("value")
+ key = ("slack", integration, channel)
+ if not channel or key in seen:
+ return None
+ seen.add(key)
+ return {"type": "slack", "integration_id": integration, "channel": channel}
+ url = (inputs.get("url") or {}).get("value")
+ key = ("webhook", url, None)
+ if not url or key in seen:
+ return None
+ seen.add(key)
+ return {"type": "webhook", "url": url if can_edit else redact_webhook_url(url)}
+
+
+def _delivery_config_for_alert(alert: VisionAlertConfiguration, *, can_edit: bool = True) -> list[dict[str, Any]]:
+ return _delivery_configs_for_alerts(alert.team_id, [str(alert.id)], can_edit=can_edit)[str(alert.id)]
+
+
+def _scout_delivery_config(summary: ScoutSummary, *, can_edit: bool = True) -> list[dict[str, Any]]:
+ targets: list[dict[str, Any]] = []
+ destinations = summary.output_destinations or {}
+ slack = destinations.get("slack")
+ if slack:
+ channel = slack.get("channel_id", "")
+ name = slack.get("channel_name")
+ targets.append(
+ {
+ "type": "slack",
+ "integration_id": slack.get("integration_id"),
+ "channel": f"{channel}|{name}" if name else channel,
+ }
+ )
+ webhook = destinations.get("webhook")
+ if webhook and webhook.get("url"):
+ url = webhook["url"]
+ targets.append({"type": "webhook", "url": url if can_edit else redact_webhook_url(url)})
+ return targets
+
+
+def render_alert_as_action(
+ alert: VisionAlertConfiguration, *, can_edit: bool = True, delivery_config: list[dict[str, Any]] | None = None
+) -> dict[str, Any]:
+ if alert.kind == VisionAlertKind.MATCH:
+ alert_config: dict[str, Any] = {"frequency": "every_match", "metric": alert.metric or "count"}
+ else:
+ alert_config = {
+ "frequency": "on_breach",
+ "metric": alert.metric,
+ "direction": alert.direction,
+ "threshold": alert.threshold,
+ "window_days": alert.window_days,
+ }
+ return {
+ "id": str(alert.id),
+ "name": alert.name,
+ "enabled": alert.enabled,
+ "mode": ActionMode.ALERT,
+ "is_scanner_digest": False,
+ "trigger_type": "schedule",
+ "trigger_config": {},
+ "scanner": str(alert.scanner_id),
+ "selection": alert.selection or {},
+ "synthesis_config": {},
+ "alert_config": alert_config,
+ "delivery_config": (
+ delivery_config if delivery_config is not None else _delivery_config_for_alert(alert, can_edit=can_edit)
+ ),
+ "hog_flow": None,
+ "next_run_at": alert.next_check_at.isoformat() if alert.next_check_at else None,
+ "last_run_at": alert.last_checked_at.isoformat() if alert.last_checked_at else None,
+ "created_at": alert.created_at.isoformat(),
+ "created_by": _user_basic(alert.created_by_id),
+ "updated_at": alert.updated_at.isoformat(),
+ }
+
+
+def render_scout_as_action(summary: ScoutSummary, *, can_edit: bool = True) -> dict[str, Any]:
+ return {
+ "id": summary.config_id,
+ "name": summary.skill_name,
+ "enabled": summary.enabled,
+ "mode": ActionMode.GROUP_SUMMARY,
+ "is_scanner_digest": False,
+ "trigger_type": "schedule",
+ "trigger_config": {"rrule": cron_to_rrule(summary.run_cron_schedule), "timezone": "UTC"},
+ "scanner": summary.source_id,
+ "selection": {},
+ "synthesis_config": {"prompt_guide": summary.description},
+ "alert_config": {},
+ "delivery_config": _scout_delivery_config(summary, can_edit=can_edit),
+ "hog_flow": None,
+ "next_run_at": None,
+ "last_run_at": summary.last_run_at.isoformat() if summary.last_run_at else None,
+ "created_at": summary.created_at.isoformat() if summary.created_at else None,
+ "created_by": _user_basic(summary.created_by_id),
+ "updated_at": None,
+ }
+
+
+def list_actions(
+ team: Team, scanner_ids: list[str], *, editable_scanner_ids: set[str] | None = None
+) -> list[dict[str, Any]]:
+ """Every alert and scout on the caller's accessible scanners, in the legacy shape.
+
+ `scanner_ids` is the caller's accessible set and `editable_scanner_ids` the subset they may
+ edit, both resolved by the viewset. An empty accessible set means nothing is visible, so the
+ surface stays closed rather than falling back to "all". Edit access is per scanner because a
+ resource-level editor can still hold an object-level restriction on one scanner, and that
+ scanner's webhook URLs must stay redacted for them.
+ """
+ editable = editable_scanner_ids if editable_scanner_ids is not None else set(scanner_ids)
+ if not scanner_ids:
+ return []
+ alerts = (
+ VisionAlertConfiguration.objects.for_team(team.id)
+ .filter(scanner_id__in=scanner_ids)
+ .select_related("scanner")
+ .order_by("created_at")
+ )
+ scouts = signals_facade.list_scouts_for_source(
+ (team.parent_team or team).id, SCOUT_SOURCE_PRODUCT, source_ids=scanner_ids
+ )
+ alert_rows = list(alerts)
+ deliveries = {
+ **_delivery_configs_for_alerts(
+ team.id, [str(a.id) for a in alert_rows if str(a.scanner_id) in editable], can_edit=True
+ ),
+ **_delivery_configs_for_alerts(
+ team.id, [str(a.id) for a in alert_rows if str(a.scanner_id) not in editable], can_edit=False
+ ),
+ }
+ return [
+ render_alert_as_action(
+ alert, can_edit=str(alert.scanner_id) in editable, delivery_config=deliveries.get(str(alert.id))
+ )
+ for alert in alert_rows
+ ] + [render_scout_as_action(scout, can_edit=str(scout.source_id) in editable) for scout in scouts]
+
+
+def _resolve(team: Team, pk: str) -> tuple[str, Any] | None:
+ """Resolve an id from any of the three id spaces to ('alert', obj) or ('scout', summary).
+
+ A digest's `migrated_to` stamp is its scout *name*, not a uuid, so every uuid-column lookup is
+ guarded — an unguarded filter raises on a name before the name lookup is ever reached.
+ """
+ if _is_uuid(pk):
+ alert = VisionAlertConfiguration.objects.for_team(team.id).filter(id=pk).first()
+ if alert is not None:
+ return ("alert", alert)
+ for scout in signals_facade.list_scouts_for_source((team.parent_team or team).id, SCOUT_SOURCE_PRODUCT):
+ if pk in (scout.config_id, scout.skill_name):
+ return ("scout", scout)
+ if not _is_uuid(pk):
+ return None
+ legacy = VisionAction.objects.for_team(team.id).filter(id=pk).first()
+ if legacy is None:
+ return None
+ stamps = (legacy.alert_config or {}) if legacy.mode == ActionMode.ALERT else (legacy.synthesis_config or {})
+ migrated = stamps.get("migrated_to")
+ if isinstance(migrated, list):
+ migrated = migrated[0] if migrated else None
+ return _resolve(team, str(migrated)) if migrated else None
+
+
+def resolve_entities(team: Team, pk: str) -> list[tuple[str, Any]]:
+ """Every entity an id stands for.
+
+ A legacy alert overriding `selection.scanner_ids` migrated into one alert per scanner, so its
+ id names all of them. Acting on only the first would leave the rest enabled.
+ """
+ if not _is_uuid(pk):
+ single = _resolve(team, pk)
+ return [single] if single else []
+ legacy = VisionAction.objects.for_team(team.id).filter(id=pk).first()
+ if legacy is not None:
+ stamps = (legacy.alert_config or {}) if legacy.mode == ActionMode.ALERT else (legacy.synthesis_config or {})
+ migrated = stamps.get("migrated_to")
+ if isinstance(migrated, list):
+ resolved = [_resolve(team, str(successor)) for successor in migrated]
+ return [entry for entry in resolved if entry is not None]
+ single = _resolve(team, pk)
+ return [single] if single else []
+
+
+def scanner_ids_for_entities(entries: list[tuple[str, Any]]) -> list[str]:
+ """Every scanner the given entities live on, so all of them can be object-checked.
+
+ Takes resolved entities rather than an id: authorizing a second resolution of the same id
+ would leave room for the check and the write to disagree, which is how a fanned-out alert
+ once had only its first successor checked.
+ """
+ ids: list[str] = []
+ for kind, entity in entries:
+ scanner_id = str(entity.scanner_id) if kind == "alert" else entity.source_id
+ if scanner_id and scanner_id not in ids:
+ ids.append(scanner_id)
+ return ids
+
+
+def render_entity(entry: tuple[str, Any], *, can_edit: bool = True) -> dict[str, Any]:
+ kind, entity = entry
+ if kind == "alert":
+ return render_alert_as_action(entity, can_edit=can_edit)
+ return render_scout_as_action(entity, can_edit=can_edit)
+
+
+def create_action(team: Team, user: User, data: dict[str, Any]) -> dict[str, Any]:
+ """Create the new-system entity a legacy create asks for.
+
+ `data` must be validated legacy payload — the viewset runs it through `VisionActionSerializer`
+ first, which is what team-scopes the scanner, checks integration ownership on Slack targets,
+ enforces https-only webhooks, and applies the selection allowlist. Nothing here re-derives
+ those, so callers must not hand it raw request data.
+ """
+ mode = data.get("mode", ActionMode.GROUP_SUMMARY)
+ if mode == ActionMode.ALERT:
+ return _create_alert(team, user, data)
+ if mode == ActionMode.GROUP_SUMMARY:
+ return _create_scout(team, user, data)
+ raise ValidationError({"mode": f"Unsupported mode {mode!r}."})
+
+
+def _validated_scanner_id(data: dict[str, Any]) -> str:
+ """The scanner from an already-validated payload, where it arrives as the model instance."""
+ scanner = data.get("scanner") or data.get("scanner_id")
+ if scanner is None:
+ raise ValidationError({"scanner": "This field is required."})
+ return str(getattr(scanner, "id", scanner))
+
+
+def _legacy_destination_data(entry: dict[str, Any]) -> "AlertDestinationData | None":
+ if entry.get("type") == "slack":
+ channel = str(entry.get("channel") or "")
+ channel_id, _, channel_name = channel.partition("|")
+ return cast(
+ "AlertDestinationData",
+ {
+ "type": DestinationType.SLACK,
+ "slack_workspace_id": entry.get("integration_id"),
+ "slack_channel_id": channel_id,
+ "slack_channel_name": channel_name or channel_id,
+ },
+ )
+ if entry.get("type") == "webhook" and entry.get("url"):
+ return cast("AlertDestinationData", {"type": DestinationType.WEBHOOK, "webhook_url": entry["url"]})
+ return None
+
+
+def _enforce_enabled_alert_cap(team: Team, scanner_id: str, *, exclude_id: str | None = None) -> None:
+ """The legacy serializer's per-scanner cap, counted on the table the shim actually writes.
+
+ `VisionActionSerializer._validate_alert_cap` counts VisionAction rows, and the shim creates
+ none, so the cap it enforces is vacuous here. Alerts evaluate on the scanner's sweep, so the
+ fan-out this bounds is real work.
+ """
+ others = VisionAlertConfiguration.objects.for_team(team.id).filter(scanner_id=scanner_id, enabled=True)
+ if exclude_id is not None:
+ others = others.exclude(id=exclude_id)
+ if others.count() >= MAX_ENABLED_ALERTS_PER_SCANNER:
+ raise ValidationError(
+ {"enabled": f"A scanner can have at most {MAX_ENABLED_ALERTS_PER_SCANNER} enabled alerts."}
+ )
+
+
+def _create_alert(team: Team, user: User, data: dict[str, Any]) -> dict[str, Any]:
+ config = data.get("alert_config") or {}
+ frequency = config.get("frequency", "every_match")
+ scanner_id = _validated_scanner_id(data)
+ if data.get("enabled", True):
+ _enforce_enabled_alert_cap(team, scanner_id)
+ kwargs: dict[str, Any] = {
+ "team_id": team.id,
+ "scanner_id": scanner_id,
+ "name": data.get("name") or "Untitled alert",
+ "enabled": data.get("enabled", True),
+ "created_by": user,
+ "first_enabled_at": timezone.now(),
+ "selection": {
+ k: v for k, v in (data.get("selection") or {}).items() if k in ("verdict", "tags", "min_score", "max_score")
+ },
+ }
+ if frequency == "on_breach":
+ kwargs.update(
+ kind=VisionAlertKind.METRIC,
+ metric=config.get("metric", "count"),
+ direction=config.get("direction", "above"),
+ threshold=float(config.get("threshold", 1)),
+ window_days=int(config.get("window_days", 1)),
+ )
+ else:
+ kwargs.update(kind=VisionAlertKind.MATCH, threshold=None)
+ alert = VisionAlertConfiguration.objects.for_team(team.id).create(**kwargs)
+
+ _provision_alert_destinations(team, user, alert, data.get("delivery_config") or [])
+ return render_alert_as_action(alert)
+
+
+def _provision_alert_destinations(
+ team: Team, user: User, alert: VisionAlertConfiguration, entries: list[dict[str, Any]]
+) -> None:
+ kinds = MATCH_EVENT_KINDS if alert.kind == VisionAlertKind.MATCH else METRIC_EVENT_KINDS
+ for entry in entries:
+ destination = _legacy_destination_data(entry)
+ if destination is None:
+ continue
+ configs = [
+ build_alert_destination_config(
+ team=team,
+ spec=EVENT_KIND_CONFIG[kind],
+ alert_id=str(alert.id),
+ alert_name=alert.name,
+ data=destination,
+ slack_context_elements=VISION_ALERT_SLACK_CONTEXT_ELEMENTS,
+ )
+ for kind in kinds
+ ]
+ create_alert_destination_hog_functions(
+ configs,
+ request=SimpleNamespace(user=user),
+ alert_id=str(alert.id),
+ allowed_event_ids=VISION_ALERT_EVENT_IDS,
+ )
+
+
+def _scout_destinations_from_legacy(data: dict[str, Any]) -> dict[str, Any]:
+ destinations: dict[str, Any] = {}
+ for entry in data.get("delivery_config") or []:
+ if entry.get("type") == "slack" and "slack" not in destinations:
+ channel = str(entry.get("channel") or "")
+ channel_id, _, channel_name = channel.partition("|")
+ destinations["slack"] = {
+ "integration_id": entry.get("integration_id"),
+ "channel_id": channel_id,
+ "channel_name": channel_name or channel_id,
+ }
+ elif entry.get("type") == "webhook" and entry.get("url") and "webhook" not in destinations:
+ destinations["webhook"] = {"url": entry["url"]}
+ return destinations
+
+
+def _create_scout(team: Team, user: User, data: dict[str, Any]) -> dict[str, Any]:
+ scanner_id = _validated_scanner_id(data)
+ name = data.get("name") or "digest"
+ rrule = (data.get("trigger_config") or {}).get("rrule") or "FREQ=DAILY;BYHOUR=8;BYMINUTE=0"
+ try:
+ cron = rrule_to_cron(rrule)
+ except ValueError as error:
+ raise ValidationError({"trigger_config": str(error)})
+
+ slug = re.sub(r"[^a-z0-9-]+", "-", name.lower()).strip("-")[:34] or "digest"
+ scout_name = f"signals-scout-{slug}"
+ destinations = _scout_destinations_from_legacy(data)
+ result = signals_facade.create_scout_for_source(
+ team=team.parent_team or team,
+ user=user,
+ name=scout_name,
+ description=(data.get("synthesis_config") or {}).get("prompt_guide") or f'Replay Vision digest "{name}".',
+ body=compose_scout_body(name, str(scanner_id), data.get("selection") or {}, data.get("synthesis_config") or {}),
+ files=[],
+ config_options={
+ "enabled": data.get("enabled", True),
+ "run_cron_schedule": cron,
+ **({"output_destinations": destinations} if destinations else {}),
+ },
+ request=SimpleNamespace(user=user),
+ serializer_context={"project_id": team.project_id},
+ source_product=SCOUT_SOURCE_PRODUCT,
+ source_id=str(scanner_id),
+ )
+ created = resolve_entities(team, str(result.config.id))
+ if not created:
+ raise NotFound()
+ return render_entity(created[0])
+
+
+def update_action(team: Team, entries: list[tuple[str, Any]], data: dict[str, Any], user: User) -> dict[str, Any]:
+ rendered = [_update_one(team, kind, entity, data, user) for kind, entity in entries]
+ return rendered[0]
+
+
+def _update_one(team: Team, kind: str, entity: Any, data: dict[str, Any], user: User) -> dict[str, Any]:
+ if kind == "alert":
+ config = data.get("alert_config") or {}
+ frequency = config.get("frequency")
+ if frequency is not None:
+ wanted = VisionAlertKind.MATCH if frequency == "every_match" else VisionAlertKind.METRIC
+ if wanted != entity.kind:
+ # kind is immutable on an alert (the DB constraint pins match alerts stateless), so
+ # accepting the field and ignoring it would report a change that never happened.
+ raise ValidationError(
+ {"alert_config": "Cannot change an alert's frequency. Delete it and create a new one."}
+ )
+ if data.get("enabled") and not entity.enabled:
+ _enforce_enabled_alert_cap(team, str(entity.scanner_id), exclude_id=str(entity.id))
+ update_fields: list[str] = []
+ for key in ("name", "selection"):
+ if key in data:
+ setattr(entity, key, data[key])
+ update_fields.append(key)
+ threshold_changed = False
+ if config and entity.kind == VisionAlertKind.METRIC:
+ for key in ("metric", "direction", "threshold", "window_days"):
+ if key in config and config[key] != getattr(entity, key):
+ setattr(entity, key, config[key])
+ update_fields.append(key)
+ threshold_changed = True
+ enabled_change = data["enabled"] if "enabled" in data and data["enabled"] != entity.enabled else None
+ with transaction.atomic():
+ # Lifecycle fields belong to the state machine: setting `enabled` directly would leave a
+ # re-enabled alert still FIRING with its old failure count, and write no audit row.
+ snapshot = entity.to_snapshot()
+ # The two writes below are the fields their adjacent apply_outcome call transitions;
+ # the state machine still decides state and failure counts.
+ if enabled_change is True:
+ entity.enabled = True # nosemgrep: replay-vision-alert-state-direct-mutation
+ update_fields.extend(apply_outcome(entity, apply_enable(snapshot), kind=VisionAlertEvent.Kind.ENABLE))
+ elif enabled_change is False:
+ entity.enabled = False # nosemgrep: replay-vision-alert-state-direct-mutation
+ update_fields.extend(apply_outcome(entity, apply_disable(snapshot), kind=VisionAlertEvent.Kind.DISABLE))
+ elif threshold_changed:
+ update_fields.extend(
+ apply_outcome(entity, apply_threshold_change(snapshot), kind=VisionAlertEvent.Kind.THRESHOLD_CHANGE)
+ )
+ entity.clear_next_check()
+ update_fields.append("next_check_at")
+ if enabled_change is not None:
+ update_fields.append("enabled")
+ if update_fields:
+ entity.save(update_fields=[*set(update_fields), "updated_at"])
+ if "delivery_config" in data:
+ # Destinations are hog functions, not columns: without rebuilding them, a caller
+ # who edits delivery_config gets a 200 while notifications keep going to the old
+ # channel.
+ soft_delete_all_alert_destinations(
+ team_id=team.id, alert_id=str(entity.id), allowed_event_ids=VISION_ALERT_EVENT_IDS
+ )
+ _provision_alert_destinations(team, user, entity, data.get("delivery_config") or [])
+ return render_alert_as_action(entity)
+
+ cron = None
+ rrule = (data.get("trigger_config") or {}).get("rrule")
+ if rrule:
+ try:
+ cron = rrule_to_cron(rrule)
+ except ValueError as error:
+ raise ValidationError({"trigger_config": str(error)})
+ unsupported = sorted({"name", "selection", "synthesis_config", "mode", "scanner"} & set(data))
+ if unsupported:
+ # Better a clear refusal than a 200 that keeps the old values: a scout's name and prompt are
+ # its skill, and editing a skill has its own authoring bar that this surface cannot clear.
+ raise ValidationError(
+ {
+ unsupported[0]: f"Edit {', '.join(unsupported)} on the scout itself; this surface can change "
+ "the schedule, enablement, and delivery targets."
+ }
+ )
+ destinations = _scout_destinations_from_legacy(data) if "delivery_config" in data else None
+ if not signals_facade.update_scout_for_source(
+ (team.parent_team or team).id,
+ SCOUT_SOURCE_PRODUCT,
+ entity.config_id,
+ enabled=data.get("enabled"),
+ run_cron_schedule=cron,
+ output_destinations=destinations,
+ ):
+ raise NotFound()
+ refreshed = resolve_entities(team, entity.config_id)
+ if not refreshed:
+ raise NotFound()
+ return render_entity(refreshed[0])
+
+
+def destroy_action(team: Team, entries: list[tuple[str, Any]]) -> None:
+ for kind, entity in entries:
+ _destroy_one(team, kind, entity)
+
+
+def _destroy_one(team: Team, kind: str, entity: Any) -> None:
+ if kind == "alert":
+ soft_delete_all_alert_destinations(
+ team_id=team.id, alert_id=str(entity.id), allowed_event_ids=VISION_ALERT_EVENT_IDS
+ )
+ entity.delete()
+ return
+ if not signals_facade.delete_scout_for_source(
+ team=team.parent_team or team, source_product=SCOUT_SOURCE_PRODUCT, config_id=entity.config_id
+ ):
+ raise NotFound()
diff --git a/products/replay_vision/backend/management/commands/migrate_vision_actions.py b/products/replay_vision/backend/management/commands/migrate_vision_actions.py
new file mode 100644
index 000000000000..f38869d1b288
--- /dev/null
+++ b/products/replay_vision/backend/management/commands/migrate_vision_actions.py
@@ -0,0 +1,428 @@
+"""Migrate legacy VisionActions onto the alerts and scouts systems, org by org.
+
+Dry-run by default. For each organization with eligible actions:
+
+- `mode=alert` actions become VisionAlertConfigurations (every_match -> match kind,
+ on_breach -> metric kind), with their Slack/webhook targets rebuilt as alert
+ destinations. A legacy alert overriding `selection.scanner_ids` becomes one new
+ alert per scanner.
+- Hand-made group summaries and default digests with deliveries become scanner
+ scouts via the signals facade.
+- Delivery-less default digests are disabled in place; the in-app card is served
+ by the new system.
+- The organization is appended to the rollout flags, so its users switch surface
+ the moment their data lands.
+
+Every touched row is stamped with a `migrated_to` pointer (or `retired`), which
+makes the command idempotent and the cutover scriptably reversible.
+"""
+
+import re
+from dataclasses import dataclass, field
+from types import SimpleNamespace
+from typing import Any, cast
+
+from django.core.management.base import BaseCommand, CommandError
+from django.db import transaction
+from django.utils import timezone
+
+import structlog
+
+from posthog.models import Team, User
+
+from products.replay_vision.backend.alert_destinations import (
+ EVENT_KIND_CONFIG,
+ MATCH_EVENT_KINDS,
+ METRIC_EVENT_KINDS,
+ VISION_ALERT_EVENT_IDS,
+ VISION_ALERT_SLACK_CONTEXT_ELEMENTS,
+)
+from products.replay_vision.backend.api.vision_actions_shim import _parse_rrule, compose_scout_body, rrule_to_cron
+from products.replay_vision.backend.models.vision_action import ActionMode, AlertFrequency, VisionAction
+from products.replay_vision.backend.models.vision_alert import (
+ ALERT_WINDOW_DAYS,
+ VisionAlertConfiguration,
+ VisionAlertDirection,
+ VisionAlertKind,
+ VisionAlertMetric,
+)
+from products.replay_vision.backend.scout_source import SCOUT_SOURCE_PRODUCT
+
+logger = structlog.get_logger(__name__)
+
+ALERTS_FLAG_KEY = "replay-vision-alerts"
+SCOUTS_FLAG_KEY = "replay-vision-scout-digests"
+
+# Legacy on_breach alerts were evaluated at their action's schedule cadence; the new
+# scheduler takes a minute interval instead.
+_FREQ_TO_MINUTES = {"MINUTELY": 15, "HOURLY": 60, "DAILY": 1440, "WEEKLY": 10080}
+
+
+@dataclass(frozen=False)
+class _Report:
+ alerts_created: int = 0
+ scouts_created: int = 0
+ defaults_retired: int = 0
+ skipped_already: int = 0
+ orgs_flagged: int = 0
+ problems: list[str] = field(default_factory=list)
+
+
+def _clean_selection(selection: dict | None) -> dict:
+ """Legacy selections already use the new predicate keys; strip what moved elsewhere."""
+ selection = dict(selection or {})
+ selection.pop("scanner_ids", None)
+ selection.pop("window_days", None)
+ selection.pop("status", None)
+ return {k: v for k, v in selection.items() if v not in (None, [], "")}
+
+
+def _destination_data(entry: dict) -> dict | None:
+ if entry.get("type") == "slack":
+ channel = str(entry.get("channel") or "")
+ channel_id, _, channel_name = channel.partition("|")
+ return {
+ "type": "slack",
+ "slack_workspace_id": entry.get("integration_id"),
+ "slack_channel_id": channel_id,
+ "slack_channel_name": channel_name or channel_id,
+ }
+ if entry.get("type") == "webhook":
+ url = entry.get("url")
+ if url:
+ return {"type": "webhook", "webhook_url": url}
+ return None
+
+
+def _acting_user(action: VisionAction) -> User | None:
+ if action.created_by is not None:
+ return action.created_by
+ membership = action.team.organization.memberships.filter(user__is_active=True).order_by("joined_at").first()
+ return membership.user if membership else None
+
+
+def _unique_name(team_id: int, base: str) -> str:
+ name = base
+ suffix = 2
+ while VisionAlertConfiguration.objects.for_team(team_id).filter(name=name).exists():
+ name = f"{base} ({suffix})"
+ suffix += 1
+ return name
+
+
+def _scout_slug(action: VisionAction) -> str:
+ # The action-id suffix makes the name deterministic and collision-free, so a re-run
+ # upserts the same scout instead of creating a duplicate or clobbering a neighbor.
+ slug = re.sub(r"[^a-z0-9-]+", "-", action.name.lower()).strip("-")[:34] or "digest"
+ return f"signals-scout-{slug}-{str(action.id).replace('-', '')[-6:]}"
+
+
+class Command(BaseCommand):
+ help = "Migrate legacy VisionActions to the new alerts and scouts systems. Dry-run unless --execute."
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--execute", action="store_true", help="Apply changes. Without it, print the plan.")
+ parser.add_argument("--org", action="append", default=[], help="Only these organization ids (repeatable).")
+ parser.add_argument(
+ "--flag-team-id",
+ type=int,
+ required=True,
+ help="Team id of this instance's internal flags project (US: 2).",
+ )
+ parser.add_argument("--limit-orgs", type=int, default=None, help="Stop after this many organizations.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ execute: bool = options["execute"]
+ report = _Report()
+
+ actions = (
+ VisionAction.objects.unscoped()
+ .filter(mode__in=[ActionMode.ALERT, ActionMode.GROUP_SUMMARY])
+ .select_related("team", "team__organization", "scanner", "created_by")
+ .order_by("team__organization_id", "team_id", "created_at")
+ )
+ if options["org"]:
+ actions = actions.filter(team__organization_id__in=options["org"])
+
+ by_org: dict[Any, list[VisionAction]] = {}
+ for action in actions:
+ by_org.setdefault(action.team.organization_id, []).append(action)
+
+ orgs = list(by_org.items())
+ if options["limit_orgs"]:
+ orgs = orgs[: options["limit_orgs"]]
+
+ for org_id, org_actions in orgs:
+ self._migrate_org(org_id, org_actions, execute, options["flag_team_id"], report)
+
+ mode = "EXECUTED" if execute else "DRY RUN"
+ self.stdout.write(
+ f"[{mode}] orgs: {len(orgs)} | alerts created: {report.alerts_created} | "
+ f"scouts created: {report.scouts_created} | defaults retired: {report.defaults_retired} | "
+ f"already migrated (skipped): {report.skipped_already} | orgs flagged: {report.orgs_flagged}"
+ )
+ for problem in report.problems:
+ self.stdout.write(f" PROBLEM: {problem}")
+ if report.problems and execute:
+ raise CommandError(f"{len(report.problems)} rows need manual attention; see above.")
+
+ def _migrate_org(
+ self, org_id: Any, org_actions: list[VisionAction], execute: bool, flag_team_id: int, report: _Report
+ ) -> None:
+ # "This org has migrated rows", not "this run migrated something": an interrupted run that
+ # already moved the rows must still be able to flag the org on a re-run, or its users sit on
+ # the legacy surface with their legacy actions disabled — no alerting at all.
+ migrated_any = False
+ org_problems = 0
+ pending: list[VisionAction] = []
+ for action in org_actions:
+ stamp_field = "alert_config" if action.mode == ActionMode.ALERT else "synthesis_config"
+ stamps = getattr(action, stamp_field) or {}
+ if stamps.get("migrated_to") or stamps.get("retired"):
+ report.skipped_already += 1
+ migrated_any = True
+ continue
+ pending.append(action)
+
+ # Check the whole organization before writing any of it. A row that fails halfway through
+ # otherwise leaves the org part-migrated and unflagged: some rows moved, the rest still
+ # live on the legacy surface, and nobody switched over.
+ blockers = [problem for action in pending if (problem := self._validation_problem(action))]
+ if blockers:
+ for problem in blockers:
+ report.problems.append(problem)
+ report.problems.append(f"org {org_id}: not migrated, {len(blockers)} row(s) need attention")
+ return
+
+ for action in pending:
+ try:
+ plan = self._plan(action)
+ if plan == "alert":
+ migrated_any |= self._migrate_alert(action, execute, report)
+ elif plan == "digest":
+ migrated_any |= self._migrate_digest(action, execute, report)
+ else:
+ # Retiring a default is a completed migration for that row: the new Overview
+ # card replaces it. Without feeding the flag flip, an org whose only rows are
+ # default digests gets them disabled and never switches surface, so its
+ # Overview reads "The featured digest is paused." forever.
+ migrated_any |= self._retire_default(action, execute, report)
+ except Exception as error:
+ org_problems += 1
+ report.problems.append(f"{action.mode} {action.id} ({action.name!r}, team {action.team_id}): {error}")
+ logger.exception("vision_action_migration.row_failed", action_id=str(action.id))
+
+ if org_problems:
+ # Flagging now would put the org on the new surface while the failed row's legacy action
+ # is still enabled on the old one — the double-notification case.
+ report.problems.append(f"org {org_id}: not flagged, {org_problems} row(s) need attention")
+ return
+ if migrated_any:
+ self._flag_org(org_id, execute, flag_team_id, report)
+
+ def _plan(self, action: VisionAction) -> str:
+ """What this row becomes. Shared by the check and the write so they cannot disagree."""
+ if action.mode == ActionMode.ALERT:
+ return "alert"
+ if action.delivery_config or not action.is_scanner_digest:
+ return "digest"
+ return "retire"
+
+ def _validation_problem(self, action: VisionAction) -> str | None:
+ """Why this row cannot migrate, or None. Reads only; never writes."""
+ where = f"{action.mode} {action.id} ({action.name!r}, team {action.team_id})"
+ plan = self._plan(action)
+ if plan == "retire":
+ return None
+ if _acting_user(action) is None and (plan == "digest" or action.delivery_config):
+ return f"{where}: no active user in the organization to own the migrated row"
+ if plan == "digest":
+ try:
+ rrule_to_cron((action.trigger_config or {}).get("rrule") or "FREQ=DAILY;BYHOUR=8;BYMINUTE=0")
+ except ValueError as error:
+ return f"{where}: {error}"
+ return None
+
+ def _migrate_alert(self, action: VisionAction, execute: bool, report: _Report) -> bool:
+ config = action.alert_config or {}
+ frequency = config.get("frequency", AlertFrequency.EVERY_MATCH)
+ selection = action.selection or {}
+ scanner_ids = selection.get("scanner_ids") or [str(action.scanner_id)]
+ acting = _acting_user(action)
+
+ new_ids: list[str] = []
+ staged: list[dict[str, Any]] = []
+ for index, scanner_id in enumerate(scanner_ids):
+ base = action.name if len(scanner_ids) == 1 else f"{action.name} ({index + 1})"
+ kwargs: dict[str, Any] = {
+ "team_id": action.team_id,
+ "scanner_id": scanner_id,
+ "name": _unique_name(action.team_id, base),
+ "enabled": action.enabled,
+ "created_by": action.created_by,
+ "first_enabled_at": action.created_at,
+ "selection": _clean_selection(selection),
+ }
+ if frequency == AlertFrequency.ON_BREACH:
+ window = int(config.get("window_days") or 1)
+ if window not in ALERT_WINDOW_DAYS:
+ window = min(ALERT_WINDOW_DAYS, key=lambda choice: abs(choice - window))
+ cadence = _FREQ_TO_MINUTES.get(
+ _parse_rrule((action.trigger_config or {}).get("rrule", "")).get("FREQ", ""), 1440
+ )
+ kwargs.update(
+ kind=VisionAlertKind.METRIC,
+ metric=config.get("metric", VisionAlertMetric.COUNT),
+ direction=config.get("direction", VisionAlertDirection.ABOVE),
+ threshold=float(config.get("threshold", 1)),
+ window_days=window,
+ check_interval_minutes=max(cadence, 15),
+ )
+ else:
+ kwargs.update(kind=VisionAlertKind.MATCH, threshold=None)
+
+ if not execute:
+ new_ids.append("(dry-run)")
+ continue
+ staged.append(kwargs)
+ report.alerts_created += len(scanner_ids)
+
+ if not execute:
+ return True
+ # One transaction for every alert this action becomes AND its stamp: a partial commit would
+ # leave unstamped alerts that a re-run duplicates, and both copies would then fire.
+ with transaction.atomic():
+ for kwargs in staged:
+ alert = VisionAlertConfiguration.objects.for_team(action.team_id).create(**kwargs)
+ self._create_destinations(alert, action, acting)
+ new_ids.append(str(alert.id))
+ action.alert_config = {**config, "migrated_to": new_ids, "migrated_at": timezone.now().isoformat()}
+ action.enabled = False
+ action.save(update_fields=["alert_config", "enabled", "updated_at"])
+ return True
+
+ def _create_destinations(self, alert: VisionAlertConfiguration, action: VisionAction, acting: User | None) -> None:
+ from products.alerts.backend.destination_configs import ( # noqa: PLC0415 — keeps the alerts API surface off the command's import path
+ AlertDestinationData,
+ DestinationType,
+ )
+ from products.alerts.backend.facade.api import ( # noqa: PLC0415 — keeps the alerts API surface off the command's import path
+ build_alert_destination_config,
+ create_alert_destination_hog_functions,
+ )
+
+ entries = [data for data in (_destination_data(entry) for entry in action.delivery_config or []) if data]
+ if not entries or acting is None:
+ if entries and acting is None:
+ raise ValueError("no acting user available to own the destination hog functions")
+ return
+ kinds = MATCH_EVENT_KINDS if alert.kind == VisionAlertKind.MATCH else METRIC_EVENT_KINDS
+ request = SimpleNamespace(user=acting)
+ for data in entries:
+ destination = cast("AlertDestinationData", {**data, "type": DestinationType(data["type"])})
+ configs = [
+ build_alert_destination_config(
+ team=alert.team,
+ spec=EVENT_KIND_CONFIG[kind],
+ alert_id=str(alert.id),
+ alert_name=alert.name,
+ data=destination,
+ slack_context_elements=VISION_ALERT_SLACK_CONTEXT_ELEMENTS,
+ )
+ for kind in kinds
+ ]
+ create_alert_destination_hog_functions(
+ configs, request=request, alert_id=str(alert.id), allowed_event_ids=VISION_ALERT_EVENT_IDS
+ )
+
+ def _migrate_digest(self, action: VisionAction, execute: bool, report: _Report) -> bool:
+ from products.signals.backend.facade import ( # noqa: PLC0415 — keeps the signals API surface off the command's import path
+ api as signals_facade,
+ )
+
+ acting = _acting_user(action)
+ if acting is None:
+ raise ValueError("no acting user available to own the scout")
+ cron = rrule_to_cron((action.trigger_config or {}).get("rrule") or "FREQ=DAILY;BYHOUR=8;BYMINUTE=0")
+
+ destinations: dict[str, Any] = {}
+ for entry in action.delivery_config or []:
+ data = _destination_data(entry)
+ if not data:
+ continue
+ if data["type"] == "slack" and "slack" not in destinations:
+ destinations["slack"] = {
+ "integration_id": data["slack_workspace_id"],
+ "channel_id": data["slack_channel_id"],
+ "channel_name": data["slack_channel_name"],
+ }
+ elif data["type"] == "webhook" and "webhook" not in destinations:
+ destinations["webhook"] = {"url": data["webhook_url"]}
+
+ payload: dict[str, Any] = {
+ "name": _scout_slug(action),
+ "description": f'Migrated Replay Vision digest "{action.name}" for scanner "{action.scanner.name}".',
+ "body": compose_scout_body(
+ action.name, action.scanner.name, action.selection or {}, action.synthesis_config or {}
+ ),
+ "config": {
+ "enabled": action.enabled,
+ "run_cron_schedule": cron,
+ **({"output_destinations": destinations} if destinations else {}),
+ },
+ }
+
+ report.scouts_created += 1
+ if not execute:
+ return True
+
+ with transaction.atomic():
+ signals_facade.create_scout_for_source(
+ team=action.team.parent_team or action.team,
+ user=acting,
+ name=payload["name"],
+ description=payload["description"],
+ body=payload["body"],
+ files=[],
+ config_options=payload["config"],
+ request=SimpleNamespace(user=acting),
+ serializer_context={"project_id": action.team.project_id},
+ source_product=SCOUT_SOURCE_PRODUCT,
+ source_id=str(action.scanner_id),
+ )
+ action.synthesis_config = {
+ **(action.synthesis_config or {}),
+ "migrated_to": payload["name"],
+ "migrated_at": timezone.now().isoformat(),
+ }
+ action.enabled = False
+ action.save(update_fields=["synthesis_config", "enabled", "updated_at"])
+ logger.info("vision_action_migration.scout_created", action_id=str(action.id), scout=payload["name"])
+ return True
+
+ def _retire_default(self, action: VisionAction, execute: bool, report: _Report) -> bool:
+ report.defaults_retired += 1
+ if not execute:
+ return True
+ action.synthesis_config = {**(action.synthesis_config or {}), "retired": True}
+ action.enabled = False
+ action.save(update_fields=["synthesis_config", "enabled", "updated_at"])
+ return True
+
+ def _flag_org(self, org_id: Any, execute: bool, flag_team_id: int, report: _Report) -> None:
+ from products.feature_flags.backend.facade.api import ( # noqa: PLC0415 — keeps the flags API surface off the command's import path
+ add_group_to_flag_targeting,
+ )
+
+ team = Team.objects.get(id=flag_team_id)
+ widened = True
+ for key in (ALERTS_FLAG_KEY, SCOUTS_FLAG_KEY):
+ if not execute:
+ continue
+ if not add_group_to_flag_targeting(team=team, key=key, group_key=str(org_id)):
+ report.problems.append(f"flag {key}: no organization targeting to widen on team {flag_team_id}")
+ widened = False
+ # Counting an org as flagged when the flag never took would report a rollout that did not
+ # happen, and its users would sit on the legacy surface with their rows already migrated.
+ if widened:
+ report.orgs_flagged += 1
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
index 401c9109af7d..7029eea02269 100644
--- a/products/replay_vision/backend/max_tools.py
+++ b/products/replay_vision/backend/max_tools.py
@@ -23,6 +23,7 @@ from products.replay_vision.backend.api.delivery import archive_delivery, provis
from products.replay_vision.backend.api.scanners import ReplayScannerSerializer
from products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_process_vision_action_workflow
from products.replay_vision.backend.api.vision_actions import VisionActionSerializer
+from products.replay_vision.backend.api.vision_actions_shim import unmigrated
from products.replay_vision.backend.billing import CREDITS_PER_DOLLAR, observation_credits_for_model
from products.replay_vision.backend.consent import is_ai_data_processing_approved
from products.replay_vision.backend.embeddings import OBSERVATION_EMBEDDING_MODEL
@@ -223,7 +224,12 @@ class ReplayVisionGatesMixin:
"""
if not is_uuid(action_id):
return None
- action = VisionAction.objects.for_team(self._team.id).filter(id=action_id).select_related("scanner").first()
+ action = (
+ unmigrated(VisionAction.objects.for_team(self._team.id))
+ .filter(id=action_id)
+ .select_related("scanner")
+ .first()
+ )
if action is None or not self.user_access_control.check_access_level_for_object(action, level):
return None
if not self.user_access_control.check_access_level_for_object(action.scanner, level):
@@ -1222,6 +1228,36 @@ class CreateReplayVisionActionTool(ReplayVisionGatesMixin, MaxTool):
# restriction that blocks the API be walked around through Max.
if scanner is None or not self.user_access_control.check_access_level_for_object(scanner, "editor"):
return f"Scanner {scanner_id} not found.", {"error": "not_found"}
+ from posthog.ph_client import (
+ feature_enabled_or_false, # noqa: PLC0415 — keeps the analytics client off the import path
+ )
+
+ if feature_enabled_or_false(
+ "replay-vision-alerts",
+ getattr(self._user, "distinct_id", str(self._user.id)),
+ groups={"organization": str(self._team.organization_id)},
+ send_feature_flag_events=False,
+ ):
+ from products.replay_vision.backend.api import (
+ vision_actions_shim, # noqa: PLC0415 — deferred with the flag branch
+ )
+
+ rendered = vision_actions_shim.create_action(
+ self._team,
+ self._user,
+ {
+ "name": name.strip(),
+ "scanner": str(scanner.id),
+ "mode": ActionMode.GROUP_SUMMARY,
+ "trigger_config": {"rrule": rrule, "timezone": self._team.timezone or "UTC"},
+ "synthesis_config": {"prompt_guide": focus.strip()} if focus and focus.strip() else {},
+ },
+ )
+ return (
+ f"Created a {cadence} scout digest of that scanner's observations. It appears on the "
+ "scanner's Scouts tab, and you can add Slack or webhook delivery there.",
+ {"vision_action_id": rendered["id"]},
+ )
# Through the serializer so the rrule and timezone are validated and the unique-name race is
# handled, rather than writing a trigger_config the scheduler later chokes on.
serializer = VisionActionSerializer(
@@ -1719,7 +1755,9 @@ class ReadReplayVisionActionsTool(ReplayVisionGatesMixin, MaxTool):
resource, not any individual scanner's ACL, so a per-scanner restriction would still leave the
action listed along with reports derived from that scanner's observations.
"""
- actions = self.user_access_control.filter_queryset_by_access_level(VisionAction.objects.for_team(self._team.id))
+ actions = self.user_access_control.filter_queryset_by_access_level(
+ unmigrated(VisionAction.objects.for_team(self._team.id))
+ )
readable_scanners = self.user_access_control.filter_queryset_by_access_level(
ReplayScanner.objects.filter(team_id=self._team.id)
)
diff --git a/products/replay_vision/backend/tests/test_migrate_vision_actions.py b/products/replay_vision/backend/tests/test_migrate_vision_actions.py
new file mode 100644
index 000000000000..6c2897da0639
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_migrate_vision_actions.py
@@ -0,0 +1,262 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from parameterized import parameterized
+
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.replay_vision.backend.management.commands.migrate_vision_actions import rrule_to_cron
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.models.vision_action import ActionMode, TriggerType, VisionAction
+from products.replay_vision.backend.models.vision_alert import VisionAlertConfiguration, VisionAlertKind
+
+_CMD = "products.replay_vision.backend.management.commands.migrate_vision_actions"
+
+
+class TestMigrateVisionActions(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="Checkout monitor",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "watch checkout"},
+ model=ScannerModel.GEMINI_3_7_FLASH,
+ )
+ for key in ("replay-vision-alerts", "replay-vision-scout-digests"):
+ FeatureFlag.objects.create(
+ team=self.team,
+ key=key,
+ created_by=self.user,
+ filters={
+ "aggregation_group_type_index": 0,
+ "groups": [
+ {
+ "properties": [
+ {
+ "key": "$group_key",
+ "type": "group",
+ "group_type_index": 0,
+ "value": [],
+ "operator": "exact",
+ }
+ ],
+ "rollout_percentage": 100,
+ }
+ ],
+ },
+ )
+
+ def _make_scanner(self, name: str) -> ReplayScanner:
+ return ReplayScanner.objects.create(
+ team=self.team,
+ name=name,
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "watch"},
+ model=ScannerModel.GEMINI_3_7_FLASH,
+ )
+
+ def _make_action(self, **overrides: Any) -> VisionAction:
+ fields: dict[str, Any] = {
+ "team": self.team,
+ "scanner": self.scanner,
+ "name": f"Legacy {VisionAction.objects.unscoped().count()}",
+ "mode": ActionMode.ALERT,
+ "trigger_type": TriggerType.SCHEDULE,
+ "trigger_config": {"rrule": "FREQ=DAILY;BYHOUR=8;BYMINUTE=0", "timezone": "UTC"},
+ "created_by": self.user,
+ "enabled": True,
+ }
+ fields.update(overrides)
+ return VisionAction.objects.unscoped().create(**fields)
+
+ def _run(self, execute: bool = True) -> None:
+ args = ["--flag-team-id", str(self.team.id)]
+ if execute:
+ args.append("--execute")
+ call_command("migrate_vision_actions", *args)
+
+ @parameterized.expand(
+ [
+ ("daily", "FREQ=DAILY;BYHOUR=9;BYMINUTE=30", "30 9 * * *"),
+ ("weekly_days", "FREQ=WEEKLY;BYDAY=MO,FR;BYHOUR=8;BYMINUTE=0", "0 8 * * 1,5"),
+ ("weekly_bare", "FREQ=WEEKLY;BYHOUR=8;BYMINUTE=0", "0 8 * * 1"),
+ ("hourly", "FREQ=HOURLY", "0 * * * *"),
+ ("minutely_floored", "FREQ=MINUTELY;INTERVAL=5", "*/15 * * * *"),
+ ("daily_bare", "FREQ=DAILY", "0 8 * * *"),
+ ]
+ )
+ def test_rrule_to_cron(self, _name: str, rrule: str, expected: str) -> None:
+ assert rrule_to_cron(rrule) == expected
+
+ def test_rrule_to_cron_rejects_unknown(self) -> None:
+ with self.assertRaises(ValueError):
+ rrule_to_cron("FREQ=MONTHLY;BYMONTHDAY=1")
+
+ def test_every_match_becomes_match_alert_with_destination(self) -> None:
+ action = self._make_action(
+ alert_config={"frequency": "every_match", "metric": "count"},
+ selection={"verdict": ["fail"], "scanner_ids": None},
+ delivery_config=[{"type": "slack", "integration_id": 7, "channel": "C123|#alerts"}],
+ )
+ with patch(f"{_CMD}.Command._create_destinations") as destinations:
+ self._run()
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).get()
+ assert alert.kind == VisionAlertKind.MATCH
+ assert alert.threshold is None
+ assert alert.selection == {"verdict": ["fail"]}
+ assert alert.enabled is True
+ destinations.assert_called_once()
+ action.refresh_from_db()
+ assert action.enabled is False
+ assert action.alert_config["migrated_to"] == [str(alert.id)]
+
+ def test_on_breach_becomes_metric_alert_with_snapped_window(self) -> None:
+ self._make_action(
+ alert_config={
+ "frequency": "on_breach",
+ "metric": "count",
+ "direction": "above",
+ "threshold": 5,
+ "window_days": 10,
+ },
+ trigger_config={"rrule": "FREQ=HOURLY", "timezone": "UTC"},
+ )
+ with patch(f"{_CMD}.Command._create_destinations"):
+ self._run()
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).get()
+ assert alert.kind == VisionAlertKind.METRIC
+ assert alert.threshold == 5.0
+ assert alert.window_days in (7, 14)
+ assert alert.check_interval_minutes == 60
+
+ def test_scanner_ids_split_into_one_alert_each(self) -> None:
+ other = ReplayScanner.objects.create(
+ team=self.team,
+ name="Second",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "x"},
+ model=ScannerModel.GEMINI_3_7_FLASH,
+ )
+ self._make_action(
+ name="Wide alert",
+ alert_config={"frequency": "every_match"},
+ selection={"scanner_ids": [str(self.scanner.id), str(other.id)]},
+ )
+ with patch(f"{_CMD}.Command._create_destinations"):
+ self._run()
+ alerts = VisionAlertConfiguration.objects.for_team(self.team.id)
+ assert alerts.count() == 2
+ assert {a.scanner_id for a in alerts} == {self.scanner.id, other.id}
+
+ def test_custom_digest_becomes_scout(self) -> None:
+ action = self._make_action(
+ name="Weekly checkout roundup",
+ mode=ActionMode.GROUP_SUMMARY,
+ is_scanner_digest=False,
+ trigger_config={"rrule": "FREQ=WEEKLY;BYDAY=MO;BYHOUR=9;BYMINUTE=0", "timezone": "UTC"},
+ selection={"verdict": ["fail"], "window_days": 7},
+ synthesis_config={"prompt_guide": "Focus on payment failures."},
+ delivery_config=[{"type": "slack", "integration_id": 7, "channel": "C123|#digests"}],
+ )
+ with patch("products.signals.backend.facade.api.create_scout_for_source") as create_scout:
+ self._run()
+ assert create_scout.call_count == 1
+ kwargs = create_scout.call_args.kwargs
+ assert kwargs["name"].startswith("signals-scout-weekly-checkout-roundup-")
+ assert kwargs["source_id"] == str(self.scanner.id)
+ assert "Focus on payment failures." in kwargs["body"]
+ assert "verdict in ['fail']" in kwargs["body"]
+ assert kwargs["config_options"]["run_cron_schedule"] == "0 9 * * 1"
+ assert kwargs["config_options"]["output_destinations"]["slack"]["channel_id"] == "C123"
+ action.refresh_from_db()
+ assert action.enabled is False
+ assert action.synthesis_config["migrated_to"] == kwargs["name"]
+
+ def test_deliveryless_default_is_retired_not_migrated(self) -> None:
+ action = self._make_action(
+ mode=ActionMode.GROUP_SUMMARY, is_scanner_digest=True, delivery_config=[], synthesis_config={}
+ )
+ with patch("products.signals.backend.facade.api.create_scout_for_source") as create_scout:
+ self._run()
+ create_scout.assert_not_called()
+ action.refresh_from_db()
+ assert action.enabled is False
+ assert action.synthesis_config == {"retired": True}
+ assert VisionAlertConfiguration.objects.for_team(self.team.id).count() == 0
+
+ def test_org_with_only_default_digests_is_still_flagged(self) -> None:
+ # One default digest per scanner: the unique constraint allows no more.
+ for index in range(2):
+ scanner = self.scanner if index == 0 else self._make_scanner(f"Scanner {index}")
+ self._make_action(
+ scanner=scanner,
+ mode=ActionMode.GROUP_SUMMARY,
+ is_scanner_digest=True,
+ delivery_config=[],
+ synthesis_config={},
+ )
+ with patch("products.signals.backend.facade.api.create_scout_for_source") as create_scout:
+ self._run()
+ create_scout.assert_not_called()
+ for key in ("replay-vision-alerts", "replay-vision-scout-digests"):
+ flag = FeatureFlag.objects.get(team=self.team, key=key)
+ assert flag.filters["groups"][0]["properties"][0]["value"] == [str(self.team.organization_id)]
+
+ def test_one_unconvertible_row_blocks_its_whole_org(self) -> None:
+ good = self._make_action(alert_config={"frequency": "every_match"})
+ bad = self._make_action(
+ name="Fortnightly digest",
+ mode=ActionMode.GROUP_SUMMARY,
+ is_scanner_digest=False,
+ # cron cannot express a fortnightly cadence, so this row cannot migrate.
+ trigger_config={"rrule": "FREQ=WEEKLY;INTERVAL=2;BYDAY=MO;BYHOUR=9;BYMINUTE=0", "timezone": "UTC"},
+ )
+ with (
+ patch(f"{_CMD}.Command._create_destinations"),
+ patch("products.signals.backend.facade.api.create_scout_for_source") as create_scout,
+ ):
+ # The run reports the blocked rows and exits non-zero so an operator sees them.
+ with self.assertRaises(CommandError):
+ self._run()
+ create_scout.assert_not_called()
+ # Nothing moved: the good row is untouched rather than half-migrating the org.
+ assert VisionAlertConfiguration.objects.for_team(self.team.id).count() == 0
+ for action in (good, bad):
+ action.refresh_from_db()
+ assert action.enabled is True
+ flag = FeatureFlag.objects.get(team=self.team, key="replay-vision-alerts")
+ assert flag.filters["groups"][0]["properties"][0]["value"] == []
+
+ def test_rerun_skips_migrated_rows(self) -> None:
+ self._make_action(alert_config={"frequency": "every_match"})
+ with patch(f"{_CMD}.Command._create_destinations"):
+ self._run()
+ self._run()
+ assert VisionAlertConfiguration.objects.for_team(self.team.id).count() == 1
+
+ def test_org_appended_to_both_flags_once(self) -> None:
+ self._make_action(alert_config={"frequency": "every_match"})
+ with patch(f"{_CMD}.Command._create_destinations"):
+ self._run()
+ self._run()
+ for key in ("replay-vision-alerts", "replay-vision-scout-digests"):
+ flag = FeatureFlag.objects.get(team=self.team, key=key)
+ values = flag.filters["groups"][0]["properties"][0]["value"]
+ assert values == [str(self.team.organization_id)]
+
+ def test_dry_run_changes_nothing(self) -> None:
+ action = self._make_action(alert_config={"frequency": "every_match"})
+ with patch(f"{_CMD}.Command._create_destinations"):
+ self._run(execute=False)
+ action.refresh_from_db()
+ assert action.enabled is True
+ assert "migrated_to" not in action.alert_config
+ assert VisionAlertConfiguration.objects.for_team(self.team.id).count() == 0
+ for key in ("replay-vision-alerts",):
+ flag = FeatureFlag.objects.get(team=self.team, key=key)
+ assert flag.filters["groups"][0]["properties"][0]["value"] == []
diff --git a/products/replay_vision/backend/tests/test_vision_actions_shim.py b/products/replay_vision/backend/tests/test_vision_actions_shim.py
new file mode 100644
index 000000000000..b605a46ea06b
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_vision_actions_shim.py
@@ -0,0 +1,582 @@
+from datetime import UTC, datetime
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.models import Organization, Team
+from posthog.models.integration import Integration
+
+from products.replay_vision.backend.api.vision_actions_shim import cron_to_rrule, rrule_to_cron
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.models.vision_action import ActionMode, TriggerType, VisionAction
+from products.replay_vision.backend.models.vision_alert import VisionAlertConfiguration, VisionAlertKind
+from products.signals.backend.facade.api import ScoutSummary
+
+_SHIM = "products.replay_vision.backend.api.vision_actions_shim"
+_VIEWSET = "products.replay_vision.backend.api.vision_actions"
+
+
+def _scout(config_id: str = "01a00000-0000-7000-8000-000000000abc", **overrides: Any) -> ScoutSummary:
+ fields: dict[str, Any] = {
+ "config_id": config_id,
+ "skill_name": "signals-scout-daily-roundup",
+ "source_id": None,
+ "enabled": True,
+ "run_cron_schedule": "0 9 * * 1",
+ "run_interval_minutes": 1440,
+ "output_destinations": {"slack": {"integration_id": 7, "channel_id": "C9", "channel_name": "#digests"}},
+ "description": "Weekly roundup",
+ "created_at": datetime(2026, 8, 1, tzinfo=UTC),
+ "created_by_id": None,
+ "last_run_at": None,
+ }
+ fields.update(overrides)
+ return ScoutSummary(**fields)
+
+
+class TestVisionActionsShim(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="Checkout monitor",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "watch checkout"},
+ model=ScannerModel.GEMINI_3_7_FLASH,
+ )
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_TEST",
+ config={"team": {"name": "Test Workspace"}},
+ sensitive_config={"access_token": "test-token"},
+ created_by=self.user,
+ )
+ self.base_url = f"/api/projects/{self.team.id}/vision/actions/"
+ self._flag = patch("posthog.ph_client.feature_enabled_or_false", return_value=True)
+ self._flag.start()
+ self.addCleanup(self._flag.stop)
+
+ @parameterized.expand(
+ [
+ ("weekly", "FREQ=WEEKLY;BYDAY=MO,FR;BYHOUR=9;BYMINUTE=30"),
+ ("daily", "FREQ=DAILY;BYHOUR=8;BYMINUTE=0"),
+ ("hourly", "FREQ=HOURLY"),
+ ("minutely", "FREQ=MINUTELY;INTERVAL=15"),
+ ]
+ )
+ def test_cron_rrule_round_trip(self, _name: str, rrule: str) -> None:
+ assert cron_to_rrule(rrule_to_cron(rrule)) == rrule
+
+ @parameterized.expand(
+ [
+ ("ordinal_byday", "FREQ=WEEKLY;BYDAY=1MO;BYHOUR=9;BYMINUTE=0"),
+ ("weekly_interval", "FREQ=WEEKLY;INTERVAL=2;BYDAY=MO;BYHOUR=9;BYMINUTE=0"),
+ ("daily_interval", "FREQ=DAILY;INTERVAL=3;BYHOUR=9;BYMINUTE=0"),
+ ]
+ )
+ def test_rrule_to_cron_rejects_schedules_cron_cannot_express(self, _name: str, rrule: str) -> None:
+ with self.assertRaises(ValueError):
+ rrule_to_cron(rrule)
+
+ def test_flagged_alert_create_lands_in_new_system(self) -> None:
+ with patch(f"{_SHIM}.create_alert_destination_hog_functions") as destinations:
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Failed checkouts",
+ "scanner": str(self.scanner.id),
+ "mode": "alert",
+ "trigger_type": "schedule",
+ "trigger_config": {"rrule": "FREQ=DAILY;BYHOUR=8;BYMINUTE=0", "timezone": "UTC"},
+ "alert_config": {"frequency": "every_match", "metric": "count"},
+ "selection": {"verdict": ["yes"]},
+ "delivery_config": [
+ {"type": "slack", "integration_id": self.integration.id, "channel": "C9|#alerts"}
+ ],
+ },
+ format="json",
+ )
+ assert response.status_code == 201, response.json()
+ data = response.json()
+ assert data["mode"] == "alert"
+ assert data["alert_config"]["frequency"] == "every_match"
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).get(id=data["id"])
+ assert alert.kind == VisionAlertKind.MATCH
+ assert alert.selection == {"verdict": ["yes"]}
+ configs = destinations.call_args.args[0]
+ assert destinations.call_args.kwargs["alert_id"] == str(alert.id)
+ # One destination per match-kind event, all on this team, pointed at the posted channel.
+ assert len(configs) == 1
+ assert all(config.team.id == self.team.id for config in configs)
+ assert "C9" in str(configs[0].payload)
+ assert VisionAction.objects.unscoped().filter(team=self.team).count() == 0
+
+ def test_flagged_on_breach_create_maps_to_metric(self) -> None:
+ with patch(f"{_SHIM}.create_alert_destination_hog_functions"):
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Too many fails",
+ "scanner": str(self.scanner.id),
+ "mode": "alert",
+ "alert_config": {
+ "frequency": "on_breach",
+ "metric": "count",
+ "direction": "above",
+ "threshold": 5,
+ "window_days": 7,
+ },
+ },
+ format="json",
+ )
+ assert response.status_code == 201, response.json()
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).get()
+ assert alert.kind == VisionAlertKind.METRIC
+ assert alert.threshold == 5.0
+ assert alert.window_days == 7
+
+ def test_flagged_digest_create_becomes_scout(self) -> None:
+ created = _scout(skill_name="signals-scout-daily-digest", source_id=str(self.scanner.id))
+ with (
+ patch(
+ f"{_SHIM}.signals_facade.create_scout_for_source",
+ return_value=type("R", (), {"config": type("C", (), {"id": created.config_id})(), "created": True})(),
+ ) as create_scout,
+ patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[created]),
+ ):
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Daily digest",
+ "scanner": str(self.scanner.id),
+ "mode": "group_summary",
+ "trigger_config": {"rrule": "FREQ=WEEKLY;BYDAY=MO;BYHOUR=9;BYMINUTE=0", "timezone": "UTC"},
+ "synthesis_config": {"prompt_guide": "Focus on payments."},
+ },
+ format="json",
+ )
+ assert response.status_code == 201, response.json()
+ kwargs = create_scout.call_args.kwargs
+ assert kwargs["config_options"]["run_cron_schedule"] == "0 9 * * 1"
+ assert "Focus on payments." in kwargs["body"]
+ assert response.json()["mode"] == "group_summary"
+ assert VisionAction.objects.unscoped().filter(team=self.team).count() == 0
+
+ def test_flagged_list_synthesizes_both_systems(self) -> None:
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ scanner=self.scanner,
+ name="Match alert",
+ kind=VisionAlertKind.MATCH,
+ selection={},
+ )
+ with patch(
+ f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[_scout(source_id=str(self.scanner.id))]
+ ):
+ response = self.client.get(self.base_url)
+ assert response.status_code == 200
+ results = response.json()["results"]
+ modes = {row["mode"] for row in results}
+ assert modes == {"alert", "group_summary"}
+ alert_row = next(row for row in results if row["mode"] == "alert")
+ assert alert_row["id"] == str(alert.id)
+ digest_row = next(row for row in results if row["mode"] == "group_summary")
+ assert digest_row["trigger_config"]["rrule"] == "FREQ=WEEKLY;BYDAY=MO;BYHOUR=9;BYMINUTE=0"
+ assert digest_row["delivery_config"] == [{"type": "slack", "integration_id": 7, "channel": "C9|#digests"}]
+
+ def test_migrated_legacy_id_resolves_to_new_alert(self) -> None:
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id, scanner=self.scanner, name="Successor", kind=VisionAlertKind.MATCH, selection={}
+ )
+ legacy = VisionAction.objects.unscoped().create(
+ team=self.team,
+ scanner=self.scanner,
+ name="Old alert",
+ mode=ActionMode.ALERT,
+ trigger_type=TriggerType.SCHEDULE,
+ enabled=False,
+ alert_config={"frequency": "every_match", "migrated_to": [str(alert.id)]},
+ )
+ with patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[]):
+ response = self.client.get(f"{self.base_url}{legacy.id}/")
+ assert response.status_code == 200
+ assert response.json()["id"] == str(alert.id)
+
+ def test_flagged_update_and_destroy_operate_on_new_alert(self) -> None:
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ scanner=self.scanner,
+ name="Metric alert",
+ kind=VisionAlertKind.METRIC,
+ threshold=5,
+ selection={},
+ )
+ response = self.client.patch(
+ f"{self.base_url}{alert.id}/", {"alert_config": {"threshold": 9}, "enabled": False}, format="json"
+ )
+ assert response.status_code == 200, response.json()
+ alert.refresh_from_db()
+ assert alert.threshold == 9
+ assert alert.enabled is False
+
+ with patch(f"{_SHIM}.soft_delete_all_alert_destinations") as soft_delete:
+ response = self.client.delete(f"{self.base_url}{alert.id}/")
+ assert response.status_code == 204
+ soft_delete.assert_called_once()
+ assert not VisionAlertConfiguration.objects.for_team(self.team.id).filter(id=alert.id).exists()
+
+ def test_flagged_scout_destroy_goes_through_facade(self) -> None:
+ summary = _scout(source_id=str(self.scanner.id))
+ with (
+ patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[summary]),
+ patch(f"{_SHIM}.signals_facade.delete_scout_for_source", return_value=True) as delete_scout,
+ ):
+ response = self.client.delete(f"{self.base_url}{summary.config_id}/")
+ assert response.status_code == 204
+ assert delete_scout.call_args.kwargs["config_id"] == summary.config_id
+
+ def test_migrated_digest_legacy_id_resolves_to_scout_by_name(self) -> None:
+ summary = _scout(skill_name="signals-scout-weekly-abc123", source_id=str(self.scanner.id))
+ legacy = VisionAction.objects.unscoped().create(
+ team=self.team,
+ scanner=self.scanner,
+ name="Old digest",
+ mode=ActionMode.GROUP_SUMMARY,
+ trigger_type=TriggerType.SCHEDULE,
+ enabled=False,
+ synthesis_config={"migrated_to": summary.skill_name},
+ )
+ with patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[summary]):
+ response = self.client.get(f"{self.base_url}{legacy.id}/")
+ assert response.status_code == 200, response.json()
+ assert response.json()["id"] == summary.config_id
+
+ def test_malformed_id_is_not_found_rather_than_server_error(self) -> None:
+ with patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[]):
+ response = self.client.get(f"{self.base_url}not-a-uuid/")
+ assert response.status_code == 404
+
+ def test_webhook_url_is_redacted_for_readers(self) -> None:
+ summary = _scout(
+ source_id=str(self.scanner.id),
+ output_destinations={"webhook": {"url": "https://hooks.example.com/t/secret-token?k=v"}},
+ )
+ with (
+ patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[summary]),
+ patch(f"{_VIEWSET}.VisionActionViewSet._accessible_scanner_ids", return_value=[str(self.scanner.id)]),
+ patch(f"{_VIEWSET}.VisionActionViewSet._can_edit_scanner", return_value=False),
+ ):
+ response = self.client.get(self.base_url)
+ assert response.status_code == 200, response.json()
+ url = response.json()["results"][0]["delivery_config"][0]["url"]
+ assert url == "https://hooks.example.com/…"
+ assert "secret-token" not in url
+
+ def test_scanner_from_another_team_is_rejected(self) -> None:
+ other_team = Team.objects.create(organization=Organization.objects.create(name="Other"), name="Other")
+ foreign_scanner = ReplayScanner.objects.create(
+ team=other_team,
+ name="Foreign",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "x"},
+ model=ScannerModel.GEMINI_3_7_FLASH,
+ )
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Cross team",
+ "scanner": str(foreign_scanner.id),
+ "mode": "alert",
+ "alert_config": {"frequency": "every_match"},
+ },
+ format="json",
+ )
+ assert response.status_code == 400, response.json()
+ assert VisionAlertConfiguration.objects.for_team(other_team.id).count() == 0
+
+ def test_slack_integration_from_another_team_is_rejected(self) -> None:
+ other_team = Team.objects.create(organization=Organization.objects.create(name="Other2"), name="Other2")
+ foreign = Integration.objects.create(
+ team=other_team, kind="slack", integration_id="T_FOREIGN", created_by=self.user
+ )
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Borrowed integration",
+ "scanner": str(self.scanner.id),
+ "mode": "alert",
+ "alert_config": {"frequency": "every_match"},
+ "delivery_config": [{"type": "slack", "integration_id": foreign.id, "channel": "C9|#x"}],
+ },
+ format="json",
+ )
+ assert response.status_code == 400, response.json()
+
+ def test_non_https_webhook_is_rejected(self) -> None:
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Cleartext",
+ "scanner": str(self.scanner.id),
+ "mode": "alert",
+ "alert_config": {"frequency": "every_match"},
+ "delivery_config": [{"type": "webhook", "url": "http://example.com/hook"}],
+ },
+ format="json",
+ )
+ assert response.status_code == 400, response.json()
+
+ def test_list_hides_scanners_the_caller_cannot_access(self) -> None:
+ VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id, scanner=self.scanner, name="Hidden", kind=VisionAlertKind.MATCH, selection={}
+ )
+ with (
+ patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[]),
+ patch(f"{_VIEWSET}.VisionActionViewSet._accessible_scanner_ids", return_value=[]),
+ ):
+ response = self.client.get(self.base_url)
+ assert response.status_code == 200
+ assert response.json()["results"] == []
+
+ def test_patch_rebuilds_alert_destinations(self) -> None:
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id, scanner=self.scanner, name="Rewired", kind=VisionAlertKind.MATCH, selection={}
+ )
+ with (
+ patch(f"{_SHIM}.soft_delete_all_alert_destinations") as soft_delete,
+ patch(f"{_SHIM}.create_alert_destination_hog_functions") as create_destinations,
+ ):
+ response = self.client.patch(
+ f"{self.base_url}{alert.id}/",
+ {
+ "delivery_config": [
+ {"type": "slack", "integration_id": self.integration.id, "channel": "C_NEW|#moved"}
+ ]
+ },
+ format="json",
+ )
+ assert response.status_code == 200, response.json()
+ soft_delete.assert_called_once()
+ assert "C_NEW" in str(create_destinations.call_args.args[0][0].payload)
+
+ def test_enabled_alert_cap_counts_new_alerts(self) -> None:
+ with patch(f"{_SHIM}.MAX_ENABLED_ALERTS_PER_SCANNER", 1):
+ VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id, scanner=self.scanner, name="First", kind=VisionAlertKind.MATCH, selection={}
+ )
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Second",
+ "scanner": str(self.scanner.id),
+ "mode": "alert",
+ "alert_config": {"frequency": "every_match"},
+ },
+ format="json",
+ )
+ assert response.status_code == 400, response.json()
+
+ def test_scout_patch_refuses_edits_it_cannot_apply(self) -> None:
+ summary = _scout(source_id=str(self.scanner.id))
+ with patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[summary]):
+ response = self.client.patch(
+ f"{self.base_url}{summary.config_id}/", {"name": "Renamed digest"}, format="json"
+ )
+ assert response.status_code == 400, response.json()
+ assert "scout" in str(response.json()).lower()
+
+ def test_legacy_id_with_several_successors_updates_and_deletes_all(self) -> None:
+ alerts = [
+ VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ scanner=self.scanner,
+ name=f"Fanned {index}",
+ kind=VisionAlertKind.MATCH,
+ selection={},
+ )
+ for index in range(2)
+ ]
+ legacy = VisionAction.objects.unscoped().create(
+ team=self.team,
+ scanner=self.scanner,
+ name="Wide legacy alert",
+ mode=ActionMode.ALERT,
+ trigger_type=TriggerType.SCHEDULE,
+ enabled=False,
+ alert_config={"frequency": "every_match", "migrated_to": [str(a.id) for a in alerts]},
+ )
+ with patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[]):
+ response = self.client.patch(f"{self.base_url}{legacy.id}/", {"enabled": False}, format="json")
+ assert response.status_code == 200, response.json()
+ for alert in alerts:
+ alert.refresh_from_db()
+ assert alert.enabled is False
+
+ with patch(f"{_SHIM}.soft_delete_all_alert_destinations"):
+ response = self.client.delete(f"{self.base_url}{legacy.id}/")
+ assert response.status_code == 204
+ assert VisionAlertConfiguration.objects.for_team(self.team.id).count() == 0
+
+ def test_fanned_out_alert_checks_every_scanner_not_just_the_first(self) -> None:
+ second = ReplayScanner.objects.create(
+ team=self.team,
+ name="Restricted",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "x"},
+ model=ScannerModel.GEMINI_3_7_FLASH,
+ )
+ alerts = [
+ VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id, scanner=scanner, name=f"Fan {i}", kind=VisionAlertKind.MATCH, selection={}
+ )
+ for i, scanner in enumerate((self.scanner, second))
+ ]
+ legacy = VisionAction.objects.unscoped().create(
+ team=self.team,
+ scanner=self.scanner,
+ name="Wide",
+ mode=ActionMode.ALERT,
+ trigger_type=TriggerType.SCHEDULE,
+ enabled=False,
+ alert_config={"frequency": "every_match", "migrated_to": [str(a.id) for a in alerts]},
+ )
+
+ # The caller may edit the first successor's scanner but not the second's.
+ def only_first(scanner: Any, level: str = "editor", **kwargs: Any) -> bool:
+ return getattr(scanner, "id", None) != second.id
+
+ with (
+ patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[]),
+ patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.check_access_level_for_object",
+ side_effect=only_first,
+ ),
+ ):
+ response = self.client.delete(f"{self.base_url}{legacy.id}/")
+ assert response.status_code == 403, response.status_code
+ assert VisionAlertConfiguration.objects.for_team(self.team.id).count() == 2
+
+ def test_frequency_change_is_refused_rather_than_ignored(self) -> None:
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id, scanner=self.scanner, name="Match", kind=VisionAlertKind.MATCH, selection={}
+ )
+ response = self.client.patch(
+ f"{self.base_url}{alert.id}/",
+ {"alert_config": {"frequency": "on_breach", "threshold": 5, "direction": "above"}},
+ format="json",
+ )
+ assert response.status_code == 400, response.json()
+ alert.refresh_from_db()
+ assert alert.kind == VisionAlertKind.MATCH
+
+ def test_name_of_a_migrated_row_can_be_reused(self) -> None:
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id, scanner=self.scanner, name="Checkout alerts", kind=VisionAlertKind.MATCH, selection={}
+ )
+ VisionAction.objects.unscoped().create(
+ team=self.team,
+ scanner=self.scanner,
+ name="Checkout alerts",
+ mode=ActionMode.ALERT,
+ trigger_type=TriggerType.SCHEDULE,
+ enabled=False,
+ alert_config={"frequency": "every_match", "migrated_to": [str(alert.id)]},
+ )
+ with (
+ patch(f"{_SHIM}.soft_delete_all_alert_destinations"),
+ patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[]),
+ ):
+ assert self.client.delete(f"{self.base_url}{alert.id}/").status_code == 204
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Checkout alerts",
+ "scanner": str(self.scanner.id),
+ "mode": "alert",
+ "alert_config": {"frequency": "every_match"},
+ },
+ format="json",
+ )
+ assert response.status_code == 201, response.json()
+
+ def test_child_environment_key_cannot_reach_the_parent_teams_scouts(self) -> None:
+ with (
+ patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[]),
+ patch(
+ "products.signals.backend.scout_harness.views.ScoutCanonicalTeamAccessPermission.has_permission",
+ return_value=False,
+ ),
+ ):
+ listed = self.client.get(self.base_url)
+ created = self.client.post(
+ self.base_url,
+ {
+ "name": "Sneaky digest",
+ "scanner": str(self.scanner.id),
+ "mode": "group_summary",
+ "trigger_config": {"rrule": "FREQ=DAILY;BYHOUR=8;BYMINUTE=0", "timezone": "UTC"},
+ },
+ format="json",
+ )
+ assert listed.status_code == 403, listed.status_code
+ assert created.status_code == 403, created.status_code
+
+ def test_rollout_decision_is_evaluated_once_per_request(self) -> None:
+ # A flip between the gate in initial() and the handler would serve scouts with the
+ # canonical-team gate skipped, so the decision must be made once.
+ with patch("posthog.ph_client.feature_enabled_or_false", return_value=True) as flag:
+ response = self.client.get(f"{self.base_url}?scanner={self.scanner.id}")
+ assert response.status_code == 200, response.json()
+ assert flag.call_count == 1
+
+ def test_reenable_runs_the_state_machine(self) -> None:
+ from products.replay_vision.backend.models.vision_alert import VisionAlertEvent, VisionAlertState
+
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ scanner=self.scanner,
+ name="Firing",
+ kind=VisionAlertKind.METRIC,
+ threshold=1,
+ state=VisionAlertState.FIRING,
+ consecutive_failures=2,
+ selection={},
+ )
+ assert self.client.patch(f"{self.base_url}{alert.id}/", {"enabled": False}, format="json").status_code == 200
+ assert self.client.patch(f"{self.base_url}{alert.id}/", {"enabled": True}, format="json").status_code == 200
+ alert.refresh_from_db()
+ # A re-enabled alert starts clean; without the state machine it would still be FIRING.
+ assert alert.state == VisionAlertState.NOT_FIRING
+ assert alert.consecutive_failures == 0
+ kinds = set(VisionAlertEvent.objects.filter(alert=alert).values_list("kind", flat=True))
+ assert {VisionAlertEvent.Kind.ENABLE, VisionAlertEvent.Kind.DISABLE} <= kinds
+
+ def test_run_on_a_shim_served_row_does_not_crash(self) -> None:
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).create(
+ team_id=self.team.id, scanner=self.scanner, name="No run", kind=VisionAlertKind.MATCH, selection={}
+ )
+ with patch(f"{_SHIM}.signals_facade.list_scouts_for_source", return_value=[]):
+ response = self.client.post(f"{self.base_url}{alert.id}/run/", {}, format="json")
+ assert response.status_code == 400, response.status_code
+
+ def test_unflagged_requests_keep_legacy_behavior(self) -> None:
+ self._flag.stop()
+ with patch("posthog.ph_client.feature_enabled_or_false", return_value=False):
+ response = self.client.post(
+ self.base_url,
+ {
+ "name": "Legacy digest",
+ "scanner": str(self.scanner.id),
+ "mode": "group_summary",
+ "trigger_type": "schedule",
+ "trigger_config": {"rrule": "FREQ=DAILY;BYHOUR=8;BYMINUTE=0", "timezone": "UTC"},
+ },
+ format="json",
+ )
+ self._flag.start()
+ assert response.status_code == 201, response.json()
+ assert VisionAction.objects.unscoped().filter(team=self.team, name="Legacy digest").exists()
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index 3539855b7fc8..6c999500666c 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -115,6 +115,11 @@ export const getVisionActionsListUrl = (projectId: string, params?: VisionAction
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const visionActionsList = async (
projectId: string,
@@ -133,6 +138,11 @@ export const getVisionActionsCreateUrl = (projectId: string) => {
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const visionActionsCreate = async (
projectId: string,
@@ -153,6 +163,11 @@ export const getVisionActionsRetrieveUrl = (projectId: string, id: string) => {
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const visionActionsRetrieve = async (
projectId: string,
@@ -171,6 +186,11 @@ export const getVisionActionsPartialUpdateUrl = (projectId: string, id: string)
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const visionActionsPartialUpdate = async (
projectId: string,
@@ -192,6 +212,11 @@ export const getVisionActionsDestroyUrl = (projectId: string, id: string) => {
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const visionActionsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
return apiMutator<void>(getVisionActionsDestroyUrl(projectId, id), {
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index b5ba8ec64319..f3ba532f0ce8 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -11,6 +11,11 @@ import * as zod from 'zod'
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const visionActionsCreateBodyNameMax = 255
@@ -197,6 +202,11 @@ export const VisionActionsCreateBody = /* @__PURE__ */ zod
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const visionActionsPartialUpdateBodyNameMax = 255
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index 2506d8a17b05..88c7d4b3c447 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -1,7 +1,7 @@
import uuid
import dataclasses
from collections.abc import Callable, Sequence
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any
from django.conf import settings
@@ -948,3 +948,126 @@ def scout_reports_for_source(
)
)
return reports
+
+
+@frozen
+class ScoutSummary:
+ """One scout standing on another product's object, in the shape that product needs to render
+ or manage it without reaching into scout tables."""
+
+ config_id: str
+ skill_name: str
+ source_id: str | None
+ enabled: bool
+ run_cron_schedule: str | None
+ run_interval_minutes: int
+ output_destinations: dict[str, Any]
+ description: str
+ created_at: datetime
+ created_by_id: int | None
+ last_run_at: datetime | None
+
+
+def list_scouts_for_source(
+ team_id: int, source_product: str, source_ids: list[str] | None = None
+) -> list[ScoutSummary]:
+ """The scouts a product stood up on its own objects, oldest first.
+
+ `(source_product, source_id)` was recorded at creation and is not user-editable, so the rows
+ returned are exactly the ones the calling product owns. Descriptions come from the live skill;
+ a scout whose skill was archived comes back with an empty description, matching the scout UI.
+ """
+ # Imported inside the call for the same reason as `create_scout_for_source`: keeps the skills
+ # API surface off the facade's import path.
+ from products.skills.backend.models.skills import (
+ LLMSkill, # noqa: PLC0415 — keeps the API surface off the import path
+ )
+
+ configs_qs = SignalScoutConfig.objects.for_team(team_id).filter(source_product=source_product)
+ if source_ids is not None:
+ configs_qs = configs_qs.filter(source_id__in=source_ids)
+ configs = list(configs_qs.order_by("created_at"))
+ descriptions = dict(
+ LLMSkill.objects.filter(
+ team_id=team_id,
+ name__in=[config.skill_name for config in configs],
+ is_latest=True,
+ deleted=False,
+ ).values_list("name", "description")
+ )
+ return [
+ ScoutSummary(
+ config_id=str(config.id),
+ skill_name=config.skill_name,
+ source_id=config.source_id,
+ enabled=config.enabled,
+ run_cron_schedule=config.run_cron_schedule,
+ run_interval_minutes=config.run_interval_minutes,
+ output_destinations=config.output_destinations or {},
+ description=descriptions.get(config.skill_name, ""),
+ created_at=config.created_at,
+ created_by_id=config.created_by_id,
+ last_run_at=config.last_run_at,
+ )
+ for config in configs
+ ]
+
+
+def update_scout_for_source(
+ team_id: int,
+ source_product: str,
+ config_id: str,
+ *,
+ enabled: bool | None = None,
+ run_cron_schedule: str | None = None,
+ output_destinations: dict[str, Any] | None = None,
+) -> bool:
+ """Apply the schedule/enablement/delivery updates a source product may make to its own scout.
+
+ Returns False when no scout with that config id belongs to the source. The skill body is
+ deliberately not updatable here — prompt edits go through the scout surface, where the
+ skill-authoring bar applies.
+ """
+ config = SignalScoutConfig.objects.for_team(team_id).filter(id=config_id, source_product=source_product).first()
+ if config is None:
+ return False
+ update_fields: list[str] = ["updated_at"]
+ if enabled is not None and enabled != config.enabled:
+ config.enabled = enabled
+ update_fields.append("enabled")
+ if run_cron_schedule is not None and run_cron_schedule != config.run_cron_schedule:
+ config.run_cron_schedule = run_cron_schedule
+ config.schedule_changed_at = datetime.now(UTC)
+ update_fields += ["run_cron_schedule", "schedule_changed_at"]
+ if output_destinations is not None and output_destinations != config.output_destinations:
+ config.output_destinations = output_destinations
+ update_fields.append("output_destinations")
+ if len(update_fields) > 1:
+ config.save(update_fields=update_fields)
+ return True
+
+
+def delete_scout_for_source(*, team: "Team", source_product: str, config_id: str) -> bool:
+ """Retire a source-owned scout for good: archive its skill and remove its config.
+
+ Deleting only the config is not enough — the coordinator recreates a default config while the
+ skill exists — so the skill is archived in the same transaction. Returns False when no scout
+ with that config id belongs to the source.
+ """
+ from django.db import transaction # noqa: PLC0415 — keeps the API surface off the import path
+
+ from products.skills.backend.api.skill_services import ( # noqa: PLC0415 — keeps the API surface off the import path
+ LLMSkillNotFoundError,
+ archive_skill,
+ )
+
+ config = SignalScoutConfig.objects.for_team(team.id).filter(id=config_id, source_product=source_product).first()
+ if config is None:
+ return False
+ with transaction.atomic():
+ try:
+ archive_skill(team, config.skill_name)
+ except LLMSkillNotFoundError:
+ pass # Already archived; the config is the orphan being cleaned up.
+ config.delete()
+ return True
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 647f6fb48fbf..1f42671be4a7 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -10,6 +10,11 @@ import * as zod from 'zod'
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const VisionActionsListParams = /* @__PURE__ */ zod.object({
project_id: zod
@@ -27,6 +32,11 @@ export const VisionActionsListQueryParams = /* @__PURE__ */ zod.object({
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const VisionActionsCreateParams = /* @__PURE__ */ zod.object({
project_id: zod
@@ -221,6 +231,11 @@ export const VisionActionsCreateBody = /* @__PURE__ */ zod
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const VisionActionsRetrieveParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this vision action.'),
@@ -233,6 +248,11 @@ export const VisionActionsRetrieveParams = /* @__PURE__ */ zod.object({
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const VisionActionsPartialUpdateParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this vision action.'),
@@ -430,6 +450,11 @@ export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod
/**
* CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ *
+ * Once an organization is on the `replay-vision-alerts` flag, this surface is a compatibility
+ * shim over the new alerts and scouts systems (see `vision_actions_shim`): the request and
+ * response contract stays exactly as documented here, but nothing reads or writes VisionAction
+ * rows anymore. The runs endpoints keep serving the pre-migration run history.
*/
export const VisionActionsDestroyParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this vision action.'),
diff --git a/tach.toml b/tach.toml
index 98ca1eb100d4..1026f39f9272 100644
--- a/tach.toml
+++ b/tach.toml
@@ -708,6 +708,7 @@ depends_on = [
"products.event_definitions",
"products.experiments",
"products.exports",
+ "products.feature_flags",
"products.notifications",
"products.signals",
"products.tasks", "products.access_control",