:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(workflows): add facade and route callers through it (#107597)
Harley Alexanderd69478c69414
diff --git a/.agents/security.md b/.agents/security.mdindex ea2a1c2d18ad..a728365a9ff4 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -196,7 +196,7 @@ An app or admin page takes the matching list in `CSPMiddleware`.On PostHog Cloud, the app policy's `script-src` and `connect-src` name each PostHog host instead of `*.posthog.com`.A script or request that goes to another PostHog subdomain needs its host in the lists that `CSPMiddleware` passes to `narrowed_app_policy()`.Local runs, E2E runs and self-hosted installs keep the wildcards, so a missing host breaks only production.-A canvas artifact takes `artifact_csp()` in `products/canvas/backend/contract.py`, and a workflow message asset takes the header its endpoint sets in `products/workflows/backend/api/hog_flow.py`.+A canvas artifact takes `artifact_csp()` in `products/canvas/backend/contract.py`, and a workflow message asset takes the header its endpoint sets in `products/workflows/backend/presentation/views/hog_flow.py`.`CSPMiddleware` returns a view-set header untouched, so widening the app policy does nothing for those two.Say why the source is needed in a comment either way, then run `posthog/test/test_csp_middleware.py`.The `csp-header-outside-csp-middleware` semgrep rule blocks a `Content-Security-Policy` header set anywhere else.diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex 934933f5b2e7..a98e7c096564 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -93,7 +93,8 @@ products/isolation_baseline.txt @PostHog/team-devex# stay out, because a mistake there is visible rather than silent.products/cdp/backend/api/** @PostHog/team-workflowsproducts/cdp/backend/models/** @PostHog/team-workflows-products/workflows/backend/api/** @PostHog/team-workflows+products/workflows/backend/facade/** @PostHog/team-workflows+products/workflows/backend/presentation/** @PostHog/team-workflowsproducts/workflows/backend/models/** @PostHog/team-workflowsproducts/messaging/backend/api/** @PostHog/team-workflowsproducts/messaging/backend/models/** @PostHog/team-workflowsdiff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.pyindex e57859ed10b3..a137fff61bcc 100644--- a/ee/hogai/context/entity_search/test/test_context.py+++ b/ee/hogai/context/entity_search/test/test_context.py@@ -24,7 +24,7 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.facade.api import record_insight_viewsfrom products.product_analytics.backend.facade.models import Insightfrom products.surveys.backend.models import Survey-from products.workflows.backend.facade.testing import create_workflow_for_test+from products.workflows.backend.facade.testing import acreate_workflow_for_testfrom ee.hogai.context import AssistantContextManagerfrom ee.hogai.context.entity_search.context import SEARCH_LIMIT, EntitySearchContext@@ -334,7 +334,7 @@ class TestEntitySearchContext(NonAtomicBaseTest):created_by=self.user,type=Survey.SurveyType.POPOVER,)- await create_workflow_for_test(+ await acreate_workflow_for_test(team_id=self.team.id, created_by_id=self.user.id, name="deleted workflow", status="archived")@@ -410,13 +410,13 @@ class TestEntitySearchContext(NonAtomicBaseTest):assert entities[0]["extra_fields"]["name"] == "List Dashboard"async def test_list_entities_workflow_surfaces_status_and_hides_archived(self):- await create_workflow_for_test(+ await acreate_workflow_for_test(team_id=self.team.id, created_by_id=self.user.id, name="welcome email", status="active")- await create_workflow_for_test(+ await acreate_workflow_for_test(team_id=self.team.id, created_by_id=self.user.id, name="win-back draft", status="draft")- await create_workflow_for_test(+ await acreate_workflow_for_test(team_id=self.team.id, created_by_id=self.user.id, name="old campaign", status="archived")@@ -440,7 +440,7 @@ class TestEntitySearchContext(NonAtomicBaseTest):for index in range(SEARCH_LIMIT)])- await create_workflow_for_test(+ await acreate_workflow_for_test(team_id=self.team.id,created_by_id=self.user.id,name="Priority workflow",diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.pyindex 97e2ab779a5c..8f1b097f5b2a 100644--- a/posthog/admin/admins/team_admin.py+++ b/posthog/admin/admins/team_admin.py@@ -39,7 +39,6 @@ from posthog.models import Teamfrom posthog.models.activity_logging.activity_log import ActivityContextBase, ActivityLog, Detail, log_activityfrom posthog.models.group_type_mapping import invalidate_group_types_cachefrom posthog.models.remote_config import RemoteConfig-from posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import DEPRECATED_ATTRSfrom posthog.personhog_client.client import get_personhog_clientfrom posthog.personhog_client.converters import proto_group_type_mapping_to_dict@@ -68,12 +67,15 @@ from products.notifications.backend.facade.api import (TargetType,create_notification,)-from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig-from products.workflows.backend.services.email_sending_tier import recompute_email_sending_tier_for_team-from products.workflows.backend.utils.email_sending_tiers import (- MIN_EMAIL_SENDING_TIER,+from products.workflows.backend.facade.api import (+ ensure_workflows_config,+ get_email_sending_state,get_email_sending_tier_limits,max_email_sending_tier,+ recompute_email_sending_tier,+ set_email_sending_tier,+ suspend_email_sending,+ unsuspend_email_sending,)logger = get_logger()@@ -786,36 +788,11 @@ class TeamAdmin(admin.ModelAdmin):messages.error(request, "Reason is required")return redirect(suspend_url)- # Row-lock the config while checking + flipping so two concurrent submits (retried POST,- # two open admin tabs) can't both pass the idempotency check and both dispatch the- # customer email + notification. Side effects stay outside the atomic block.- get_or_create_team_extension(team, TeamWorkflowsConfig)- with transaction.atomic():- config = TeamWorkflowsConfig.objects.select_for_update().get(team_id=team.pk)- if config.email_sending_suspended_at is not None:- already_suspended_at = config.email_sending_suspended_at- suspended_at = None- else:- already_suspended_at = None- suspended_at = timezone.now()- config.email_sending_suspended_at = suspended_at- config.email_sending_suspension_reason = reason- # Drop the trust tier now, in the same locked transaction, rather than at the next- # daily sweep: a suspension is the strongest signal there is, and the tier sets how- # fast the team may send once reinstated. A suspension always maps to the lowest- # tier, and that mapping needs no metrics, so write it here instead of through the- # recompute. This does not depend on ClickHouse and it also covers pinned teams,- # which the periodic sweep skips.- config.email_sending_tier = MIN_EMAIL_SENDING_TIER- config.email_sending_tier_updated_at = suspended_at- config.save(- update_fields=[- "email_sending_suspended_at",- "email_sending_suspension_reason",- "email_sending_tier",- "email_sending_tier_updated_at",- ]- )+ # The facade row-locks the config while checking + flipping, so concurrent submits can't+ # both dispatch the customer email + notification. Side effects stay outside that lock.+ change = suspend_email_sending(team.pk, reason)+ already_suspended_at = change.previously_suspended_at+ suspended_at = change.changed_atif already_suspended_at is not None:self.message_user(@@ -866,19 +843,8 @@ class TeamAdmin(admin.ModelAdmin):raise PermissionDeniedteam_url = reverse("admin:posthog_team_change", args=[object_id])- # Symmetric to suspend: lock the row, re-check, flip inside the transaction so racing- # submits can't both fire the re-enable side effects.- with transaction.atomic():- config = TeamWorkflowsConfig.objects.select_for_update().filter(team_id=team.pk).first()- if not config or config.email_sending_suspended_at is None:- was_suspended = False- unsuspended_at = None- else:- was_suspended = True- unsuspended_at = timezone.now()- config.email_sending_suspended_at = None- config.email_sending_suspension_reason = ""- config.save(update_fields=["email_sending_suspended_at", "email_sending_suspension_reason"])+ unsuspended_at = unsuspend_email_sending(team.pk).changed_at+ was_suspended = unsuspended_at is not Noneif not was_suspended:self.message_user(request, f"Email sending for team '{team.name}' is not suspended.", level=messages.INFO)@@ -914,12 +880,12 @@ class TeamAdmin(admin.ModelAdmin):def email_sending_suspension_state(self, team: Team):if not team.pk:return "-"- config = TeamWorkflowsConfig.objects.filter(team_id=team.pk).first()- if config and config.email_sending_suspended_at:+ state = get_email_sending_state(team.pk)+ if state and state.suspended_at:return format_html('<span style="color:red"><strong>Suspended</strong></span> at {} — {}',- config.email_sending_suspended_at.isoformat(),- config.email_sending_suspension_reason or "no reason recorded",+ state.suspended_at.isoformat(),+ state.suspension_reason or "no reason recorded",)return format_html("<em>Sending enabled</em>")@@ -927,8 +893,8 @@ class TeamAdmin(admin.ModelAdmin):def email_sending_suspension_actions(self, team: Team):if not team.pk:return "-"- config = TeamWorkflowsConfig.objects.filter(team_id=team.pk).first()- is_suspended = bool(config and config.email_sending_suspended_at)+ state = get_email_sending_state(team.pk)+ is_suspended = bool(state and state.suspended_at)# nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)return mark_safe(render_to_string(@@ -946,10 +912,10 @@ class TeamAdmin(admin.ModelAdmin):def email_sending_tier_state(self, team: Team) -> str:if not team.pk:return "-"- config = TeamWorkflowsConfig.objects.filter(team_id=team.pk).first()- tier = config.email_sending_tier if config else 0+ state = get_email_sending_state(team.pk)+ tier = state.tier if state else 0limits = get_email_sending_tier_limits(tier)- updated_at = config.email_sending_tier_updated_at if config else None+ updated_at = state.tier_updated_at if state else Noneallowlist_note = ""if team.pk in settings.HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS:# A saved tier changes nothing while the team sits on the legacy allowlist, which the@@ -969,7 +935,7 @@ class TeamAdmin(admin.ModelAdmin):f"{limits.per_day:,}",f"{limits.max_batch_audience:,}",updated_at.isoformat() if updated_at else "never (team has not been evaluated yet)",- "yes" if config and config.email_sending_tier_pinned else "no",+ "yes" if state and state.tier_pinned else "no",settings.WORKFLOWS_EMAIL_TIER_MODE,mark_safe(allowlist_note), # noqa: S308 - static admin-only string, no user input)@@ -978,13 +944,13 @@ class TeamAdmin(admin.ModelAdmin):def email_sending_tier_actions(self, team: Team) -> str:if not team.pk:return "-"- config = TeamWorkflowsConfig.objects.filter(team_id=team.pk).first()+ state = get_email_sending_state(team.pk)tiers = [{"tier": tier,"per_hour": f"{get_email_sending_tier_limits(tier).per_hour:,}","per_day": f"{get_email_sending_tier_limits(tier).per_day:,}",- "selected": tier == (config.email_sending_tier if config else 0),+ "selected": tier == (state.tier if state else 0),}for tier in range(max_email_sending_tier() + 1)]@@ -994,7 +960,7 @@ class TeamAdmin(admin.ModelAdmin):"admin/posthog/team/email_sending_tier_actions.html",{"tiers": tiers,- "pinned": bool(config and config.email_sending_tier_pinned),+ "pinned": bool(state and state.tier_pinned),"set_tier_url": reverse("admin:posthog_team_set_email_sending_tier", args=[team.pk]),"recompute_url": reverse("admin:posthog_team_recompute_email_sending_tier", args=[team.pk]),},@@ -1021,23 +987,7 @@ class TeamAdmin(admin.ModelAdmin):return redirect(team_url)pinned = request.POST.get("pinned") == "on"- get_or_create_team_extension(team, TeamWorkflowsConfig)- with transaction.atomic():- config = TeamWorkflowsConfig.objects.select_for_update().get(team_id=team.pk)- previous_tier = config.email_sending_tier- config.email_sending_tier = tier- config.email_sending_tier_pinned = pinned- if tier != previous_tier:- # Only a real tier change restarts the dwell clock. Toggling the pin alone must not- # push the next earned promotion out by the full dwell.- config.email_sending_tier_updated_at = timezone.now()- config.save(- update_fields=[- "email_sending_tier",- "email_sending_tier_pinned",- "email_sending_tier_updated_at",- ]- )+ previous_tier = set_email_sending_tier(team.pk, tier=tier, pinned=pinned)logger.info("admin_set_email_sending_tier",@@ -1069,9 +1019,9 @@ class TeamAdmin(admin.ModelAdmin):# A team that only sent through the API may have no config row yet, and the sweep skips a# rowless team. Create the row first so the recompute can move it off tier 0, matching the# suspend and set-tier actions.- get_or_create_team_extension(team, TeamWorkflowsConfig)+ ensure_workflows_config(team.pk)try:- decision = recompute_email_sending_tier_for_team(team.id)+ decision = recompute_email_sending_tier(team.id)except Exception:logger.exception("admin_recompute_email_sending_tier_failed", team_id=team.id)self.message_user(request, "Could not recompute the tier. Check the logs.", level=messages.ERROR)diff --git a/posthog/admin/test_admin.py b/posthog/admin/test_admin.pyindex 970c75316ed9..6222f07d5ae5 100644--- a/posthog/admin/test_admin.py+++ b/posthog/admin/test_admin.py@@ -29,9 +29,6 @@ from products.product_analytics.backend.facade.models import Insightfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Surveyfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow-from products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate-from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJobclass TestOAuthSidebarRegrouping(BaseTest):@@ -220,9 +217,6 @@ class TestProductAdminRegistration:@pytest.mark.parametrize("model",[- HogFlow,- HogFlowTemplate,- HogFlowBatchJob,HogFunction,Plugin,PluginConfig,diff --git a/posthog/admin/test_team_admin.py b/posthog/admin/test_team_admin.pyindex c805e749322a..b45e0d71bbff 100644--- a/posthog/admin/test_team_admin.py+++ b/posthog/admin/test_team_admin.py@@ -30,8 +30,8 @@ from posthog.models.team.team import Teamfrom posthog.personhog_client.fake_client import FakePersonHogClientfrom posthog.personhog_client.proto import GetGroupTypeMappingsByProjectIdRequest-from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig-from products.workflows.backend.services.email_sending_tier import TierDecision+from products.workflows.backend.facade.contracts import TierDecision+from products.workflows.backend.facade.team_extension import TeamWorkflowsConfigdef _attach_messages(request) -> None:@@ -716,7 +716,7 @@ class TestTeamAdminEmailSendingSuspension(BaseTest):# bar"), which misled staff when the real reason was the dwell or a cooldown.request = self._post()with patch(- "posthog.admin.admins.team_admin.recompute_email_sending_tier_for_team",+ "posthog.admin.admins.team_admin.recompute_email_sending_tier",return_value=TierDecision(team_id=self.team.id, previous_tier=4, new_tier=4, reason="too_soon"),):response = self.admin.recompute_email_sending_tier_view(request, str(self.team.pk))@@ -729,9 +729,7 @@ class TestTeamAdminEmailSendingSuspension(BaseTest):# rowless team, so the recompute action must create the row before it runs.TeamWorkflowsConfig.objects.filter(team_id=self.team.pk).delete()assert self._config() is None- with patch(- "posthog.admin.admins.team_admin.recompute_email_sending_tier_for_team", return_value=None- ) as mock_recompute:+ with patch("posthog.admin.admins.team_admin.recompute_email_sending_tier", return_value=None) as mock_recompute:response = self.admin.recompute_email_sending_tier_view(self._post(), str(self.team.pk))assert response.status_code == 302mock_recompute.assert_called_once_with(self.team.id)diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 43df69ed5d70..128662963890 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -123,7 +123,7 @@ from products.cdp.backend.services.integration_usage import get_enabled_hog_funcfrom products.slack_app.backend.services.slack_auth import SLACK_AUTH_FAILURE_CODESfrom products.tasks.backend.facade.api import get_in_progress_runs_for_github_integrationfrom products.tasks.backend.facade.contracts import InProgressGithubRunsDTO-from products.workflows.backend.services.integration_usage import get_active_hog_flows_using_integration+from products.workflows.backend.facade.api import get_active_workflows_using_integrationlogger = structlog.get_logger(__name__)@@ -1395,7 +1395,7 @@ class IntegrationViewSet(return super().get_throttles()def perform_destroy(self, instance: Integration) -> None:- flows_using_integration = get_active_hog_flows_using_integration(+ flows_using_integration = get_active_workflows_using_integration(team_id=instance.team_id, integration_id=instance.id)functions_using_integration = get_enabled_hog_functions_using_integration(diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 4861758336c9..17d6e97e6e8c 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -90,12 +90,12 @@ from posthog.utils import (from products.ai_training.backend.facade.api import queue_person_training_deletionfrom products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.util import get_all_cohort_ids_by_person_uuid-from products.workflows.backend.api.message_assets import (+from products.workflows.backend.facade.api import get_workflow_names+from products.workflows.backend.presentation.views.message_assets import (MessageAssetSerializer,PersonMessageAssetsRequestSerializer,fetch_message_assets_for_person,)-from products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)@@ -1673,13 +1673,9 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# Single lookup for every workflow referenced by this page of rows so the tab shows# human-readable names instead of raw UUIDs. Deleted workflows drop out of the map# and the row's `function_name` stays empty — the frontend falls back to `function_id`.- # HogFlow.id is a UUID column; ClickHouse function_id is a plain string, so coerce- # both sides to string when building the lookup dict.- function_ids = {row.function_id for row in data}- name_by_id = {- str(pk): (name or "")- for pk, name in HogFlow.objects.filter(team_id=self.team_id, id__in=function_ids).values_list("id", "name")- }+ # HogFlow.id is a UUID column; ClickHouse function_id is a plain string, so the names come+ # back keyed by the string id.+ name_by_id = get_workflow_names(team_id=self.team_id, workflow_ids={row.function_id for row in data})enriched = [dataclasses.replace(row, function_name=name_by_id.get(row.function_id, "")) for row in data]return response.Response(MessageAssetSerializer(enriched, many=True).data)diff --git a/posthog/api/search.py b/posthog/api/search.pyindex e18429d96c3c..11ada1086fc6 100644--- a/posthog/api/search.py+++ b/posthog/api/search.py@@ -26,7 +26,7 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookfrom products.product_analytics.backend.facade.models import Insightfrom products.surveys.backend.models import Survey-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.facade.api import search_workflowsLIMIT = 25@@ -98,12 +98,12 @@ ENTITY_MAP: dict[str, EntityConfig] = {"search_fields": {"name": "A", "description": "C"},"extra_fields": ["name", "description"],},- "hog_flow": {- "klass": HogFlow,- "search_fields": {"name": "A", "description": "C"},- "extra_fields": ["name", "description"],- },}++# Workflows are searched through the workflows facade rather than unioned by model class, so+# they are not in ENTITY_MAP. `search_entities` merges them in when this entity is requested.+WORKFLOW_ENTITY = "hog_flow"+SEARCHABLE_ENTITIES = [*ENTITY_MAP, WORKFLOW_ENTITY]"""Map of entity names to their class, search_fields and extra_fields.@@ -115,7 +115,7 @@ class QuerySerializer(serializers.Serializer):"""Validates and formats query params."""q = serializers.CharField(required=False, default="")- entities = serializers.MultipleChoiceField(required=False, choices=list(ENTITY_MAP.keys()))+ entities = serializers.MultipleChoiceField(required=False, choices=SEARCHABLE_ENTITIES)include_counts = serializers.BooleanField(required=False, default=True)def validate_q(self, value: str):@@ -144,7 +144,7 @@ class SearchViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):params = query_serializer.validated_data# get entities to search from params or default to all entities- entities = set(params["entities"]) if params["entities"] else set(ENTITY_MAP.keys())+ entities = set(params["entities"]) if params["entities"] else set(SEARCHABLE_ENTITIES)query = params["q"]include_counts = params["include_counts"]@@ -160,6 +160,7 @@ class SearchViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):response_data: dict[str, Any] = {"results": results}if counts is not None:+ counts.setdefault(WORKFLOW_ENTITY, None)response_data["counts"] = countsreturn Response(response_data)@@ -175,6 +176,9 @@ def search_entities(include_counts: bool = True,annotate_access_levels: UserAccessControl | None = None,) -> tuple[list[dict[str, Any]], dict[str, int | None] | None, int | None]:+ workflows_requested = WORKFLOW_ENTITY in entities+ entities = entities - {WORKFLOW_ENTITY}+# empty queryset to union things onto itcounts: dict[str, int | None] = dict.fromkeys(entity_map) if include_counts else {}qs = (@@ -199,19 +203,48 @@ def search_entities(if include_counts:counts[entity_name] = klass_qs.count()- # order by rank- if query:- qs = qs.order_by("-rank")+ # order by rank. Ordering an empty union by a column no member added raises, which only+ # happens here when workflows were the one entity requested.+ if entities or not workflows_requested:+ if query:+ qs = qs.order_by("-rank")+ else:+ qs = qs.order_by("type", F("_sort_name").asc(nulls_first=True))++ if not workflows_requested:+ # Get total count before pagination (only when needed)+ total_count = qs.count() if include_counts else None+ results = cast(list[dict[str, Any]], list(qs[offset : offset + limit]))+ if annotate_access_levels is not None:+ _annotate_user_access_levels(results, entity_map, annotate_access_levels)else:- qs = qs.order_by("type", F("_sort_name").asc(nulls_first=True))+ workflow_results, workflow_count = search_workflows(+ project_id=project_id,+ query=query,+ access_control=view.user_access_control,+ limit=offset + limit,+ include_archived=True,+ with_access_levels=annotate_access_levels is not None,+ include_count=include_counts,+ )+ for result in workflow_results:+ result["extra_fields"].pop("status", None)+ if include_counts:+ counts[WORKFLOW_ENTITY] = workflow_count++ union_results = cast(list[dict[str, Any]], list(qs[: offset + limit])) if entities else []+ if annotate_access_levels is not None:+ _annotate_user_access_levels(union_results, entity_map, annotate_access_levels)+ total_count = ((qs.count() if entities else 0) + workflow_count) if include_counts else None- # Get total count before pagination (only when needed)- total_count = qs.count() if include_counts else None+ # Both inputs arrive in the database order, so a stable sort on the leading key keeps it.+ merged = [*union_results, *workflow_results]+ if query:+ merged.sort(key=lambda result: result["rank"], reverse=True)+ else:+ merged.sort(key=lambda result: result["type"])+ results = merged[offset : offset + limit]- # Apply pagination- results = cast(list[dict[str, Any]], list(qs[offset : offset + limit]))- if annotate_access_levels is not None:- _annotate_user_access_levels(results, entity_map, annotate_access_levels)for result in results:result.pop("_sort_name", None)result.pop("_pk", None)diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 7762afe4c4f3..b450b4a0a318 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -142,7 +142,8 @@ from products.web_analytics.backend.hogql_queries.custom_bot_definitions importvalidate_rule as validate_custom_bot_rule,validate_rule_set as validate_custom_bot_rule_set,)-from products.workflows.backend.models.team_workflows_config import EmailTrackingConsentMode, TeamWorkflowsConfig+from products.workflows.backend.facade.enums import EMAIL_TRACKING_CONSENT_MODE_CHOICES+from products.workflows.backend.facade.team_extension import TeamWorkflowsConfigtracer = trace.get_tracer(__name__)@@ -961,7 +962,7 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr),)email_tracking_consent_mode = serializers.ChoiceField(- choices=EmailTrackingConsentMode.choices,+ choices=EMAIL_TRACKING_CONSENT_MODE_CHOICES,required=False,help_text=("Recipient-consent enforcement for open/click tracking on marketing workflow emails. "diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex eba6ea3b1ba7..9a2403bf36d1 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -84,7 +84,8 @@ from products.batch_exports.backend.facade.contracts import DestinationTypefrom products.cdp.backend.models import HogFunctionfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.tasks.backend.facade.contracts import InProgressGithubRunsDTO-from products.workflows.backend.models import HogFlow+from products.workflows.backend.facade.contracts import WorkflowSummary+from products.workflows.backend.facade.testing import create_workflow_for_testdef _p256_public_pem() -> str:@@ -621,10 +622,9 @@ class TestEmailIntegration:self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")- @patch("products.workflows.backend.providers.SESProvider")- def test_integration_from_domain(self, mock_ses_provider_class):- mock_client = MagicMock()- mock_ses_provider_class.return_value = mock_client+ @patch("products.workflows.backend.facade.api.verify_ses_email_domain")+ @patch("products.workflows.backend.facade.api.create_ses_email_domain")+ def test_integration_from_domain(self, mock_create_email_domain, mock_verify_email_domain):integration = EmailIntegration.create_native_integration({**self.valid_config, "mail_from_subdomain": "youmustnothavelikedmyemail", "provider": "ses"},@@ -646,17 +646,16 @@ class TestEmailIntegration:assert integration.sensitive_config == {}assert integration.created_by == self.user- mock_client.create_email_domain.assert_called_once_with(+ mock_create_email_domain.assert_called_once_with("posthog.com",mail_from_subdomain="youmustnothavelikedmyemail",team_id=self.team.id,org_team_ids=[self.team.id],)- @patch("products.workflows.backend.providers.SESProvider")- def test_email_verify_returns_ses_result(self, mock_ses_provider_class):- mock_client = MagicMock()- mock_ses_provider_class.return_value = mock_client+ @patch("products.workflows.backend.facade.api.verify_ses_email_domain")+ @patch("products.workflows.backend.facade.api.create_ses_email_domain")+ def test_email_verify_returns_ses_result(self, mock_create_email_domain, mock_verify_email_domain):# Mock the verify_email_domain method to return a test resultexpected_result = {@@ -685,7 +684,7 @@ class TestEmailIntegration:},],}- mock_client.verify_email_domain.return_value = expected_result+ mock_verify_email_domain.return_value = expected_resultintegration = EmailIntegration.create_native_integration({**self.valid_config, "provider": "ses"},@@ -698,7 +697,7 @@ class TestEmailIntegration:assert verification_result == expected_result- mock_client.verify_email_domain.assert_called_once_with(+ mock_verify_email_domain.assert_called_once_with("posthog.com", mail_from_subdomain="feedback", team_id=self.team.id)@@ -712,17 +711,16 @@ class TestEmailIntegration:"provider": "ses",}- @patch("products.workflows.backend.providers.SESProvider")- def test_email_verify_updates_integration(self, mock_ses_provider_class):- mock_client = MagicMock()- mock_ses_provider_class.return_value = mock_client+ @patch("products.workflows.backend.facade.api.verify_ses_email_domain")+ @patch("products.workflows.backend.facade.api.create_ses_email_domain")+ def test_email_verify_updates_integration(self, mock_create_email_domain, mock_verify_email_domain):# Mock the verify_email_domain method to return a test resultexpected_result = {"status": "success","dnsRecords": [],}- mock_client.verify_email_domain.return_value = expected_result+ mock_verify_email_domain.return_value = expected_resultintegration = EmailIntegration.create_native_integration({**self.valid_config, "provider": "ses"},@@ -735,7 +733,7 @@ class TestEmailIntegration:assert verification_result == expected_result- mock_client.verify_email_domain.assert_called_once_with(+ mock_verify_email_domain.assert_called_once_with("posthog.com", mail_from_subdomain="feedback", team_id=self.team.id)@@ -749,19 +747,20 @@ class TestEmailIntegration:"provider": "ses",}- @patch("products.workflows.backend.providers.SESProvider")- def test_email_verify_updates_all_other_integrations_with_same_domain(self, mock_ses_provider_class, settings):+ @patch("products.workflows.backend.facade.api.verify_ses_email_domain")+ @patch("products.workflows.backend.facade.api.create_ses_email_domain")+ def test_email_verify_updates_all_other_integrations_with_same_domain(+ self, mock_create_email_domain, mock_verify_email_domain, settings+ ):settings.SES_ACCESS_KEY_ID = "test_access_key"settings.SES_SECRET_ACCESS_KEY = "test_secret_key"- mock_client = MagicMock()- mock_ses_provider_class.return_value = mock_client# Mock the verify_email_domain method to return a test resultexpected_result = {"status": "success","dnsRecords": [],}- mock_client.verify_email_domain.return_value = expected_result+ mock_verify_email_domain.return_value = expected_resultintegration1 = EmailIntegration.create_native_integration({**self.valid_config, "provider": "ses"},@@ -6630,9 +6629,9 @@ class TestIntegrationDeletionWorkflowGuard:},]- def _create_flow(self, status: str = "active", actions: list | None = None) -> HogFlow:- return HogFlow.objects.create(- team=self.team,+ def _create_flow(self, status: str = "active", actions: list | None = None) -> WorkflowSummary:+ return create_workflow_for_test(+ team_id=self.team.id,name="Welcome Email Sequence",status=status,actions=actions if actions is not None else self._email_actions(self.integration.id),@@ -6854,8 +6853,8 @@ class TestIntegrationDeletionHogFunctionGuard:def test_destroy_blocked_message_includes_workflows_and_functions(self, client: HttpClient):self._create_function(name="Slack notifier")- HogFlow.objects.create(- team=self.team,+ create_workflow_for_test(+ team_id=self.team.id,name="Slack flow",status="active",actions=[diff --git a/posthog/api/test/test_search.py b/posthog/api/test/test_search.pyindex b4e5fe9c15ae..edead0222e0f 100644--- a/posthog/api/test/test_search.py+++ b/posthog/api/test/test_search.py@@ -5,7 +5,7 @@ from unittest.mock import Mockfrom django.db import connectionfrom django.test.utils import CaptureQueriesContext-from posthog.api.search import ENTITY_MAP, class_queryset, search_entities+from posthog.api.search import ENTITY_MAP, SEARCHABLE_ENTITIES, class_queryset, search_entitiesfrom posthog.helpers.full_text_search import build_search_vector, process_queryfrom posthog.models import OrganizationMembership, Team, User@@ -16,7 +16,7 @@ from products.event_definitions.backend.models.event_definition import EventDefifrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookfrom products.product_analytics.backend.facade.models import Insight-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.facade.testing import create_workflow_for_testclass TestSearch(APIBaseTest):@@ -191,9 +191,9 @@ class TestSearch(APIBaseTest):self.assertEqual(results[0]["extra_fields"]["name"], "second feature")def test_hog_flows(self):- HogFlow.objects.create(name="first workflow", team=self.team)- HogFlow.objects.create(name="second workflow", team=self.team)- HogFlow.objects.create(name="third workflow", team=self.team)+ create_workflow_for_test(team_id=self.team.id, name="first workflow")+ create_workflow_for_test(team_id=self.team.id, name="second workflow")+ create_workflow_for_test(team_id=self.team.id, name="third workflow")response = self.client.get("/api/projects/@current/search?q=sec&entities=hog_flow")@@ -276,7 +276,7 @@ class TestSearch(APIBaseTest):with CaptureQueriesContext(connection) as ctx_with:search_entities(- entities=set(ENTITY_MAP.keys()),+ entities=set(SEARCHABLE_ENTITIES),query="sec",project_id=self.team.project_id,view=mock_view,@@ -286,7 +286,7 @@ class TestSearch(APIBaseTest):with CaptureQueriesContext(connection) as ctx_without:search_entities(- entities=set(ENTITY_MAP.keys()),+ entities=set(SEARCHABLE_ENTITIES),query="sec",project_id=self.team.project_id,view=mock_view,@@ -295,7 +295,8 @@ class TestSearch(APIBaseTest):)assert len(ctx_with) - len(ctx_without) >= 13- assert len(ctx_without) == 1+ # One query for the unioned entities, one for the workflows merged in through the facade.+ assert len(ctx_without) == 2def test_search_entities_returns_total_count(self):for i in range(5):diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 53169a2775d2..40f5e5c3147c 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -48,7 +48,7 @@ from posthog.utils import get_instance_realmfrom products.access_control.backend.models.access_control import AccessControlfrom products.conversations.backend.playbook import compose_support_playbookfrom products.dashboards.backend.models.dashboard import Dashboard-from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig+from products.workflows.backend.facade.team_extension import TeamWorkflowsConfigdef team_api_test_factory():diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex c6392aa8fb21..46de9b159f71 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -106,7 +106,7 @@ from products.warehouse_sources.backend.facade.models import (ExternalDataSource,)from products.warehouse_sources.backend.facade.types import DIRECT_ENGINE_BY_SOURCE_TYPE-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.facade.testing import create_workflow_for_test# Only directly-queryable tables are team-scoped via a WHERE clause. Namespace nodes such as# `information_schema` carry no `table` of their own (just child catalog tables computed per-query),@@ -522,8 +522,8 @@ def _create_error_tracking_symbol_set(team: Team, label: str) -> uuid.UUID:return create_symbol_set(team_id=team.pk, ref=f"symbol_set_{label}", storage_ptr=f"symbolsets/{label}")-def _create_hog_flow(team: Team, label: str) -> HogFlow:- return HogFlow.objects.create(team=team, name=f"flow_{label}")+def _create_hog_flow(team: Team, label: str) -> str:+ return create_workflow_for_test(team_id=team.id, name=f"flow_{label}").iddef _create_message_category(team: Team, label: str):diff --git a/posthog/management/commands/test/test_set_recorder_script.py b/posthog/management/commands/test/test_set_recorder_script.pyindex 879b3a24aa82..71a34532d63d 100644--- a/posthog/management/commands/test/test_set_recorder_script.py+++ b/posthog/management/commands/test/test_set_recorder_script.py@@ -148,7 +148,7 @@ class TestSetRecorderScriptCommand(BaseTest):# each save is a single UPDATE, which is this test's floor.with (mock.patch("products.cdp.backend.tasks.hog_functions.refresh_affected_hog_functions.delay"),- mock.patch("products.workflows.backend.tasks.hog_flows.refresh_affected_hog_flows.delay"),+ mock.patch("products.workflows.backend.facade.tasks.refresh_affected_hog_flows.delay"),mock.patch("posthog.models.team.team.set_team_in_cache"),):call_command(diff --git a/posthog/models/integration/email.py b/posthog/models/integration/email.pyindex 14a80dc4f5ab..c4696e2b17c9 100644--- a/posthog/models/integration/email.py+++ b/posthog/models/integration/email.py@@ -1,6 +1,6 @@"""Native email-sending integration (SES / maildev) and its cleanup signal."""-from typing import TYPE_CHECKING, Any+from typing import Anyfrom django.conf import settingsfrom django.db import models, transaction@@ -16,9 +16,6 @@ from posthog.plugins.plugin_server_api import reload_integrations_on_workersfrom . import model-if TYPE_CHECKING:- from products.workflows.backend.providers import SESProvider-class EmailIntegration:integration: model.Integration@@ -28,14 +25,6 @@ class EmailIntegration:raise Exception("EmailIntegration init called with Integration with wrong 'kind'")self.integration = integration- @property- def ses_provider(self) -> "SESProvider":- from products.workflows.backend.providers import (- SESProvider, # noqa: PLC0415 — keeps the heavy dep off the import path- )-- return SESProvider()-@classmethoddef create_native_integration(cls, config: dict, team_id: int, organization_id: str, created_by: User | None = None@@ -60,13 +49,12 @@ class EmailIntegration:# Create domain in the appropriate providerif provider == "ses":- from products.workflows.backend.providers import (- SESProvider, # noqa: PLC0415 — keeps the heavy dep off the import path+ from products.workflows.backend.facade.api import (+ create_ses_email_domain, # noqa: PLC0415 — keeps the workflows facade off the model import path)- ses = SESProvider()org_team_ids = list(Team.objects.filter(organization_id=organization_id).values_list("id", flat=True))- ses.create_email_domain(+ create_ses_email_domain(domain,mail_from_subdomain=mail_from_subdomain,team_id=team_id,@@ -111,12 +99,11 @@ class EmailIntegration:# Update domain in the appropriate providerif provider == "ses":- from products.workflows.backend.providers import (- SESProvider, # noqa: PLC0415 — keeps the heavy dep off the import path+ from products.workflows.backend.facade.api import (+ update_ses_mail_from_subdomain, # noqa: PLC0415 — keeps the workflows facade off the model import path)- ses = SESProvider()- ses.update_mail_from_subdomain(domain, mail_from_subdomain=mail_from_subdomain)+ update_ses_mail_from_subdomain(domain, mail_from_subdomain=mail_from_subdomain)elif provider == "maildev" and settings.DEBUG:passelse:@@ -139,17 +126,21 @@ class EmailIntegration:# Use the appropriate provider for verificationif provider == "ses":- verification_result = self.ses_provider.verify_email_domain(+ from products.workflows.backend.facade.api import (+ verify_ses_email_domain, # noqa: PLC0415 — keeps the workflows facade off the model import path+ )++ verification_result = verify_ses_email_domain(domain, mail_from_subdomain=mail_from_subdomain, team_id=self.integration.team_id)elif provider == "maildev":- from products.workflows.backend.providers import (- MAILDEV_MOCK_DNS_RECORDS, # noqa: PLC0415 — keeps the heavy dep off the import path+ from products.workflows.backend.facade.api import (+ get_maildev_mock_dns_records, # noqa: PLC0415 — keeps the workflows facade off the model import path)verification_result = {"status": "success",- "dnsRecords": MAILDEV_MOCK_DNS_RECORDS,+ "dnsRecords": get_maildev_mock_dns_records(),}else:raise ValueError(f"Invalid provider: {provider}")diff --git a/posthog/models/integration/twilio.py b/posthog/models/integration/twilio.pyindex 7cfcb4448951..8e0e0876425f 100644--- a/posthog/models/integration/twilio.py+++ b/posthog/models/integration/twilio.py@@ -1,34 +1,26 @@"""Twilio integration."""-from typing import TYPE_CHECKING-from rest_framework.exceptions import ValidationErrorfrom . import model-if TYPE_CHECKING:- from products.workflows.backend.providers import TwilioProvider-class TwilioIntegration:integration: model.Integration- twilio_provider: "TwilioProvider"def __init__(self, integration: model.Integration) -> None:- from products.workflows.backend.providers import (- TwilioProvider, # noqa: PLC0415 — keeps the heavy dep off the import path- )-if integration.kind != "twilio":raise Exception("TwilioIntegration init called with Integration with wrong 'kind'")self.integration = integration- self.twilio_provider = TwilioProvider(- account_sid=self.integration.config["account_sid"],- auth_token=self.integration.sensitive_config["auth_token"],- )+ self._account_sid = self.integration.config["account_sid"]+ self._auth_token = self.integration.sensitive_config["auth_token"]def list_twilio_phone_numbers(self) -> list[dict]:- twilio_phone_numbers = self.twilio_provider.get_phone_numbers()+ from products.workflows.backend.facade.api import (+ get_twilio_phone_numbers, # noqa: PLC0415 — keeps the workflows facade off the model import path+ )++ twilio_phone_numbers = get_twilio_phone_numbers(account_sid=self._account_sid, auth_token=self._auth_token)if not twilio_phone_numbers:raise Exception(f"There was an internal error")@@ -36,7 +28,11 @@ class TwilioIntegration:return twilio_phone_numbersdef integration_from_keys(self) -> model.Integration:- account_info = self.twilio_provider.get_account_info()+ from products.workflows.backend.facade.api import (+ get_twilio_account_info, # noqa: PLC0415 — keeps the workflows facade off the model import path+ )++ account_info = get_twilio_account_info(account_sid=self._account_sid, auth_token=self._auth_token)if not account_info.get("sid"):raise ValidationError({"account_info": "Failed to get account info"})diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.pyindex b6a88bbf02d6..a2dfc9fb70f4 100644--- a/posthog/models/product_intent/product_intent.py+++ b/posthog/models/product_intent/product_intent.py@@ -27,7 +27,6 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.facade.models import Insightfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Survey-from products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = structlog.get_logger(__name__)@@ -268,8 +267,10 @@ class ProductIntent(UUIDTModel, RootTeamMixin):return Falsedef has_activated_workflows(self) -> bool:+ from products.workflows.backend.facade.api import has_active_workflows # noqa: PLC0415+# At least one workflow needs to be active (not just drafted)- return HogFlow.objects.filter(team=self.team, status=HogFlow.State.ACTIVE).exists()+ return has_active_workflows(team_id=self.team_id)def check_and_update_activation(self, skip_reporting: bool = False) -> bool:# If the intent is already activated, we don't need to check againdiff --git a/posthog/models/team/team.py b/posthog/models/team/team.pyindex 013ad95ef2e7..997cac5ad11c 100644--- a/posthog/models/team/team.py+++ b/posthog/models/team/team.py@@ -747,7 +747,7 @@ class Team(UUIDTClassicModel):@cached_propertydef workflows_config(self):- from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig+ from products.workflows.backend.facade.team_extension import TeamWorkflowsConfigreturn get_or_create_team_extension(self, TeamWorkflowsConfig)diff --git a/posthog/models/test/integration/test_email.py b/posthog/models/test/integration/test_email.pyindex 38680b953d1f..c92d9eb3a0e9 100644--- a/posthog/models/test/integration/test_email.py+++ b/posthog/models/test/integration/test_email.py@@ -2,7 +2,7 @@import pytestfrom posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import patchfrom disposable_email_domains import blocklist as disposable_email_domains_listfrom parameterized import parameterized@@ -12,11 +12,9 @@ from posthog.models.integration import EmailIntegration, Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team-from products.workflows.backend.providers import SESProvider-class TestEmailIntegrationDomainValidation(BaseTest):- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ @patch("products.workflows.backend.facade.api.create_ses_email_domain")def test_successful_domain_creation_ses(self, mock_create_email_domain):mock_create_email_domain.return_value = {"status": "success", "domain": "successdomain.com"}config = {"email": "[email protected]", "name": "Test User", "provider": "ses"}@@ -30,8 +28,8 @@ class TestEmailIntegrationDomainValidation(BaseTest):assert integration.config["name"] == "Test User"assert integration.config["verified"] is False- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- @patch("products.workflows.backend.providers.SESProvider.verify_email_domain")+ @patch("products.workflows.backend.facade.api.create_ses_email_domain")+ @patch("products.workflows.backend.facade.api.verify_ses_email_domain")def test_duplicate_domain_in_another_organization(self, mock_create_email_domain, mock_verify_email_domain):mock_create_email_domain.return_value = {"status": "success", "domain": "successdomain.com"}mock_verify_email_domain.return_value = {"status": "verified", "domain": "example.com"}@@ -50,7 +48,7 @@ class TestEmailIntegrationDomainValidation(BaseTest):)assert "already exists in another organization" in str(exc.value)- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ @patch("products.workflows.backend.facade.api.create_ses_email_domain")def test_duplicate_domain_in_same_organization_allowed(self, mock_create_email_domain):mock_create_email_domain.return_value = {"status": "success", "domain": "example.com"}# Create an integration with a domain in one team@@ -91,7 +89,7 @@ class TestEmailIntegrationDomainValidation(BaseTest):assert disposable_domain in str(exc.value)assert "not supported" in str(exc.value)- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ @patch("products.workflows.backend.facade.api.create_ses_email_domain")def test_cross_org_guard_blocks_mixed_case_domain(self, mock_create_email_domain):mock_create_email_domain.return_value = {"status": "success", "domain": "example.com"}other_org = Organization.objects.create(name="other org")@@ -112,7 +110,7 @@ class TestEmailIntegrationDomainValidation(BaseTest):)assert "already exists in another organization" in str(exc.value)- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ @patch("products.workflows.backend.facade.api.create_ses_email_domain")def test_stored_domain_is_lowercased(self, mock_create_email_domain):mock_create_email_domain.return_value = {"status": "success", "domain": "successdomain.com"}integration = EmailIntegration.create_native_integration(@@ -144,175 +142,9 @@ class TestEmailIntegrationDomainValidation(BaseTest):assert "not supported" in str(exc.value)-class TestEmailIntegrationCrossTenantStaleVerification(BaseTest):- def _build_ses_provider(self, tenants_for_domain: dict[str, list[str]] | None = None) -> SESProvider:- patcher = patch("products.workflows.backend.providers.ses.boto3.client")- patcher.start()- self.addCleanup(patcher.stop)-- provider = SESProvider()- provider.ses_client = MagicMock()- provider.ses_v2_client = MagicMock()- provider.sts_client = MagicMock()- provider.sts_client.get_caller_identity.return_value = {"Account": "123456789012"}-- provider.ses_client.verify_domain_identity.return_value = {"VerificationToken": "tok"}- provider.ses_client.verify_domain_dkim.return_value = {"DkimTokens": ["t1", "t2", "t3"]}- provider.ses_client.set_identity_mail_from_domain.return_value = {}-- def _list_resource_tenants(ResourceArn: str) -> dict:- domain = ResourceArn.split("/")[-1]- return {"ResourceTenants": [{"TenantName": t} for t in (tenants_for_domain or {}).get(domain, [])]}-- provider.ses_v2_client.list_resource_tenants.side_effect = _list_resource_tenants- return provider-- def _set_global_ses_success(self, provider, domain: str) -> None:- provider.ses_client.get_identity_verification_attributes.return_value = {- "VerificationAttributes": {domain: {"VerificationStatus": "Success"}}- }- provider.ses_client.get_identity_dkim_attributes.return_value = {- "DkimAttributes": {domain: {"DkimVerificationStatus": "Success"}}- }- provider.ses_client.get_identity_mail_from_domain_attributes.return_value = {- "MailFromDomainAttributes": {domain: {"MailFromDomainStatus": "Success"}}- }-- @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")- def test_verify_email_domain_requires_team_tenant_association(self, mock_resolver_cls):- provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})- self._set_global_ses_success(provider, "partner.com")- dmarc_answer = MagicMock()- dmarc_answer.strings = [b"v=DMARC1; p=none;"]- mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]-- result_team_a = provider.verify_email_domain("partner.com", "feedback", team_id=1)- result_team_b = provider.verify_email_domain("partner.com", "feedback", team_id=999)-- assert result_team_a["status"] == "success"- assert result_team_b["status"] == "pending"-- @patch("products.workflows.backend.providers.SESProvider.delete_identity")- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_destroy_email_integration_deletes_ses_identity(self, mock_create_email_domain, mock_delete_identity):- from posthog.api.integration import IntegrationViewSet-- mock_create_email_domain.return_value = {"status": "success"}- integration = EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Owner"},- team_id=self.team.id,- organization_id=str(self.organization.id),- created_by=self.user,- )-- with self.captureOnCommitCallbacks(execute=True):- IntegrationViewSet().perform_destroy(integration)-- mock_delete_identity.assert_called_once_with("partner.com")- assert not Integration.objects.filter(pk=integration.pk).exists()-- @patch("products.workflows.backend.providers.SESProvider.delete_identity")- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_destroy_email_integration_skips_ses_delete_when_sibling_exists(- self, mock_create_email_domain, mock_delete_identity- ):- from posthog.api.integration import IntegrationViewSet-- mock_create_email_domain.return_value = {"status": "success"}- sibling_team = Team.objects.create(organization=self.organization, name="sibling team")- EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Sibling"},- team_id=sibling_team.id,- organization_id=str(self.organization.id),- created_by=self.user,- )- integration = EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Owner"},- team_id=self.team.id,- organization_id=str(self.organization.id),- created_by=self.user,- )-- with self.captureOnCommitCallbacks(execute=True):- IntegrationViewSet().perform_destroy(integration)-- assert mock_delete_identity.call_count == 0-- def test_create_email_domain_rejects_foreign_tenant_owner(self):- provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})-- with pytest.raises(Exception) as exc:- provider.create_email_domain("partner.com", "feedback", team_id=999, org_team_ids=[999])- assert "already associated with another organization" in str(exc.value)-- def test_create_email_domain_allows_sibling_team_in_same_org(self):- provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})-- provider.create_email_domain(- "partner.com",- "feedback",- team_id=2,- org_team_ids=[1, 2, 3, 4, 5],- )-- @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_takeover_after_owner_deletes_integration_is_blocked(self, mock_create_email_domain, mock_resolver_cls):- from posthog.api.integration import IntegrationViewSet-- mock_create_email_domain.return_value = {"status": "success"}- dmarc_answer = MagicMock()- dmarc_answer.strings = [b"v=DMARC1; p=none;"]- mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]-- org_a = Organization.objects.create(name="org a")- team_a = Team.objects.create(organization=org_a, name="team a")- org_b = Organization.objects.create(name="org b")- team_b = Team.objects.create(organization=org_b, name="team b")-- integration_a = EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Owner A"},- team_id=team_a.id,- organization_id=str(org_a.id),- created_by=self.user,- )- with patch("products.workflows.backend.providers.SESProvider.delete_identity") as mock_delete:- with self.captureOnCommitCallbacks(execute=True):- IntegrationViewSet().perform_destroy(integration_a)- mock_delete.assert_called_once_with("partner.com")-- integration_b = EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Attacker B"},- team_id=team_b.id,- organization_id=str(org_b.id),- created_by=self.user,- )-- provider = self._build_ses_provider(tenants_for_domain={"partner.com": []})- self._set_global_ses_success(provider, "partner.com")-- email_b = EmailIntegration(integration_b)- with patch.object(type(email_b), "ses_provider", new=provider):- result = email_b.verify()-- assert result["status"] == "pending"- integration_b.refresh_from_db()- assert integration_b.config.get("verified") is False-- def test_aws_account_id_is_cached_per_provider(self):- provider = self._build_ses_provider()- provider.sts_client.get_caller_identity.reset_mock()-- for _ in range(5):- provider._identity_arn("partner.com")- provider._identity_arn("other.com")-- assert provider.sts_client.get_caller_identity.call_count == 1--class TestEmailIntegrationSESCleanupOnDelete(BaseTest):def _create_email_integration(self, email: str, team_id: int, organization_id: str) -> Integration:- with patch("products.workflows.backend.providers.SESProvider.create_email_domain"):+ with patch("products.workflows.backend.facade.api.create_ses_email_domain"):return EmailIntegration.create_native_integration({"email": email, "name": "Test"},team_id=team_id,@@ -320,7 +152,7 @@ class TestEmailIntegrationSESCleanupOnDelete(BaseTest):created_by=self.user,)- @patch("products.workflows.backend.providers.SESProvider.delete_identity")+ @patch("posthog.tasks.integrations.delete_ses_identity")def test_team_cascade_delete_cleans_up_ses_identity(self, mock_delete_identity):team = Team.objects.create(organization=self.organization, name="doomed team")self._create_email_integration("[email protected]", team.id, str(self.organization.id))@@ -330,7 +162,7 @@ class TestEmailIntegrationSESCleanupOnDelete(BaseTest):mock_delete_identity.assert_called_once_with("partner.com")- @patch("products.workflows.backend.providers.SESProvider.delete_identity")+ @patch("posthog.tasks.integrations.delete_ses_identity")def test_cascade_delete_skips_ses_cleanup_while_domain_still_in_use(self, mock_delete_identity):team = Team.objects.create(organization=self.organization, name="doomed team")self._create_email_integration("[email protected]", team.id, str(self.organization.id))diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.pyindex 16b75783be3a..d3220a12cb88 100644--- a/posthog/models/test/test_product_intent.py+++ b/posthog/models/test/test_product_intent.py@@ -30,7 +30,7 @@ from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.facade.models import Insightfrom products.surveys.backend.models import Survey-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.facade.testing import create_workflow_for_testclass TestProductIntent(BaseTest):@@ -842,21 +842,21 @@ class TestProductIntent(BaseTest):def test_has_activated_workflows_with_active_workflow(self):self.product_intent.product_type = ProductKey.WORKFLOWSself.product_intent.save()- HogFlow.objects.create(team=self.team, name="Test workflow", status=HogFlow.State.ACTIVE)+ create_workflow_for_test(team_id=self.team.id, name="Test workflow", status="active")assert self.product_intent.has_activated_workflows() is Truedef test_has_not_activated_workflows_with_draft_workflow_only(self):self.product_intent.product_type = ProductKey.WORKFLOWSself.product_intent.save()- HogFlow.objects.create(team=self.team, name="Test workflow", status=HogFlow.State.DRAFT)+ create_workflow_for_test(team_id=self.team.id, name="Test workflow", status="draft")assert self.product_intent.has_activated_workflows() is Falsedef test_has_not_activated_workflows_with_archived_workflow_only(self):self.product_intent.product_type = ProductKey.WORKFLOWSself.product_intent.save()- HogFlow.objects.create(team=self.team, name="Test workflow", status=HogFlow.State.ARCHIVED)+ create_workflow_for_test(team_id=self.team.id, name="Test workflow", status="archived")assert self.product_intent.has_activated_workflows() is Falsediff --git a/posthog/tasks/integrations.py b/posthog/tasks/integrations.pyindex dfa892fa0b1a..129932bc6447 100644--- a/posthog/tasks/integrations.py+++ b/posthog/tasks/integrations.py@@ -10,7 +10,7 @@ from posthog.models.integration import (from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueue-from products.workflows.backend.providers import SESProvider+from products.workflows.backend.facade.api import delete_ses_identity@shared_task(ignore_result=True, queue=CeleryQueue.INTEGRATIONS.value)@@ -123,7 +123,7 @@ def delete_ses_identity_if_unused(domain: str) -> None:if Integration.objects.filter(kind="email", config__domain=domain).exists():return- SESProvider().delete_identity(domain)+ delete_ses_identity(domain)@shared_task(ignore_result=True, queue=CeleryQueue.INTEGRATIONS.value)diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 2dd3a70a20d7..58e811d0f9f1 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -148,10 +148,12 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import (report_stuck_heatmap_screenshots,)from products.wizard.backend.facade.tasks import reconcile_wizard_runs-from products.workflows.backend.tasks.email_sending_tiers import recompute_workflows_email_sending_tiers-from products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputation-from products.workflows.backend.tasks.ses_tenant_state import reconcile_ses_tenant_states-from products.workflows.backend.tasks.workflow_email_health import sweep_workflow_email_deliverability+from products.workflows.backend.facade.tasks import (+ poll_ses_account_reputation,+ recompute_workflows_email_sending_tiers,+ reconcile_ses_tenant_states,+ sweep_workflow_email_deliverability,+)TWENTY_FOUR_HOURS = 24 * 60 * 60diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex a4448e91103f..4309b4a850f5 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -130,7 +130,6 @@ posthog/hogql_queries/utils/test/test_formula_ast.py::TestFormulaASTposthog/hogql_queries/utils/test/test_sampling.py::TestQueriesUtilposthog/kafka_client/test/test_client.py::KafkaClientRoundtripTestCaseposthog/management/commands/test/test_analyze_migration_risk.py::TestAnalyzeMigrationRisk-posthog/management/commands/test/test_backfill_workflows_slack_integration.py::TestRewriteSlackWorkspaceInActionsposthog/management/commands/test/test_base_hypercache_command.py::TestVerificationResultsErrorReportingposthog/management/commands/test/test_survey_cohort_bytecode_stl.py::TestBytecodeWalkerposthog/models/filters/test/test_filter_mixins.py::TestFilterMixins@@ -390,4 +389,5 @@ products/web_analytics/dags/tests/test_cache_warming.py::TestMaybeExpandWarmingDproducts/web_analytics/dags/tests/test_cache_warming.py::TestMaybeOptIntoLazyPrecomputeproducts/web_analytics/dags/tests/test_cache_warming.py::TestSplitWarmableQueriesproducts/web_analytics/dags/tests/test_cache_warming.py::TestWarmableQueriesCaching+products/workflows/backend/test/test_backfill_workflows_slack_integration.py::TestRewriteSlackWorkspaceInActionsproducts/workflows/backend/test/test_email_sending_tier.py::TestEmailSendingTierDecisiondiff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex 3d4e2e81b966..ff0eb95546ad 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -24,8 +24,8 @@ LIST_VIEWSETS_WITHOUT_DIRECT_SHARED_PAGINATION = {"products.managed_migrations.backend.api.support_batch_imports.BatchImportSupportViewSet","products.product_analytics.backend.presentation.insight_ee.EnterpriseInsightsViewSet","products.reminders.backend.api.reminder.ReminderViewSet",- "products.workflows.backend.api.hog_flow.HogFlowViewSet",- "products.workflows.backend.api.hog_flow_template.PublicHogFlowTemplateViewSet",+ "products.workflows.backend.presentation.views.hog_flow.HogFlowViewSet",+ "products.workflows.backend.presentation.views.hog_flow_template.PublicHogFlowTemplateViewSet",}EXISTING_CUSTOM_LIST_VIEWSETS = {@@ -258,9 +258,9 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.wizard.backend.presentation.registry.views.WizardRegistryViewSet","products.wizard.backend.presentation.runs.views.WizardRunViewSet","products.wizard.backend.presentation.sessions.views.WizardSessionViewSet",- "products.workflows.backend.api.hog_flow.HogFlowViewSet",- "products.workflows.backend.api.hog_flow_template.HogFlowTemplateViewSet",- "products.workflows.backend.api.hog_flow_template.PublicHogFlowTemplateViewSet",+ "products.workflows.backend.presentation.views.hog_flow.HogFlowViewSet",+ "products.workflows.backend.presentation.views.hog_flow_template.HogFlowTemplateViewSet",+ "products.workflows.backend.presentation.views.hog_flow_template.PublicHogFlowTemplateViewSet",}diff --git a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py b/posthog/test/repo_invariants/test_serializer_timestamp_guard.pyindex bff849693808..dc89374ca063 100644--- a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py+++ b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py@@ -146,7 +146,7 @@ REVIEWED_WRITABLE: dict[str, str] = {"products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.end_date": "Client stops the survey by setting this","products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.response_sampling_start_date": "Client sets when response sampling starts","products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.start_date": "Client launches the survey by setting this",- "products.workflows.backend.api.hog_flow.HogFlowScheduleSerializer.starts_at": "Client sets when the schedule starts",+ "products.workflows.backend.presentation.views.hog_flow.HogFlowScheduleSerializer.starts_at": "Client sets when the schedule starts",}# Views and serializers the guard cannot read, each with a reason. An entry hides partdiff --git a/posthog/urls.py b/posthog/urls.pyindex 5e023cfec0d7..893dbb45184e 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -75,7 +75,7 @@ from products.tasks.backend.facade.agent_proxy import agent_proxy_callbackfrom products.tasks.backend.presentation.views.gateway_generation_requests import gateway_generation_requestfrom products.user_interviews.backend.presentation.webhooks import start_call as user_interviews_start_callfrom products.warehouse_sources.backend.presentation.views.public_source_configs import PublicSourceConfigViewSet-from products.workflows.backend.api import hog_flow, hog_flow_template+from products.workflows.backend.presentation.views import hog_flow, hog_flow_templatefrom .utils import opt_slash_pathfrom .views import (diff --git a/posthog/views.py b/posthog/views.pyindex d5191bcc8887..4d1b6baf734e 100644--- a/posthog/views.py+++ b/posthog/views.py@@ -72,7 +72,7 @@ from products.messaging.backend.models.message_preferences import (PreferenceStatus,)from products.messaging.backend.services.customerio_sync_service import sync_preferences_to_customerio-from products.workflows.backend.models.team_workflows_config import EmailTrackingConsentMode+from products.workflows.backend.facade.enums import EmailTrackingConsentModelogger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.pyindex b370330e76ff..95728c4aa684 100644--- a/products/ai_observability/backend/api/evaluation_reports.py+++ b/products/ai_observability/backend/api/evaluation_reports.py@@ -45,7 +45,7 @@ from products.ai_observability.backend.models.evaluation_reports import (EvaluationReportRun,)from products.ai_observability.backend.models.evaluations import Evaluation, EvaluationTarget-from products.workflows.backend.utils.rrule_utils import validate_rrule+from products.workflows.backend.facade.api import validate_rrulelogger = structlog.get_logger(__name__)diff --git a/products/ai_observability/backend/models/evaluation_reports.py b/products/ai_observability/backend/models/evaluation_reports.pyindex 963d7c7b9da6..a4ec908255b1 100644--- a/products/ai_observability/backend/models/evaluation_reports.py+++ b/products/ai_observability/backend/models/evaluation_reports.py@@ -7,7 +7,7 @@ from dateutil.rrule import rrulestrfrom posthog.models.utils import UUIDTModel-from products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule+from products.workflows.backend.facade.api import compute_next_occurrences, validate_rrulefrom .evaluation_configs import REPORTABLE_OUTPUT_TYPES_BY_TARGETdiff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex fbf0e148dc0e..2c0b8b8853ec 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -33,7 +33,8 @@ from products.tasks.backend.facade.access import DesktopAccessDecisionfrom products.tasks.backend.facade.ai_run_defaults import update_team_ai_run_preferences, update_user_ai_run_preferencesfrom products.tasks.backend.facade.contracts import ComputeQuotaDenialReasonfrom products.tasks.backend.models import Channel, Task, TaskRun, TaskThreadMessage-from products.workflows.backend.models import HogFlow+from products.workflows.backend.facade.api import get_workflow_summary+from products.workflows.backend.facade.testing import create_workflow_for_testclass InMemoryStorage:@@ -2228,8 +2229,8 @@ class TestCanvasActions(CanvasAPIBaseTest):label="canvas-actions", user=self.user, secure_value=hash_key_value(raw_key), scopes=scopes)self.client.logout()- workflow = HogFlow.objects.create(- team=self.team, name="Loop", status="active", trigger={}, actions=[], edges=[]+ workflow = create_workflow_for_test(+ team_id=self.team.id, name="Loop", status="active", trigger={}, actions=[], edges=[])response = self.client.post(@@ -2251,8 +2252,8 @@ class TestCanvasActions(CanvasAPIBaseTest):def test_workflow_verbs_flip_status_and_refuse_other_projects(self):canvas_id = self._actions_canvas(verbs=("workflows.pause", "workflows.resume"))- loop = HogFlow.objects.create(- team=self.team,+ loop = create_workflow_for_test(+ team_id=self.team.id,name="Plan",status="active",trigger={"type": "schedule"},@@ -2260,27 +2261,23 @@ class TestCanvasActions(CanvasAPIBaseTest):edges=[],)other_team = self.organization.teams.create(name="other")- foreign = HogFlow.objects.create(- team=other_team, name="Elsewhere", status="active", trigger={}, actions=[], edges=[]+ foreign = create_workflow_for_test(+ team_id=other_team.id, name="Elsewhere", status="active", trigger={}, actions=[], edges=[])paused = self._invoke(canvas_id, "workflows.pause", {"workflow_ids": [str(loop.id)]})assert paused.status_code == status.HTTP_200_OK, paused.json()assert paused.json()["result"] == {"workflows": [{"id": str(loop.id), "status": "draft"}]}- loop.refresh_from_db()- assert loop.status == "draft"+ assert get_workflow_summary(team_id=self.team.id, workflow_id=loop.id).status == "draft"resumed = self._invoke(canvas_id, "workflows.resume", {"workflow_ids": [str(loop.id)]})assert resumed.status_code == status.HTTP_200_OK, resumed.json()- loop.refresh_from_db()- assert loop.status == "active"+ assert get_workflow_summary(team_id=self.team.id, workflow_id=loop.id).status == "active"refused = self._invoke(canvas_id, "workflows.pause", {"workflow_ids": [str(loop.id), str(foreign.id)]})assert refused.status_code == status.HTTP_404_NOT_FOUND, refused.json()- foreign.refresh_from_db()- assert foreign.status == "active"- loop.refresh_from_db()- assert loop.status == "active"+ assert get_workflow_summary(team_id=other_team.id, workflow_id=foreign.id).status == "active"+ assert get_workflow_summary(team_id=self.team.id, workflow_id=loop.id).status == "active"@parameterized.expand([@@ -2302,15 +2299,14 @@ class TestCanvasActions(CanvasAPIBaseTest):)def test_resume_rejects_an_invalid_draft(self, actions):canvas_id = self._actions_canvas(verbs=("workflows.resume",))- loop = HogFlow.objects.create(- team=self.team, name="Invalid", status="draft", trigger={}, actions=actions, edges=[]+ loop = create_workflow_for_test(+ team_id=self.team.id, name="Invalid", status="draft", trigger={}, actions=actions, edges=[])response = self._invoke(canvas_id, "workflows.resume", {"workflow_ids": [str(loop.id)]})assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()- loop.refresh_from_db()- assert loop.status == "draft"+ assert get_workflow_summary(team_id=self.team.id, workflow_id=loop.id).status == "draft"def test_registry_lists_every_verb_with_authoring_docs(self):# Agents build against this endpoint instead of a skill file, so a verbdiff --git a/products/customer_analytics/backend/apps.py b/products/customer_analytics/backend/apps.pyindex 618dd87376a6..db6e082aa4a9 100644--- a/products/customer_analytics/backend/apps.py+++ b/products/customer_analytics/backend/apps.py@@ -16,10 +16,8 @@ class CustomerAnalyticsConfig(AppConfig):workflows importing this product (the dependency runs the other way). The queryimpls are imported lazily so HogQL stays off the django.setup() path."""- from products.workflows.backend.services.account_audience import (- AccountAudienceFilters,- register_account_audience_provider,- )+ from products.workflows.backend.facade.account_audience import register_account_audience_provider+ from products.workflows.backend.facade.contracts import AccountAudienceFiltersclass _Provider:def count_accounts(self, team, filters: AccountAudienceFilters) -> int:diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex dee9095585d0..caf35d8d1189 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -187,11 +187,11 @@ from products.notebooks.backend.facade import (# the notebooks legacy-leak interface block.from products.notebooks.backend.models import ResourceNotebookfrom products.warehouse_sources.backend.facade.hooks import WarehouseBinding, saved_query_binding, schema_binding-from products.workflows.backend.services.template_input_usage import (- HogFlowReference,+from products.workflows.backend.facade.api import (filter_hog_flow_references_by_access_level,get_hog_flows_referencing_template_input_keys,)+from products.workflows.backend.facade.contracts import HogFlowReferencefrom . import contracts@@ -206,7 +206,7 @@ if TYPE_CHECKING:from posthog.models.user import Userfrom products.customer_analytics.backend.models import CustomPropertyValue- from products.workflows.backend.services.account_audience import AccountAudienceFilters+ from products.workflows.backend.facade.contracts import AccountAudienceFiltersdef _to_account_properties(properties: _ModelAccountProperties) -> contracts.AccountProperties:diff --git a/products/customer_analytics/backend/hogql_queries/account_audience.py b/products/customer_analytics/backend/hogql_queries/account_audience.pyindex ad6ddd6ff5dc..6c84c9483887 100644--- a/products/customer_analytics/backend/hogql_queries/account_audience.py+++ b/products/customer_analytics/backend/hogql_queries/account_audience.py@@ -18,10 +18,7 @@ from posthog.models.user import Userfrom posthog.synthetic_user import SyntheticUserfrom products.customer_analytics.backend.models import CustomPropertyDefinition, DataType-from products.workflows.backend.services.account_audience import (- AccountAudienceCustomPropertyFilter,- AccountAudienceFilters,-)+from products.workflows.backend.facade.contracts import AccountAudienceCustomPropertyFilter, AccountAudienceFiltersclass _AudiencePrincipal(SyntheticUser):diff --git a/products/customer_analytics/backend/hogql_queries/test/test_account_audience.py b/products/customer_analytics/backend/hogql_queries/test/test_account_audience.pyindex 6ab4ebb166ff..58436215f58a 100644--- a/products/customer_analytics/backend/hogql_queries/test/test_account_audience.py+++ b/products/customer_analytics/backend/hogql_queries/test/test_account_audience.py@@ -17,10 +17,7 @@ from products.customer_analytics.backend.facade.api import (from products.customer_analytics.backend.logic import relationships as relationships_logicfrom products.customer_analytics.backend.models import AccountRelationshipDefinition, CustomPropertyValuefrom products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition-from products.workflows.backend.services.account_audience import (- AccountAudienceCustomPropertyFilter,- AccountAudienceFilters,-)+from products.workflows.backend.facade.contracts import AccountAudienceCustomPropertyFilter, AccountAudienceFilters@override_settings(IN_UNIT_TESTING=True)diff --git a/products/customer_analytics/backend/test/test_account_audience_provider.py b/products/customer_analytics/backend/test/test_account_audience_provider.pyindex 0566e013d7f0..8805d854ee58 100644--- a/products/customer_analytics/backend/test/test_account_audience_provider.py+++ b/products/customer_analytics/backend/test/test_account_audience_provider.py@@ -3,7 +3,10 @@ from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTestfrom django.test import override_settingsfrom products.customer_analytics.backend.test.factories import create_account-from products.workflows.backend.services.account_audience import get_account_audience_count, get_account_audience_page+from products.workflows.backend.facade.testing import (+ count_account_audience_for_test,+ list_account_audience_page_for_test,+)@override_settings(IN_UNIT_TESTING=True)@@ -13,5 +16,5 @@ class TestAccountAudienceProviderWiring(ClickhouseTestMixin, NonAtomicBaseTest):create_account(team_id=self.team.id, name="No key", external_id=None)filters = {"audience_type": "accounts"}- assert get_account_audience_page(self.team, filters, cursor=None) == ["a1"]- assert get_account_audience_count(self.team, filters) == 1+ assert list_account_audience_page_for_test(team_id=self.team.id, filters=filters, cursor=None) == ["a1"]+ assert count_account_audience_for_test(team_id=self.team.id, filters=filters) == 1diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.pyindex b43bfe80deb3..e563df06401d 100644--- a/products/customer_analytics/backend/test/test_custom_property_values.py+++ b/products/customer_analytics/backend/test/test_custom_property_values.py@@ -39,7 +39,7 @@ from products.customer_analytics.backend.models import ()from products.customer_analytics.backend.models.custom_property_value import ACTIVE_VALUE_CONSTRAINT_NAMEfrom products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition-from products.workflows.backend.models import HogFlow+from products.workflows.backend.facade.testing import create_workflow_for_testLOGIC_MODULE = "products.customer_analytics.backend.logic.custom_property_values"@@ -709,8 +709,8 @@ class TestCustomPropertyDefinitionReferences(BaseTest):return uacdef _create_workflow_setting(self, definition_id: str, *, name: str = "Onboarding", status: str = "active"):- return HogFlow.objects.create(- team=self.team,+ return create_workflow_for_test(+ team_id=self.team.id,name=name,status=status,actions=[diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex e31eb8f8d09f..4bcad46eb6aa 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -65,7 +65,8 @@ from products.product_analytics.backend.facade.models import Insightfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable-from products.workflows.backend.models import HogFlow+from products.workflows.backend.facade.contracts import WorkflowSummary+from products.workflows.backend.facade.testing import create_workflow_for_testclass TestCustomerProfileConfigViewSet(APIBaseTest):@@ -2075,9 +2076,9 @@ class TestCustomPropertyDefinitionAccessControl(APIBaseTest):organization_member=membership,)- def _create_workflow_reference(self, *, name: str) -> HogFlow:- return HogFlow.objects.create(- team=self.team,+ def _create_workflow_reference(self, *, name: str) -> WorkflowSummary:+ return create_workflow_for_test(+ team_id=self.team.id,name=name,status="active",actions=[diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.pyindex a16fda14c5a1..dbf272ffb0b6 100644--- a/products/signals/backend/scout_harness/profile/builders.py+++ b/products/signals/backend/scout_harness/profile/builders.py@@ -66,7 +66,7 @@ from products.signals.backend.scout_harness.profile.schema import Inventoryfrom products.signals.backend.scout_harness.team_limits import withheld_skills_for_teamfrom products.surveys.backend.models import Surveyfrom products.warehouse_sources.backend.facade import api as warehouse_sources-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.facade.api import get_workflow_activity_summarylogger = logging.getLogger(__name__)@@ -603,21 +603,18 @@ def _recent_hog_flows(team: Team) -> dict[str, Any]:HogFlow's `status` enum carries the flow's lifecycle state directly; we surfaceit as-is so the agent can distinguish drafts from active flows."""- qs = HogFlow.objects.filter(team=team)- total = qs.count()- active = qs.exclude(status="archived").count()- recent = qs.order_by("-updated_at")[:RECENT_ENTITY_LIMIT].values("id", "name", "status", "updated_at")+ summary = get_workflow_activity_summary(team_id=team.id, recent_limit=RECENT_ENTITY_LIMIT)return {- "total_count": total,- "active_count": active,+ "total_count": summary.total_count,+ "active_count": summary.active_count,"recent": [{- "id": str(row["id"]),- "name": row["name"] or "",- "status": row["status"],- "updated_at": row["updated_at"].isoformat() if row["updated_at"] else None,+ "id": flow.id,+ "name": flow.name,+ "status": flow.status,+ "updated_at": flow.updated_at.isoformat() if flow.updated_at else None,}- for row in recent+ for flow in summary.recent],}diff --git a/products/signals/backend/scout_harness/workflow_runs.py b/products/signals/backend/scout_harness/workflow_runs.pyindex 333959e6334a..993578a6e73c 100644--- a/products/signals/backend/scout_harness/workflow_runs.py+++ b/products/signals/backend/scout_harness/workflow_runs.py@@ -1,7 +1,7 @@"""Dispatch a scout run from a workflow's "Run scout" step.The third way a scout run starts, after the coordinator's schedule and the manual `run` endpoint.-`products/workflows/backend/api/workflow_scout_runs.py` has already proved *which* workflow is+`products/workflows/backend/presentation/views/workflow_scout_runs.py` has already proved *which* workflow isfiring; this module decides whether that fire may spend a run, and dispatches it if so.Two deliberate properties. A trigger is additive to the schedule: it never stamps `last_run_at`, sodiff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.pyindex 83c445c572d2..edd663e307fe 100644--- a/products/signals/backend/test/test_scout_harness_profile.py+++ b/products/signals/backend/test/test_scout_harness_profile.py@@ -83,7 +83,7 @@ from products.signals.backend.scout_harness.tools.profile import (from products.skills.backend.models.skills import LLMSkillfrom products.surveys.backend.models import Surveyfrom products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.facade.testing import create_workflow_for_testclass TestProjectContext(BaseTest):@@ -716,16 +716,16 @@ class TestRecentHogFunctions(BaseTest):class TestRecentHogFlows(BaseTest):def test_total_active_counts_excludes_archived(self) -> None:- HogFlow.objects.create(team=self.team, name="draft", status="draft")- HogFlow.objects.create(team=self.team, name="active", status="active")- HogFlow.objects.create(team=self.team, name="archived", status="archived")+ create_workflow_for_test(team_id=self.team.id, name="draft", status="draft")+ create_workflow_for_test(team_id=self.team.id, name="active", status="active")+ create_workflow_for_test(team_id=self.team.id, name="archived", status="archived")result = _recent_hog_flows(self.team)assert result["total_count"] == 3assert result["active_count"] == 2 # everything except archiveddef test_team_isolated(self) -> None:other = self.organization.teams.create(name="other")- HogFlow.objects.create(team=other, name="x", status="active")+ create_workflow_for_test(team_id=other.id, name="x", status="active")result = _recent_hog_flows(self.team)assert result["total_count"] == 0diff --git a/products/tasks/backend/tests/test_workflow_tasks_api.py b/products/tasks/backend/tests/test_workflow_tasks_api.pyindex 325691e38ea6..3d0c7c5baf81 100644--- a/products/tasks/backend/tests/test_workflow_tasks_api.py+++ b/products/tasks/backend/tests/test_workflow_tasks_api.py@@ -33,8 +33,9 @@ from products.tasks.backend.logic.services.workflow_tasks import ()from products.tasks.backend.models import Channel, Task, TaskRunfrom products.tasks.backend.visibility import task_control_q, task_visibility_q-from products.workflows.backend.api.workflow_tasks import WorkflowTaskCreateSerializer-from products.workflows.backend.models import HogFlow, TeamWorkflowsConfig+from products.workflows.backend.facade.team_extension import TeamWorkflowsConfig+from products.workflows.backend.facade.testing import create_workflow_for_test+from products.workflows.backend.presentation.views.workflow_tasks import WorkflowTaskCreateSerializerSECRET = "test-tasks-create-jwt"@@ -58,10 +59,10 @@ class TestWorkflowTasksAPI(APIBaseTest):def setUp(self) -> None:super().setUp()self.client.logout()- self.hog_flow = HogFlow.objects.create(- team=self.team,+ self.hog_flow = create_workflow_for_test(+ team_id=self.team.id,name="Alert triage",- created_by=self.user,+ created_by_id=self.user.id,trigger={"type": "manual"},)self.url = f"/api/projects/{self.team.id}/workflow_tasks/"@@ -117,7 +118,7 @@ class TestWorkflowTasksAPI(APIBaseTest):task = Task.objects.get(id=body["id"])assert task.team_id == self.team.idassert task.origin_product == Task.OriginProduct.WORKFLOW- assert task.hog_flow_id == self.hog_flow.id+ assert str(task.hog_flow_id) == self.hog_flow.idassert task.created_by_id == self.user.idassert task.description == "look into the alert"run = TaskRun.objects.get(id=body["run_id"])@@ -370,7 +371,7 @@ class TestWorkflowTasksAPI(APIBaseTest):@patch("products.tasks.backend.logic.services.workflow_tasks.usage_limit_response")def test_refuses_an_owner_removed_from_the_organization(self, usage_limit_response_mock) -> None:former_member = self._create_user("[email protected]")- flow = HogFlow.objects.create(team=self.team, name="Orphaned", created_by=former_member)+ flow = create_workflow_for_test(team_id=self.team.id, name="Orphaned", created_by_id=former_member.id)OrganizationMembership.objects.filter(user=former_member, organization=self.organization).delete()response = self._post(token=_token(self.team.id, str(flow.id)))@@ -385,7 +386,7 @@ class TestWorkflowTasksAPI(APIBaseTest):flow_id = str(uuid4())else:other_team = self.create_team_with_organization(self.organization)- flow_id = str(HogFlow.objects.create(team=other_team, name="Theirs", created_by=self.user).id)+ flow_id = create_workflow_for_test(team_id=other_team.id, name="Theirs", created_by_id=self.user.id).idresponse = self._post(token=_token(self.team.id, flow_id))@@ -411,7 +412,7 @@ class TestWorkflowTasksAPI(APIBaseTest):@patch("products.tasks.backend.logic.services.workflow_tasks.usage_limit_response")def test_skips_creation_at_the_daily_cap(self, scope: str, usage_limit_response_mock) -> None:if scope == "per_workflow":- self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY, hog_flow_id=self.hog_flow.id)+ self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY, hog_flow_id=UUID(self.hog_flow.id))expected_fragment = "This workflow reached its daily limit"else:# Two other workflows fill the team budget; this workflow is far under its own cap.@@ -438,7 +439,7 @@ class TestWorkflowTasksAPI(APIBaseTest):"workflow_task_team_rate_limit_per_day": WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY + 1,},)- self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY, hog_flow_id=self.hog_flow.id)+ self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY, hog_flow_id=UUID(self.hog_flow.id))self._seed_created_tasks(WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY - WORKFLOW_TASK_RATE_CAP_PER_DAY,hog_flow_id=uuid4(),@@ -483,7 +484,7 @@ class TestWorkflowTasksAPI(APIBaseTest):if case == "older_than_24h":self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY,- hog_flow_id=self.hog_flow.id,+ hog_flow_id=UUID(self.hog_flow.id),created_at=django_timezone.now() - timedelta(hours=25),)else:@@ -527,7 +528,7 @@ class TestWorkflowTasksAPI(APIBaseTest):# owner is over the usage limit; the retry of the already-created request must# still return the existing task.resolve_ids.return_value = {"server-1": None}- self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY, hog_flow_id=self.hog_flow.id)+ self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY, hog_flow_id=UUID(self.hog_flow.id))with patch("products.tasks.backend.logic.services.workflow_tasks.usage_limit_response", return_value=object()):replay = self._post({"idempotency_key": "invocation-1", "connectors": ["server-1"], "max_parallel_tasks": 1}diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.pyindex 81d34286eec4..9d6491fc52d6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py@@ -37,7 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.sta)from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import build_table_namefrom products.warehouse_sources.backend.temporal.data_imports.util import PostHogInternalDatabaseError-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.facade.api import has_active_workflow_for_warehouse_table# Per-file exceptions are swallowed (the file is deleted and the run continues), so a failed file# is silently dropped rows. The outcome label is what makes that visible to alerting.@@ -254,12 +254,9 @@ class CDPProducer:# Also gate on active workflows (HogFlows) triggered by this table - without this the# producer never emits to Kafka for a team whose only consumer is a warehouse-triggered workflow.- return HogFlow.objects.filter(- team_id=self.team_id,- status=HogFlow.State.ACTIVE,- trigger__type=trigger_source,- trigger__table_name=dot_notated_table_name,- ).exists()+ return has_active_workflow_for_warehouse_table(+ team_id=self.team_id, trigger_source=trigger_source, table_name=dot_notated_table_name+ )except (DjangoOperationalError, OSError) as e:# This queries PostHog's own database, not the source being synced. A transient# failure reaching it (e.g. a DNS blip resolving our host) stringifies with thediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.pyindex 959fdfd6f5d6..a337845bb29b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py@@ -36,7 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.stafrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSourcefrom products.warehouse_sources.backend.temporal.data_imports.util import PostHogInternalDatabaseErrorfrom products.warehouse_sources.backend.types import ExternalDataSourceType-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.facade.testing import acreate_workflow_for_testdef _patch_async_producer_scope(mock_producer):@@ -221,9 +221,9 @@ async def test_should_run_with_matching_hog_flow(team):team=team, name="table_1", source=source, table=table)- await sync_to_async(HogFlow.objects.create)(- team=team,- status=HogFlow.State.ACTIVE,+ await acreate_workflow_for_test(+ team_id=team.id,+ status="active",trigger={"type": "data-warehouse-table", "table_name": "postgres.table_1"},)@@ -244,9 +244,9 @@ async def test_should_not_produce_table_with_draft_hog_flow(team):team=team, name="table_1", source=source, table=table)- await sync_to_async(HogFlow.objects.create)(- team=team,- status=HogFlow.State.DRAFT,+ await acreate_workflow_for_test(+ team_id=team.id,+ status="draft",trigger={"type": "data-warehouse-table", "table_name": "postgres.table_1"},)@@ -267,9 +267,9 @@ async def test_should_not_produce_table_with_non_matching_hog_flow_table(team):team=team, name="table_1", source=source, table=table)- await sync_to_async(HogFlow.objects.create)(- team=team,- status=HogFlow.State.ACTIVE,+ await acreate_workflow_for_test(+ team_id=team.id,+ status="active",trigger={"type": "data-warehouse-table", "table_name": "postgres.some_other_table"},)@@ -295,9 +295,9 @@ async def test_should_run_with_both_hog_function_and_flow(team):enabled=True,filters={"source": "data-warehouse-table", "data_warehouse": [{"table_name": "postgres.table_1"}]},)- await sync_to_async(HogFlow.objects.create)(- team=team,- status=HogFlow.State.ACTIVE,+ await acreate_workflow_for_test(+ team_id=team.id,+ status="active",trigger={"type": "data-warehouse-table", "table_name": "postgres.table_1"},)@@ -1128,10 +1128,10 @@ async def test_view_should_run_with_matching_hog_function(team):@pytest.mark.asyncioasync def test_view_should_run_with_matching_hog_flow(team):view = await _create_view(team)- await sync_to_async(HogFlow.objects.create)(- team=team,+ await acreate_workflow_for_test(+ team_id=team.id,name="test workflow",- status=HogFlow.State.ACTIVE,+ status="active",trigger={"type": "data-warehouse-view", "table_name": "daily_revenue"},edges=[],actions=[],diff --git a/products/workflows/backend/facade/account_audience.py b/products/workflows/backend/facade/account_audience.pynew file mode 100644index 000000000000..ee046e9ab591--- /dev/null+++ b/products/workflows/backend/facade/account_audience.py@@ -0,0 +1,6 @@+"""Kept separate from ``facade/api.py`` because ``CustomerAnalyticsConfig.ready`` imports it+during ``django.setup()``, so it must stay import-light."""++from products.workflows.backend.services.account_audience import register_account_audience_provider++__all__ = ["register_account_audience_provider"]diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.pyindex c5510e56d2e8..9783f3d7242a 100644--- a/products/workflows/backend/facade/api.py+++ b/products/workflows/backend/facade/api.py@@ -1,4 +1,5 @@-from typing import Any+from collections.abc import Iterable+from typing import Any, castfrom uuid import UUIDfrom django.db.models import F@@ -7,7 +8,46 @@ from posthog.helpers.full_text_search import build_rankfrom posthog.ingress.contracts import WebhookDeliveryfrom products.access_control.backend.facade.user_access_control import UserAccessControl+from products.workflows.backend.facade.contracts import (+ RecentWorkflow,+ TierDecision,+ WorkflowActivitySummary,+ WorkflowSummary,+)from products.workflows.backend.models import HogFlow+from products.workflows.backend.services.email_sending_controls import (+ ensure_workflows_config,+ get_email_sending_state,+ set_email_sending_tier,+ suspend_email_sending,+ unsuspend_email_sending,+)+from products.workflows.backend.services.integration_usage import get_active_hog_flows_using_integration+from products.workflows.backend.services.template_input_usage import (+ filter_hog_flow_references_by_access_level,+ get_hog_flows_referencing_template_input_keys,+)+from products.workflows.backend.utils.email_sending_tiers import (+ MIN_EMAIL_SENDING_TIER,+ get_email_sending_tier_limits,+ max_email_sending_tier,+)+from products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule++__all__ = [+ "MIN_EMAIL_SENDING_TIER",+ "compute_next_occurrences",+ "ensure_workflows_config",+ "filter_hog_flow_references_by_access_level",+ "get_email_sending_state",+ "get_email_sending_tier_limits",+ "get_hog_flows_referencing_template_input_keys",+ "max_email_sending_tier",+ "set_email_sending_tier",+ "suspend_email_sending",+ "unsuspend_email_sending",+ "validate_rrule",+]class WorkflowNotFound(Exception):@@ -29,12 +69,20 @@ def search_workflows(access_control: UserAccessControl,limit: int,offset: int = 0,+ include_archived: bool = False,+ with_access_levels: bool = False,+ include_count: bool = True,) -> tuple[list[dict[str, Any]], int]:+ """Ranked full-text search over a project's workflows, in the result shape of core search.++ ``with_access_levels`` adds ``user_access_level``, the user's resolved level for each workflow.+ ``include_count=False`` skips the count query and reports a total of 0.+ """+ statuses = [HogFlow.State.DRAFT, HogFlow.State.ACTIVE]+ if include_archived:+ statuses.append(HogFlow.State.ARCHIVED)queryset = access_control.filter_queryset_by_access_level(- HogFlow.objects.filter(- team__project_id=project_id,- status__in=(HogFlow.State.DRAFT, HogFlow.State.ACTIVE),- )+ HogFlow.objects.filter(team__project_id=project_id, status__in=statuses))if query:@@ -43,13 +91,20 @@ def search_workflows(else:queryset = queryset.order_by(F("name").asc(nulls_first=True))- total_count = queryset.count()- fields = ["id", "name", "description", "status"]+ total_count = queryset.count() if include_count else 0+ fields = ["id", "name", "description", "status", "created_by_id"]if query:fields.append("rank")+ rows = list(queryset[offset : offset + limit].values(*fields))+ access_levels = (+ access_control.bulk_object_access_levels("hog_flow", [(str(row["id"]), row["created_by_id"]) for row in rows])+ if with_access_levels+ else {}+ )+results: list[dict[str, Any]] = []- for workflow in queryset[offset : offset + limit].values(*fields):+ for workflow in rows:result: dict[str, Any] = {"type": "hog_flow","result_id": str(workflow["id"]),@@ -61,6 +116,8 @@ def search_workflows(}if query:result["rank"] = workflow["rank"]+ if with_access_levels:+ result["user_access_level"] = access_levels.get(str(workflow["id"]))results.append(result)return results, total_count@@ -99,7 +156,9 @@ def set_workflow_enabled(*, team_id: int, user_id: int, workflow_id: UUID, enabl"""from posthog.models.user import User # noqa: PLC0415 — keeps the user model off the facade import path- from products.workflows.backend.api.hog_flow import HogFlowSerializer # noqa: PLC0415 - heavy DRF import+ from products.workflows.backend.presentation.views.hog_flow import ( # noqa: PLC0415 - heavy DRF import+ HogFlowSerializer,+ )hog_flow = HogFlow.objects.select_related("team").filter(team_id=team_id, id=workflow_id).first()if hog_flow is None:@@ -124,3 +183,113 @@ def set_workflow_enabled(*, team_id: int, user_id: int, workflow_id: UUID, enablhog_flow.status = targethog_flow.save(update_fields=["status", "updated_at"])return str(hog_flow.status)+++def get_workflow_names(*, team_id: int, workflow_ids: Iterable[str]) -> dict[str, str]:+ """Names keyed by the workflow id as a string. Deleted workflows are left out."""+ return {+ str(pk): (name or "")+ for pk, name in HogFlow.objects.filter(team_id=team_id, id__in=list(workflow_ids)).values_list("id", "name")+ }+++def get_workflow_summary(*, team_id: int, workflow_id: str) -> WorkflowSummary:+ row = HogFlow.objects.filter(team_id=team_id, id=workflow_id).values("id", "name", "status").first()+ if row is None:+ raise WorkflowNotFound()+ return WorkflowSummary(id=str(row["id"]), name=row["name"] or "", status=row["status"])+++def has_active_workflows(*, team_id: int) -> bool:+ return HogFlow.objects.filter(team_id=team_id, status=HogFlow.State.ACTIVE).exists()+++def has_active_workflow_for_warehouse_table(*, team_id: int, trigger_source: str, table_name: str) -> bool:+ return HogFlow.objects.filter(+ team_id=team_id,+ status=HogFlow.State.ACTIVE,+ trigger__type=trigger_source,+ trigger__table_name=table_name,+ ).exists()+++def get_workflow_activity_summary(*, team_id: int, recent_limit: int) -> WorkflowActivitySummary:+ """Total and non-archived workflow counts, plus the most recently updated workflows."""+ qs = HogFlow.objects.filter(team_id=team_id)+ recent = qs.order_by("-updated_at")[:recent_limit].values("id", "name", "status", "updated_at")+ return WorkflowActivitySummary(+ total_count=qs.count(),+ active_count=qs.exclude(status=HogFlow.State.ARCHIVED).count(),+ recent=tuple(+ RecentWorkflow(+ id=str(row["id"]), name=row["name"] or "", status=row["status"], updated_at=row["updated_at"]+ )+ for row in recent+ ),+ )+++def get_active_workflows_using_integration(*, team_id: int, integration_id: int) -> list[WorkflowSummary]:+ return [+ WorkflowSummary(id=str(flow.id), name=flow.name or "", status=flow.status)+ for flow in get_active_hog_flows_using_integration(team_id=team_id, integration_id=integration_id)+ ]+++def recompute_email_sending_tier(team_id: int) -> TierDecision | None:+ # Deferred to keep the ClickHouse metrics client off the facade import path.+ from products.workflows.backend.services.email_sending_tier import ( # noqa: PLC0415+ recompute_email_sending_tier_for_team,+ )++ return recompute_email_sending_tier_for_team(team_id)+++# The provider helpers look the provider class up on the providers package at call time, which+# also keeps boto3 and the Twilio client off the facade import path.+++def create_ses_email_domain(+ domain: str, *, mail_from_subdomain: str, team_id: int, org_team_ids: Iterable[int] | None = None+) -> None:+ from products.workflows.backend import providers # noqa: PLC0415++ providers.SESProvider().create_email_domain(+ domain, mail_from_subdomain=mail_from_subdomain, team_id=team_id, org_team_ids=org_team_ids+ )+++def update_ses_mail_from_subdomain(domain: str, *, mail_from_subdomain: str) -> None:+ from products.workflows.backend import providers # noqa: PLC0415++ providers.SESProvider().update_mail_from_subdomain(domain, mail_from_subdomain=mail_from_subdomain)+++def verify_ses_email_domain(domain: str, *, mail_from_subdomain: str, team_id: int) -> dict[str, Any]:+ from products.workflows.backend import providers # noqa: PLC0415++ return providers.SESProvider().verify_email_domain(domain, mail_from_subdomain=mail_from_subdomain, team_id=team_id)+++def delete_ses_identity(identity: str) -> None:+ from products.workflows.backend import providers # noqa: PLC0415++ providers.SESProvider().delete_identity(identity)+++def get_maildev_mock_dns_records() -> list[dict[str, Any]]:+ from products.workflows.backend import providers # noqa: PLC0415++ return cast(list[dict[str, Any]], providers.MAILDEV_MOCK_DNS_RECORDS)+++def get_twilio_phone_numbers(*, account_sid: str, auth_token: str) -> list[dict]:+ from products.workflows.backend import providers # noqa: PLC0415++ return providers.TwilioProvider(account_sid=account_sid, auth_token=auth_token).get_phone_numbers()+++def get_twilio_account_info(*, account_sid: str, auth_token: str) -> dict:+ from products.workflows.backend import providers # noqa: PLC0415++ return providers.TwilioProvider(account_sid=account_sid, auth_token=auth_token).get_account_info()diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pynew file mode 100644index 000000000000..50e340794d3c--- /dev/null+++ b/products/workflows/backend/facade/contracts.py@@ -0,0 +1,116 @@+from dataclasses import dataclass+from datetime import datetime+from typing import TYPE_CHECKING, Any, Literal, Protocol+from uuid import UUID++from posthog.dataclasses import frozen++if TYPE_CHECKING:+ from posthog.models.team.team import Team+++@frozen+class WorkflowSummary:+ id: str+ name: str+ status: str+++@frozen+class RecentWorkflow:+ id: str+ name: str+ status: str+ updated_at: datetime | None+++@frozen+class WorkflowActivitySummary:+ total_count: int+ active_count: int+ recent: tuple[RecentWorkflow, ...]+++@dataclass(frozen=True)+class HogFlowReference:+ id: str+ name: str+ status: str+++@frozen+class AccountAudienceCustomPropertyFilter:+ """One custom-property predicate of a batch audience (key = definition id)."""++ definition_id: UUID+ operator: str+ value: Any = None+++AccountAssignmentStatus = Literal["all", "assigned", "unassigned"]+++@frozen+class AccountAudienceFilters:+ """Account selection for a batch run; empty filters mean every account with an external_id."""++ tag_names: tuple[str, ...] = ()+ assignment_status: AccountAssignmentStatus | None = None+ assigned_to_user_ids: tuple[int, ...] = ()+ all_roles_unassigned: bool = False+ custom_properties: tuple[AccountAudienceCustomPropertyFilter, ...] = ()+++class AccountAudienceProvider(Protocol):+ def count_accounts(self, team: "Team", filters: AccountAudienceFilters) -> int: ...++ def list_account_external_ids(+ self, team: "Team", filters: AccountAudienceFilters, *, cursor: str | None, limit: int+ ) -> list[str]: ...++ def get_account_group_type_name(self, team: "Team") -> str | None: ...+++@frozen+class EmailSendingTierLimits:+ """What a trust tier allows: two send-rate caps and a maximum batch audience."""++ tier: int+ per_hour: int+ per_day: int+ max_batch_audience: int+++@frozen+class TierDecision:+ team_id: int+ previous_tier: int+ new_tier: int+ reason: str++ @property+ def changed(self) -> bool:+ return self.previous_tier != self.new_tier+++@frozen+class EmailSendingState:+ """A team's email sending controls. A team with no config row reads as the field defaults."""++ suspended_at: datetime | None+ suspension_reason: str+ tier: int+ tier_pinned: bool+ tier_updated_at: datetime | None+++@frozen+class EmailSendingSuspensionChange:+ """The outcome of a suspend or unsuspend request.++ ``changed_at`` is set only when this request flipped the state. ``previously_suspended_at`` is+ set when a suspend request found the team already suspended.+ """++ changed_at: datetime | None+ previously_suspended_at: datetime | None = Nonediff --git a/products/workflows/backend/facade/enums.py b/products/workflows/backend/facade/enums.pynew file mode 100644index 000000000000..48d92fb24a93--- /dev/null+++ b/products/workflows/backend/facade/enums.py@@ -0,0 +1,17 @@+from enum import StrEnum+++class EmailTrackingConsentMode(StrEnum):+ # No consent enforcement: tracking follows the email step's own setting only.+ OFF = "off"+ # Track by default; suppress tracking for recipients who have opted out.+ OPT_OUT = "opt_out"+ # Do not track unless the recipient has explicitly opted in.+ OPT_IN = "opt_in"+++# The labels Django's TextChoices derived from the member names, so the model field and the API+# schema keep the same choices.+EMAIL_TRACKING_CONSENT_MODE_CHOICES = [+ (mode.value, mode.name.replace("_", " ").title()) for mode in EmailTrackingConsentMode+]diff --git a/products/workflows/backend/facade/tasks.py b/products/workflows/backend/facade/tasks.pynew file mode 100644index 000000000000..558401eda9e4--- /dev/null+++ b/products/workflows/backend/facade/tasks.py@@ -0,0 +1,13 @@+from products.workflows.backend.tasks.email_sending_tiers import recompute_workflows_email_sending_tiers+from products.workflows.backend.tasks.hog_flows import refresh_affected_hog_flows+from products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputation+from products.workflows.backend.tasks.ses_tenant_state import reconcile_ses_tenant_states+from products.workflows.backend.tasks.workflow_email_health import sweep_workflow_email_deliverability++__all__ = [+ "poll_ses_account_reputation",+ "recompute_workflows_email_sending_tiers",+ "reconcile_ses_tenant_states",+ "refresh_affected_hog_flows",+ "sweep_workflow_email_deliverability",+]diff --git a/products/workflows/backend/facade/team_extension.py b/products/workflows/backend/facade/team_extension.pynew file mode 100644index 000000000000..ce2700204a55--- /dev/null+++ b/products/workflows/backend/facade/team_extension.py@@ -0,0 +1,11 @@+"""Facade re-export for the workflows team-extension model.++Core's ``Team.workflows_config`` accessor and ``posthog/api/team.py`` register/read this+extension by class identity through ``get_or_create_team_extension``. Re-exporting the model+class keeps that registry coupling at the facade boundary without exposing the internal models+package.+"""++from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig++__all__ = ["TeamWorkflowsConfig"]diff --git a/products/workflows/backend/facade/testing.py b/products/workflows/backend/facade/testing.pyindex c4c1bf1ee2ed..d982da6eb47f 100644--- a/products/workflows/backend/facade/testing.py+++ b/products/workflows/backend/facade/testing.py@@ -1,13 +1,41 @@-from typing import Literal+from typing import Any+from asgiref.sync import sync_to_async++from posthog.models.team import Team++from products.workflows.backend.facade.contracts import WorkflowSummaryfrom products.workflows.backend.models import HogFlow+from products.workflows.backend.services.account_audience import get_account_audience_count, get_account_audience_page-async def create_workflow_for_test(+def create_workflow_for_test(*,team_id: int,- created_by_id: int,- name: str,- status: Literal["active", "archived", "draft"],-) -> None:- await HogFlow.objects.acreate(team_id=team_id, created_by_id=created_by_id, name=name, status=status)+ name: str | None = None,+ status: str = "draft",+ created_by_id: int | None = None,+ trigger: dict[str, Any] | None = None,+ actions: list[dict[str, Any]] | None = None,+ edges: list[dict[str, Any]] | None = None,+) -> WorkflowSummary:+ """Seed a workflow row. Fields left as None take the model defaults."""+ optional = {"name": name, "trigger": trigger, "actions": actions, "edges": edges}+ flow = HogFlow.objects.create(+ team_id=team_id,+ status=status,+ created_by_id=created_by_id,+ **{field: value for field, value in optional.items() if value is not None},+ )+ return WorkflowSummary(id=str(flow.id), name=flow.name or "", status=flow.status)+++acreate_workflow_for_test = sync_to_async(create_workflow_for_test)+++def count_account_audience_for_test(*, team_id: int, filters: dict[str, Any]) -> int:+ return get_account_audience_count(Team.objects.get(pk=team_id), filters)+++def list_account_audience_page_for_test(*, team_id: int, filters: dict[str, Any], cursor: str | None) -> list[str]:+ return get_account_audience_page(Team.objects.get(pk=team_id), filters, cursor)diff --git a/posthog/management/commands/backfill_hogflow_billable_action_types.py b/products/workflows/backend/management/commands/backfill_hogflow_billable_action_types.pysimilarity index 100%rename from posthog/management/commands/backfill_hogflow_billable_action_types.pyrename to products/workflows/backend/management/commands/backfill_hogflow_billable_action_types.pydiff --git a/posthog/management/commands/backfill_workflows_slack_integration.py b/products/workflows/backend/management/commands/backfill_workflows_slack_integration.pysimilarity index 100%rename from posthog/management/commands/backfill_workflows_slack_integration.pyrename to products/workflows/backend/management/commands/backfill_workflows_slack_integration.pydiff --git a/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.py b/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.pyindex 7f859fee71f3..edf56a9324e4 100644--- a/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.py+++ b/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.py@@ -7,13 +7,13 @@ from django.db import transactionimport structlog-from products.workflows.backend.api.hog_flow import (+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.presentation.views.hog_flow import (TemplateCache,merge_secret_maps,plaintext_secret_map,strip_secrets_from_content,)-from products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = structlog.get_logger(__name__)diff --git a/posthog/management/commands/refresh_hog_flows.py b/products/workflows/backend/management/commands/refresh_hog_flows.pysimilarity index 99%rename from posthog/management/commands/refresh_hog_flows.pyrename to products/workflows/backend/management/commands/refresh_hog_flows.pyindex 1e870cd2165e..15f858809c6a 100644--- a/posthog/management/commands/refresh_hog_flows.py+++ b/products/workflows/backend/management/commands/refresh_hog_flows.py@@ -9,7 +9,8 @@ from django.test import RequestFactoryimport structlog-from products.workflows.backend.api.hog_flow import (+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.presentation.views.hog_flow import (HogFlowSerializer,TemplateCache,mask_secret_action_inputs,@@ -17,7 +18,6 @@ from products.workflows.backend.api.hog_flow import (partition_flow_secrets,plaintext_secret_map,)-from products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = structlog.get_logger(__name__)diff --git a/products/workflows/backend/models/team_workflows_config.py b/products/workflows/backend/models/team_workflows_config.pyindex a8c308ff3b99..27800f4ffeef 100644--- a/products/workflows/backend/models/team_workflows_config.py+++ b/products/workflows/backend/models/team_workflows_config.py@@ -3,14 +3,7 @@ from django.db import modelsfrom posthog.models.team import Team--class EmailTrackingConsentMode(models.TextChoices):- # No consent enforcement: tracking follows the email step's own setting only.- OFF = "off"- # Track by default; suppress tracking for recipients who have opted out.- OPT_OUT = "opt_out"- # Do not track unless the recipient has explicitly opted in.- OPT_IN = "opt_in"+from products.workflows.backend.facade.enums import EMAIL_TRACKING_CONSENT_MODE_CHOICES, EmailTrackingConsentModeclass TeamWorkflowsConfig(models.Model):@@ -23,7 +16,7 @@ class TeamWorkflowsConfig(models.Model):# Recipient-consent enforcement for open/click tracking on marketing emails (CNIL/ePrivacy).# Enforced at send time in the Node worker; transactional emails are exempt.email_tracking_consent_mode = models.CharField(- max_length=16, choices=EmailTrackingConsentMode.choices, default=EmailTrackingConsentMode.OFF+ max_length=16, choices=EMAIL_TRACKING_CONSENT_MODE_CHOICES, default=EmailTrackingConsentMode.OFF)# Staff-controlled kill switch: while set, the CDP email worker blocks all workflow emaildiff --git a/products/workflows/backend/presentation/__init__.py b/products/workflows/backend/presentation/__init__.pynew file mode 100644index 000000000000..41bc8707f2ff--- /dev/null+++ b/products/workflows/backend/presentation/__init__.py@@ -0,0 +1 @@+"""HTTP presentation layer of the workflows product (DRF viewsets and serializers)."""diff --git a/products/workflows/backend/api/__init__.py b/products/workflows/backend/presentation/views/__init__.pysimilarity index 100%rename from products/workflows/backend/api/__init__.pyrename to products/workflows/backend/presentation/views/__init__.pydiff --git a/products/workflows/backend/api/action_redirects.py b/products/workflows/backend/presentation/views/action_redirects.pysimilarity index 100%rename from products/workflows/backend/api/action_redirects.pyrename to products/workflows/backend/presentation/views/action_redirects.pydiff --git a/products/workflows/backend/api/graph_operations.py b/products/workflows/backend/presentation/views/graph_operations.pysimilarity index 100%rename from products/workflows/backend/api/graph_operations.pyrename to products/workflows/backend/presentation/views/graph_operations.pydiff --git a/products/workflows/backend/api/graph_validation.py b/products/workflows/backend/presentation/views/graph_validation.pysimilarity index 100%rename from products/workflows/backend/api/graph_validation.pyrename to products/workflows/backend/presentation/views/graph_validation.pydiff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pysimilarity index 99%rename from products/workflows/backend/api/hog_flow.pyrename to products/workflows/backend/presentation/views/hog_flow.pyindex 27ec48be7763..761eb003f2df 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -128,21 +128,6 @@ from products.tasks.backend.facade.workflow_tasks import (resolve_connectors,validate_skill_names,)-from products.workflows.backend.api.action_redirects import compute_action_redirects-from products.workflows.backend.api.graph_operations import _deep_merge, apply_graph_operations-from products.workflows.backend.api.graph_validation import validate_graph-from products.workflows.backend.api.hog_flow_batch_job import (- HogFlowBatchJobCancelResponseSerializer,- HogFlowBatchJobSerializer,-)-from products.workflows.backend.api.message_assets import (- MessageAssetContentRequestSerializer,- MessageAssetSerializer,- MessageAssetsRequestSerializer,- fetch_message_asset_html,- fetch_message_assets,-)-from products.workflows.backend.api.publish_impact import build_publish_impactfrom products.workflows.backend.metrics import (GUARDRAIL_LABELS,GUARDRAIL_METRICS,@@ -169,6 +154,21 @@ from products.workflows.backend.models.hog_flow_revision import HogFlowRevisionfrom products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedulefrom products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfigfrom products.workflows.backend.models.workflow_proposal import WorkflowProposal+from products.workflows.backend.presentation.views.action_redirects import compute_action_redirects+from products.workflows.backend.presentation.views.graph_operations import _deep_merge, apply_graph_operations+from products.workflows.backend.presentation.views.graph_validation import validate_graph+from products.workflows.backend.presentation.views.hog_flow_batch_job import (+ HogFlowBatchJobCancelResponseSerializer,+ HogFlowBatchJobSerializer,+)+from products.workflows.backend.presentation.views.message_assets import (+ MessageAssetContentRequestSerializer,+ MessageAssetSerializer,+ MessageAssetsRequestSerializer,+ fetch_message_asset_html,+ fetch_message_assets,+)+from products.workflows.backend.presentation.views.publish_impact import build_publish_impactfrom products.workflows.backend.providers.ses import SESProviderfrom products.workflows.backend.services.account_audience import (ACCOUNT_BATCH_SIZE,diff --git a/products/workflows/backend/api/hog_flow_batch_job.py b/products/workflows/backend/presentation/views/hog_flow_batch_job.pysimilarity index 100%rename from products/workflows/backend/api/hog_flow_batch_job.pyrename to products/workflows/backend/presentation/views/hog_flow_batch_job.pydiff --git a/products/workflows/backend/api/hog_flow_template.py b/products/workflows/backend/presentation/views/hog_flow_template.pysimilarity index 99%rename from products/workflows/backend/api/hog_flow_template.pyrename to products/workflows/backend/presentation/views/hog_flow_template.pyindex e93a2013f2e7..9730497f93c5 100644--- a/products/workflows/backend/api/hog_flow_template.py+++ b/products/workflows/backend/presentation/views/hog_flow_template.py@@ -18,8 +18,8 @@ from posthog.models import Userfrom posthog.models.activity_logging.activity_log import Detail, log_activityfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplate-from products.workflows.backend.api.hog_flow import HogFlowMaskingSerializer, HogFlowVariableSerializerfrom products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate+from products.workflows.backend.presentation.views.hog_flow import HogFlowMaskingSerializer, HogFlowVariableSerializerfrom products.workflows.backend.templates import get_global_template_by_id, load_global_templateslogger = structlog.get_logger(__name__)diff --git a/products/workflows/backend/api/message_assets.py b/products/workflows/backend/presentation/views/message_assets.pysimilarity index 100%rename from products/workflows/backend/api/message_assets.pyrename to products/workflows/backend/presentation/views/message_assets.pydiff --git a/products/workflows/backend/api/publish_impact.py b/products/workflows/backend/presentation/views/publish_impact.pysimilarity index 98%rename from products/workflows/backend/api/publish_impact.pyrename to products/workflows/backend/presentation/views/publish_impact.pyindex 0b5f2f7b8863..95d16d226352 100644--- a/products/workflows/backend/api/publish_impact.py+++ b/products/workflows/backend/presentation/views/publish_impact.py@@ -1,7 +1,7 @@import refrom typing import Any, Optional-from products.workflows.backend.api.action_redirects import compute_action_redirects+from products.workflows.backend.presentation.views.action_redirects import compute_action_redirects# Publish-time impact summary: what applying a staged draft will do to people already in the flow.# Pure functions over the two graphs plus externally-fetched counts, so the matrix is unit-testablediff --git a/products/workflows/backend/api/workflow_scout_runs.py b/products/workflows/backend/presentation/views/workflow_scout_runs.pysimilarity index 100%rename from products/workflows/backend/api/workflow_scout_runs.pyrename to products/workflows/backend/presentation/views/workflow_scout_runs.pydiff --git a/products/workflows/backend/api/workflow_tasks.py b/products/workflows/backend/presentation/views/workflow_tasks.pysimilarity index 100%rename from products/workflows/backend/api/workflow_tasks.pyrename to products/workflows/backend/presentation/views/workflow_tasks.pydiff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.pyindex 723ca1b48e32..b84eb3a1f678 100644--- a/products/workflows/backend/routes.py+++ b/products/workflows/backend/routes.py@@ -5,7 +5,12 @@ from posthog.ingress.sns.provider import build_sns_providerfrom posthog.ingress.views import build_webhook_viewfrom posthog.utils import opt_slash_path-from products.workflows.backend.api import hog_flow, hog_flow_template, workflow_scout_runs, workflow_tasks+from products.workflows.backend.presentation.views import (+ hog_flow,+ hog_flow_template,+ workflow_scout_runs,+ workflow_tasks,+)# AWS SES tenant reputation events, delivered EventBridge -> SNS HTTPS subscription. Workflows owns# the topic and its allowlist setting, so the route is mounted here rather than in core.diff --git a/products/workflows/backend/services/account_audience.py b/products/workflows/backend/services/account_audience.pyindex 81f8a458ecba..da8f68a76676 100644--- a/products/workflows/backend/services/account_audience.py+++ b/products/workflows/backend/services/account_audience.py@@ -11,14 +11,19 @@ implementation arrives through a provider registered during ``django.setup()``(``CustomerAnalyticsConfig.ready``) — the same hook inversion warehouse_sources uses."""-from typing import Any, Literal, Protocolfrom uuid import UUIDfrom rest_framework import exceptions-from posthog.dataclasses import frozenfrom posthog.models.team.team import Team+from products.workflows.backend.facade.contracts import (+ AccountAssignmentStatus,+ AccountAudienceCustomPropertyFilter,+ AccountAudienceFilters,+ AccountAudienceProvider,+)+ACCOUNT_BATCH_SIZE = 500# Mirrors ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST in@@ -46,39 +51,6 @@ SUPPORTED_CUSTOM_PROPERTY_OPERATORS = frozenset(_VALUELESS_OPERATORS = frozenset({"is_set", "is_not_set"})-@frozen-class AccountAudienceCustomPropertyFilter:- """One custom-property predicate of a batch audience (key = definition id)."""-- definition_id: UUID- operator: str- value: Any = None---AccountAssignmentStatus = Literal["all", "assigned", "unassigned"]---@frozen-class AccountAudienceFilters:- """Account selection for a batch run; empty filters mean every account with an external_id."""-- tag_names: tuple[str, ...] = ()- assignment_status: AccountAssignmentStatus | None = None- assigned_to_user_ids: tuple[int, ...] = ()- all_roles_unassigned: bool = False- custom_properties: tuple[AccountAudienceCustomPropertyFilter, ...] = ()---class AccountAudienceProvider(Protocol):- def count_accounts(self, team: Team, filters: AccountAudienceFilters) -> int: ...-- def list_account_external_ids(- self, team: Team, filters: AccountAudienceFilters, *, cursor: str | None, limit: int- ) -> list[str]: ...-- def get_account_group_type_name(self, team: Team) -> str | None: ...--_provider: AccountAudienceProvider | None = Nonediff --git a/products/workflows/backend/services/email_sending_controls.py b/products/workflows/backend/services/email_sending_controls.pynew file mode 100644index 000000000000..7e2ee83153e0--- /dev/null+++ b/products/workflows/backend/services/email_sending_controls.py@@ -0,0 +1,97 @@+"""Staff controls over a team's workflow email sending: suspension and the pinned trust tier."""++from django.db import transaction+from django.utils import timezone++from posthog.models.team import Team+from posthog.models.team.extensions import get_or_create_team_extension++from products.workflows.backend.facade.contracts import EmailSendingState, EmailSendingSuspensionChange+from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig+from products.workflows.backend.utils.email_sending_tiers import MIN_EMAIL_SENDING_TIER+++def ensure_workflows_config(team_id: int) -> None:+ get_or_create_team_extension(Team.objects.get(pk=team_id), TeamWorkflowsConfig)+++def get_email_sending_state(team_id: int) -> EmailSendingState | None:+ config = TeamWorkflowsConfig.objects.filter(team_id=team_id).first()+ if config is None:+ return None+ return EmailSendingState(+ suspended_at=config.email_sending_suspended_at,+ suspension_reason=config.email_sending_suspension_reason,+ tier=config.email_sending_tier,+ tier_pinned=config.email_sending_tier_pinned,+ tier_updated_at=config.email_sending_tier_updated_at,+ )+++def suspend_email_sending(team_id: int, reason: str) -> EmailSendingSuspensionChange:+ # Row-lock the config while checking + flipping so two concurrent submits (retried POST,+ # two open admin tabs) can't both pass the idempotency check and both dispatch the+ # customer email + notification. Side effects stay with the caller, outside the atomic block.+ ensure_workflows_config(team_id)+ with transaction.atomic():+ config = TeamWorkflowsConfig.objects.select_for_update().get(team_id=team_id)+ if config.email_sending_suspended_at is not None:+ return EmailSendingSuspensionChange(+ changed_at=None, previously_suspended_at=config.email_sending_suspended_at+ )+ suspended_at = timezone.now()+ config.email_sending_suspended_at = suspended_at+ config.email_sending_suspension_reason = reason+ # Drop the trust tier now, in the same locked transaction, rather than at the next+ # daily sweep: a suspension is the strongest signal there is, and the tier sets how+ # fast the team may send once reinstated. A suspension always maps to the lowest+ # tier, and that mapping needs no metrics, so write it here instead of through the+ # recompute. This does not depend on ClickHouse and it also covers pinned teams,+ # which the periodic sweep skips.+ config.email_sending_tier = MIN_EMAIL_SENDING_TIER+ config.email_sending_tier_updated_at = suspended_at+ config.save(+ update_fields=[+ "email_sending_suspended_at",+ "email_sending_suspension_reason",+ "email_sending_tier",+ "email_sending_tier_updated_at",+ ]+ )+ return EmailSendingSuspensionChange(changed_at=suspended_at)+++def unsuspend_email_sending(team_id: int) -> EmailSendingSuspensionChange:+ # Symmetric to suspend: lock the row, re-check, flip inside the transaction so racing+ # submits can't both fire the re-enable side effects.+ with transaction.atomic():+ config = TeamWorkflowsConfig.objects.select_for_update().filter(team_id=team_id).first()+ if not config or config.email_sending_suspended_at is None:+ return EmailSendingSuspensionChange(changed_at=None)+ unsuspended_at = timezone.now()+ config.email_sending_suspended_at = None+ config.email_sending_suspension_reason = ""+ config.save(update_fields=["email_sending_suspended_at", "email_sending_suspension_reason"])+ return EmailSendingSuspensionChange(changed_at=unsuspended_at)+++def set_email_sending_tier(team_id: int, *, tier: int, pinned: bool) -> int:+ """Write a staff-chosen tier and pin state, and return the tier the team had before."""+ ensure_workflows_config(team_id)+ with transaction.atomic():+ config = TeamWorkflowsConfig.objects.select_for_update().get(team_id=team_id)+ previous_tier = config.email_sending_tier+ config.email_sending_tier = tier+ config.email_sending_tier_pinned = pinned+ if tier != previous_tier:+ # Only a real tier change restarts the dwell clock. Toggling the pin alone must not+ # push the next earned promotion out by the full dwell.+ config.email_sending_tier_updated_at = timezone.now()+ config.save(+ update_fields=[+ "email_sending_tier",+ "email_sending_tier_pinned",+ "email_sending_tier_updated_at",+ ]+ )+ return previous_tierdiff --git a/products/workflows/backend/services/email_sending_tier.py b/products/workflows/backend/services/email_sending_tier.pyindex 42b8b7175298..4f3b83feae6b 100644--- a/products/workflows/backend/services/email_sending_tier.py+++ b/products/workflows/backend/services/email_sending_tier.py@@ -11,6 +11,7 @@ from posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.dataclasses import frozen+from products.workflows.backend.facade.contracts import TierDecisionfrom products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfigfrom products.workflows.backend.utils.email_sending_tiers import (MIN_EMAIL_SENDING_TIER,@@ -77,18 +78,6 @@ class TeamSendingHistory:return not (complaints_are_dirty or bounces_are_dirty)-@frozen-class TierDecision:- team_id: int- previous_tier: int- new_tier: int- reason: str-- @property- def changed(self) -> bool:- return self.previous_tier != self.new_tier--@frozenclass SesTenantState:"""AWS's own view of the team's SES tenant, synced by the tenant-state tasks.diff --git a/products/workflows/backend/services/template_input_usage.py b/products/workflows/backend/services/template_input_usage.pyindex 7f7bd8bb609d..1c53f847ea06 100644--- a/products/workflows/backend/services/template_input_usage.py+++ b/products/workflows/backend/services/template_input_usage.py@@ -6,22 +6,15 @@ workflows that set it. Used (e.g.) to surface which workflows reference a customdefinition via the "Update account property" action's ``properties`` input."""-from dataclasses import dataclassfrom typing import TYPE_CHECKING+from products.workflows.backend.facade.contracts import HogFlowReferencefrom products.workflows.backend.models import HogFlowif TYPE_CHECKING:from products.access_control.backend.facade.user_access_control import UserAccessControl-@dataclass(frozen=True)-class HogFlowReference:- id: str- name: str- status: str--def get_hog_flows_referencing_template_input_keys(team_id: int,template_id: str,diff --git a/posthog/test/test_backfill_hogflow_billable_action_types.py b/products/workflows/backend/test/test_backfill_hogflow_billable_action_types.pysimilarity index 100%rename from posthog/test/test_backfill_hogflow_billable_action_types.pyrename to products/workflows/backend/test/test_backfill_hogflow_billable_action_types.pydiff --git a/posthog/management/commands/test/test_backfill_workflows_slack_integration.py b/products/workflows/backend/test/test_backfill_workflows_slack_integration.pysimilarity index 96%rename from posthog/management/commands/test/test_backfill_workflows_slack_integration.pyrename to products/workflows/backend/test/test_backfill_workflows_slack_integration.pyindex d72cd186ebdf..a2902f06f4f2 100644--- a/posthog/management/commands/test/test_backfill_workflows_slack_integration.py+++ b/products/workflows/backend/test/test_backfill_workflows_slack_integration.py@@ -3,10 +3,12 @@ from unittest.mock import patchfrom django.core.management import call_command-from posthog.management.commands import backfill_workflows_slack_integration as backfill-from posthog.management.commands.backfill_workflows_slack_integration import _rewrite_slack_workspace_in_actionsfrom posthog.models import Team+from products.workflows.backend.management.commands import backfill_workflows_slack_integration as backfill+from products.workflows.backend.management.commands.backfill_workflows_slack_integration import (+ _rewrite_slack_workspace_in_actions,+)from products.workflows.backend.models.hog_flow.hog_flow import HogFlowdiff --git a/products/workflows/backend/test/test_email_integration_ses.py b/products/workflows/backend/test/test_email_integration_ses.pynew file mode 100644index 000000000000..ad8f8c6380c4--- /dev/null+++ b/products/workflows/backend/test/test_email_integration_ses.py@@ -0,0 +1,170 @@+import pytest+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from posthog.api.integration import IntegrationViewSet+from posthog.models.integration import EmailIntegration, Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.workflows.backend.providers import SESProvider+++class TestEmailIntegrationCrossTenantStaleVerification(BaseTest):+ def _build_ses_provider(self, tenants_for_domain: dict[str, list[str]] | None = None) -> SESProvider:+ patcher = patch("products.workflows.backend.providers.ses.boto3.client")+ patcher.start()+ self.addCleanup(patcher.stop)++ provider = SESProvider()+ provider.ses_client = MagicMock()+ provider.ses_v2_client = MagicMock()+ provider.sts_client = MagicMock()+ provider.sts_client.get_caller_identity.return_value = {"Account": "123456789012"}++ provider.ses_client.verify_domain_identity.return_value = {"VerificationToken": "tok"}+ provider.ses_client.verify_domain_dkim.return_value = {"DkimTokens": ["t1", "t2", "t3"]}+ provider.ses_client.set_identity_mail_from_domain.return_value = {}++ def _list_resource_tenants(ResourceArn: str) -> dict:+ domain = ResourceArn.split("/")[-1]+ return {"ResourceTenants": [{"TenantName": t} for t in (tenants_for_domain or {}).get(domain, [])]}++ provider.ses_v2_client.list_resource_tenants.side_effect = _list_resource_tenants+ return provider++ def _set_global_ses_success(self, provider, domain: str) -> None:+ provider.ses_client.get_identity_verification_attributes.return_value = {+ "VerificationAttributes": {domain: {"VerificationStatus": "Success"}}+ }+ provider.ses_client.get_identity_dkim_attributes.return_value = {+ "DkimAttributes": {domain: {"DkimVerificationStatus": "Success"}}+ }+ provider.ses_client.get_identity_mail_from_domain_attributes.return_value = {+ "MailFromDomainAttributes": {domain: {"MailFromDomainStatus": "Success"}}+ }++ @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")+ def test_verify_email_domain_requires_team_tenant_association(self, mock_resolver_cls):+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})+ self._set_global_ses_success(provider, "partner.com")+ dmarc_answer = MagicMock()+ dmarc_answer.strings = [b"v=DMARC1; p=none;"]+ mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]++ result_team_a = provider.verify_email_domain("partner.com", "feedback", team_id=1)+ result_team_b = provider.verify_email_domain("partner.com", "feedback", team_id=999)++ assert result_team_a["status"] == "success"+ assert result_team_b["status"] == "pending"++ @patch("products.workflows.backend.providers.SESProvider.delete_identity")+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_destroy_email_integration_deletes_ses_identity(self, mock_create_email_domain, mock_delete_identity):+ mock_create_email_domain.return_value = {"status": "success"}+ integration = EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Owner"},+ team_id=self.team.id,+ organization_id=str(self.organization.id),+ created_by=self.user,+ )++ with self.captureOnCommitCallbacks(execute=True):+ IntegrationViewSet().perform_destroy(integration)++ mock_delete_identity.assert_called_once_with("partner.com")+ assert not Integration.objects.filter(pk=integration.pk).exists()++ @patch("products.workflows.backend.providers.SESProvider.delete_identity")+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_destroy_email_integration_skips_ses_delete_when_sibling_exists(+ self, mock_create_email_domain, mock_delete_identity+ ):+ mock_create_email_domain.return_value = {"status": "success"}+ sibling_team = Team.objects.create(organization=self.organization, name="sibling team")+ EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Sibling"},+ team_id=sibling_team.id,+ organization_id=str(self.organization.id),+ created_by=self.user,+ )+ integration = EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Owner"},+ team_id=self.team.id,+ organization_id=str(self.organization.id),+ created_by=self.user,+ )++ with self.captureOnCommitCallbacks(execute=True):+ IntegrationViewSet().perform_destroy(integration)++ assert mock_delete_identity.call_count == 0++ def test_create_email_domain_rejects_foreign_tenant_owner(self):+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})++ with pytest.raises(Exception) as exc:+ provider.create_email_domain("partner.com", "feedback", team_id=999, org_team_ids=[999])+ assert "already associated with another organization" in str(exc.value)++ def test_create_email_domain_allows_sibling_team_in_same_org(self):+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})++ provider.create_email_domain(+ "partner.com",+ "feedback",+ team_id=2,+ org_team_ids=[1, 2, 3, 4, 5],+ )++ @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_takeover_after_owner_deletes_integration_is_blocked(self, mock_create_email_domain, mock_resolver_cls):+ mock_create_email_domain.return_value = {"status": "success"}+ dmarc_answer = MagicMock()+ dmarc_answer.strings = [b"v=DMARC1; p=none;"]+ mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]++ org_a = Organization.objects.create(name="org a")+ team_a = Team.objects.create(organization=org_a, name="team a")+ org_b = Organization.objects.create(name="org b")+ team_b = Team.objects.create(organization=org_b, name="team b")++ integration_a = EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Owner A"},+ team_id=team_a.id,+ organization_id=str(org_a.id),+ created_by=self.user,+ )+ with patch("products.workflows.backend.providers.SESProvider.delete_identity") as mock_delete:+ with self.captureOnCommitCallbacks(execute=True):+ IntegrationViewSet().perform_destroy(integration_a)+ mock_delete.assert_called_once_with("partner.com")++ integration_b = EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Attacker B"},+ team_id=team_b.id,+ organization_id=str(org_b.id),+ created_by=self.user,+ )++ provider = self._build_ses_provider(tenants_for_domain={"partner.com": []})+ self._set_global_ses_success(provider, "partner.com")++ email_b = EmailIntegration(integration_b)+ with patch("products.workflows.backend.providers.SESProvider", return_value=provider):+ result = email_b.verify()++ assert result["status"] == "pending"+ integration_b.refresh_from_db()+ assert integration_b.config.get("verified") is False++ def test_aws_account_id_is_cached_per_provider(self):+ provider = self._build_ses_provider()+ provider.sts_client.get_caller_identity.reset_mock()++ for _ in range(5):+ provider._identity_arn("partner.com")+ provider._identity_arn("other.com")++ assert provider.sts_client.get_caller_identity.call_count == 1diff --git a/products/workflows/backend/test/test_hog_flow_admin.py b/products/workflows/backend/test/test_hog_flow_admin.pyindex 404ff0949418..ad2d2fcd0483 100644--- a/products/workflows/backend/test/test_hog_flow_admin.py+++ b/products/workflows/backend/test/test_hog_flow_admin.py@@ -1,5 +1,7 @@+import pytestfrom unittest.mock import patch+from django.contrib import adminfrom django.contrib.admin.models import CHANGE, LogEntryfrom django.contrib.admin.sites import AdminSitefrom django.contrib.contenttypes.models import ContentType@@ -9,10 +11,13 @@ from django.http import HttpRequestfrom django.test import RequestFactory, TestCasefrom django.utils import timezone+from posthog.admin import register_all_adminfrom posthog.models.user import Userfrom products.workflows.backend.admin.hog_flow_admin import HogFlowAdminfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate+from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJobclass TestHogFlowAdminEmailAudit(TestCase):@@ -56,3 +61,11 @@ class TestHogFlowAdminEmailAudit(TestCase):entry = self._admin_history()assert entry.user_id == self.user.pkassert "Resumed" in entry.change_message++[email protected]("model", [HogFlow, HogFlowTemplate, HogFlowBatchJob], ids=lambda m: m.__name__)+def test_workflows_models_are_registered_in_admin(model):+ # The admin classes register only when autodiscovery imports this product's admin package.+ # Tests skip the lazy admin registry, so trigger registration explicitly.+ register_all_admin()+ assert admin.site.is_registered(model), f"{model.__name__} is not registered in Django admin"diff --git a/posthog/models/test/test_hog_flow_batch_job.py b/products/workflows/backend/test/test_hog_flow_batch_job.pysimilarity index 95%rename from posthog/models/test/test_hog_flow_batch_job.pyrename to products/workflows/backend/test/test_hog_flow_batch_job.pyindex 259c00c83424..1487aa00a977 100644--- a/posthog/models/test/test_hog_flow_batch_job.py+++ b/products/workflows/backend/test/test_hog_flow_batch_job.py@@ -1,11 +1,13 @@from unittest.mock import patch+from django.db.models.signals import post_savefrom django.test import TestCasefrom posthog.models.user import Userfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob+from products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import handle_hog_flow_batch_job_createdclass TestHogFlowBatchJob(TestCase):@@ -71,11 +73,6 @@ class TestHogFlowBatchJob(TestCase):@patch("products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.handle_hog_flow_batch_job_created")def test_hog_flow_batch_job_created_signal(self, mock_handler, mock_create_invocation):# Disconnect the signal temporarily to test it- from django.db.models.signals import post_save-- from products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import (- handle_hog_flow_batch_job_created,- )post_save.disconnect(handle_hog_flow_batch_job_created, sender=HogFlowBatchJob)diff --git a/products/workflows/backend/test/test_hog_flow_schedule.py b/products/workflows/backend/test/test_hog_flow_schedule.pyindex 647dbb780920..a769dfd9d33f 100644--- a/products/workflows/backend/test/test_hog_flow_schedule.py+++ b/products/workflows/backend/test/test_hog_flow_schedule.py@@ -11,13 +11,13 @@ import requestsfrom parameterized import parameterizedfrom rest_framework import status-from products.workflows.backend.api.hog_flow import (- HOG_FLOW_RUN_IDEMPOTENCY_IN_PROGRESS,- _hog_flow_run_idempotency_cache_key,-)from products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJobfrom products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule+from products.workflows.backend.presentation.views.hog_flow import (+ HOG_FLOW_RUN_IDEMPOTENCY_IN_PROGRESS,+ _hog_flow_run_idempotency_cache_key,+)from products.workflows.backend.utils.rrule_utils import compute_next_occurrencesBATCH_TRIGGER = {@@ -434,7 +434,7 @@ class TestProcessDueSchedules(APIBaseTest):@override_settings(INTERNAL_API_SECRET="test-secret")[email protected]("products.workflows.backend.api.hog_flow.create_hog_flow_scheduled_invocation")[email protected]("products.workflows.backend.presentation.views.hog_flow.create_hog_flow_scheduled_invocation")class TestProcessDueScheduleTriggers(APIBaseTest):INTERNAL_URL = "/api/internal/hog_flows/process_due_schedules"@@ -542,7 +542,7 @@ class TestProcessDueScheduleTriggers(APIBaseTest):assert len(response.json()["processed"]) == 0[email protected]("products.workflows.backend.api.hog_flow.create_hog_flow_scheduled_invocation")[email protected]("products.workflows.backend.presentation.views.hog_flow.create_hog_flow_scheduled_invocation")class TestHogFlowRun(APIBaseTest):def _create_workflow(self, workflow_status="active", trigger_type="schedule", variables=None):return HogFlow.objects.create(diff --git a/posthog/management/commands/test/test_refresh_hog_flows.py b/products/workflows/backend/test/test_refresh_hog_flows.pysimilarity index 100%rename from posthog/management/commands/test/test_refresh_hog_flows.pyrename to products/workflows/backend/test/test_refresh_hog_flows.pydiff --git a/products/workflows/backend/api/test/__init__.py b/products/workflows/backend/tests/api/__init__.pysimilarity index 100%rename from products/workflows/backend/api/test/__init__.pyrename to products/workflows/backend/tests/api/__init__.pydiff --git a/products/workflows/backend/api/test/test_action_redirects.py b/products/workflows/backend/tests/api/test_action_redirects.pysimilarity index 98%rename from products/workflows/backend/api/test/test_action_redirects.pyrename to products/workflows/backend/tests/api/test_action_redirects.pyindex 58c6f1d39250..3b4e89173614 100644--- a/products/workflows/backend/api/test/test_action_redirects.py+++ b/products/workflows/backend/tests/api/test_action_redirects.py@@ -2,7 +2,10 @@ from unittest import TestCasefrom parameterized import parameterized-from products.workflows.backend.api.action_redirects import MAX_ACTION_REDIRECTS, compute_action_redirects+from products.workflows.backend.presentation.views.action_redirects import (+ MAX_ACTION_REDIRECTS,+ compute_action_redirects,+)def _actions(*ids: str) -> list[dict]:diff --git a/products/workflows/backend/api/test/test_email_reputation.py b/products/workflows/backend/tests/api/test_email_reputation.pysimilarity index 94%rename from products/workflows/backend/api/test/test_email_reputation.pyrename to products/workflows/backend/tests/api/test_email_reputation.pyindex 8618cdb5f33c..d33f69ad9355 100644--- a/products/workflows/backend/api/test/test_email_reputation.py+++ b/products/workflows/backend/tests/api/test_email_reputation.py@@ -57,12 +57,12 @@ class TestEmailReputationAPI(APIBaseTest):provider.get_identity_isp_metrics.return_value = isp_metrics or []with (patch(- "products.workflows.backend.api.hog_flow.fetch_app_metric_totals_by_source",+ "products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals_by_source",return_value=totals_by_source,),- patch("products.workflows.backend.api.hog_flow.SESProvider", return_value=provider),+ patch("products.workflows.backend.presentation.views.hog_flow.SESProvider", return_value=provider),patch(- "products.workflows.backend.api.hog_flow._isp_breakdown_enabled",+ "products.workflows.backend.presentation.views.hog_flow._isp_breakdown_enabled",return_value=isp_flag_enabled,),):@@ -144,8 +144,11 @@ class TestEmailReputationAPI(APIBaseTest):provider = MagicMock()provider.get_tenant_reputation.side_effect = Exception("SES timeout")with (- patch("products.workflows.backend.api.hog_flow.fetch_app_metric_totals_by_source", return_value={}),- patch("products.workflows.backend.api.hog_flow.SESProvider", return_value=provider),+ patch(+ "products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals_by_source",+ return_value={},+ ),+ patch("products.workflows.backend.presentation.views.hog_flow.SESProvider", return_value=provider),):url = f"/api/projects/{self.team.id}/hog_flows/reputation"first = self.client.get(url)@@ -455,10 +458,13 @@ class TestEmailReputationAPI(APIBaseTest):provider = MagicMock()provider.get_tenant_reputation.return_value = Nonewith (- patch("products.workflows.backend.api.hog_flow.fetch_app_metric_totals_by_source", return_value={}),- patch("products.workflows.backend.api.hog_flow.SESProvider", return_value=provider),- patch("products.workflows.backend.api.hog_flow._isp_breakdown_enabled", return_value=True),- patch("products.workflows.backend.api.hog_flow.cache.add", return_value=False),+ patch(+ "products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals_by_source",+ return_value={},+ ),+ patch("products.workflows.backend.presentation.views.hog_flow.SESProvider", return_value=provider),+ patch("products.workflows.backend.presentation.views.hog_flow._isp_breakdown_enabled", return_value=True),+ patch("products.workflows.backend.presentation.views.hog_flow.cache.add", return_value=False),):response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")@@ -543,12 +549,12 @@ class TestEmailReputationAccessControl(APIBaseTest):]with (patch(- "products.workflows.backend.api.hog_flow.fetch_app_metric_totals_by_source",+ "products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals_by_source",return_value={str(flow.id): {"email_sent": 100, "email_bounced_hard": 5}},),- patch("products.workflows.backend.api.hog_flow.SESProvider", return_value=provider),+ patch("products.workflows.backend.presentation.views.hog_flow.SESProvider", return_value=provider),# Enabled, so what the assertion below tests is the access-control gate, not the flag.- patch("products.workflows.backend.api.hog_flow._isp_breakdown_enabled", return_value=True),+ patch("products.workflows.backend.presentation.views.hog_flow._isp_breakdown_enabled", return_value=True),):response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")diff --git a/products/workflows/backend/api/test/test_graph_validation.py b/products/workflows/backend/tests/api/test_graph_validation.pysimilarity index 98%rename from products/workflows/backend/api/test/test_graph_validation.pyrename to products/workflows/backend/tests/api/test_graph_validation.pyindex 4b3015fc6519..093588c55923 100644--- a/products/workflows/backend/api/test/test_graph_validation.py+++ b/products/workflows/backend/tests/api/test_graph_validation.py@@ -4,8 +4,8 @@ from unittest import TestCasefrom parameterized import parameterizedfrom rest_framework import serializers-from products.workflows.backend.api.graph_operations import apply_graph_operations-from products.workflows.backend.api.graph_validation import validate_graph+from products.workflows.backend.presentation.views.graph_operations import apply_graph_operations+from products.workflows.backend.presentation.views.graph_validation import validate_graphTRIGGER = {"id": "t", "name": "trigger", "type": "trigger", "config": {"type": "event"}}EXIT = {"id": "x", "name": "exit", "type": "exit", "config": {}}diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pysimilarity index 98%rename from products/workflows/backend/api/test/test_hog_flow.pyrename to products/workflows/backend/tests/api/test_hog_flow.pyindex 457914f15411..8f1a619edf3b 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -36,14 +36,14 @@ from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_from products.cohorts.backend.models.cohort import Cohortfrom products.skills.backend.models.skills import LLMSkillfrom products.tasks.backend.facade.contracts import WorkflowLastRunDTO-from products.workflows.backend.api.hog_flow import (+from products.workflows.backend.models.hog_flow.hog_flow import SUPPORTED_ACTION_TYPES, HogFlow+from products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import HogFlowBatchJob+from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule+from products.workflows.backend.presentation.views.hog_flow import (HogFlowActionSerializer,_should_validate_strictly,mint_audience_confirm_token,)-from products.workflows.backend.models.hog_flow.hog_flow import SUPPORTED_ACTION_TYPES, HogFlow-from products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import HogFlowBatchJob-from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule_AUDIENCE_CONDITION = {"key": "email", "type": "person", "value": "x", "operator": "icontains"}_WIDER_AUDIENCE_CONDITION = {"key": "email", "type": "person", "value": "@", "operator": "icontains"}@@ -162,7 +162,7 @@ class TestHogFlowAPI(APIBaseTest):return hog_flow, action- @patch("products.workflows.backend.api.hog_flow.publish_resource_edited")+ @patch("products.workflows.backend.presentation.views.hog_flow.publish_resource_edited")def test_emits_resource_edited_on_create_and_update(self, mock_emit):hog_flow, _ = self._create_hog_flow_with_action({"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}@@ -483,7 +483,8 @@ class TestHogFlowAPI(APIBaseTest):)with patch(- "products.workflows.backend.api.hog_flow.list_workflow_last_runs", return_value={loop.id: last_run}+ "products.workflows.backend.presentation.views.hog_flow.list_workflow_last_runs",+ return_value={loop.id: last_run},) as lookup:response = self.client.get(f"/api/projects/{self.team.id}/hog_flows")@@ -2451,7 +2452,7 @@ class TestHogFlowAPI(APIBaseTest):assert actions["trigger_node"]["type"] == "trigger"assert "exit_1" in actions- @patch("products.workflows.backend.api.hog_flow.publish_resource_edited")+ @patch("products.workflows.backend.presentation.views.hog_flow.publish_resource_edited")def test_graph_update_emits_resource_edited(self, mock_emit):# The surgical /graph path is the primary MCP edit route, so it must emit the same# "edited elsewhere" signal as the full update path — otherwise an open builder never@@ -2623,7 +2624,9 @@ class TestHogFlowAPI(APIBaseTest):assert create.status_code == 201, create.json()flow_id = create.json()["id"]- with patch("products.workflows.backend.api.hog_flow.create_hog_flow_invocation_test") as mock_invoke:+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.create_hog_flow_invocation_test"+ ) as mock_invoke:mock_invoke.return_value = MagicMock(status_code=200, json=lambda: {"status": "success"})response = self.client.post(@@ -3496,7 +3499,8 @@ class TestHogFlowAPI(APIBaseTest):with (self._account_audience_provider(),patch(- "products.workflows.backend.api.hog_flow.get_account_audience_page", return_value=["a1", "a2"]+ "products.workflows.backend.presentation.views.hog_flow.get_account_audience_page",+ return_value=["a1", "a2"],) as mock_page,):response = self.client.post(@@ -3555,7 +3559,7 @@ class TestHogFlowAPI(APIBaseTest):with (self._account_audience_provider(),patch(- "products.workflows.backend.api.hog_flow.get_account_audience_count", side_effect=[3, 10]+ "products.workflows.backend.presentation.views.hog_flow.get_account_audience_count", side_effect=[3, 10]) as mock_count,):response = self.client.post(@@ -3722,7 +3726,9 @@ class TestHogFlowAPI(APIBaseTest):assert _should_validate_strictly(context, is_draft) is expected_strictdef test_hog_flow_user_blast_radius_requires_filters(self):- with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.get_user_blast_radius"+ ) as mock_get_user_blast_radius:response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/user_blast_radius", {})assert response.status_code == 400, response.json()@@ -3730,7 +3736,9 @@ class TestHogFlowAPI(APIBaseTest):mock_get_user_blast_radius.assert_not_called()def test_hog_flow_user_blast_radius_returns_counts(self):- with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.get_user_blast_radius"+ ) as mock_get_user_blast_radius:from products.feature_flags.backend.user_blast_radius import BlastRadiusResult # noqa: PLC0415mock_get_user_blast_radius.return_value = BlastRadiusResult(affected=4, total=10)@@ -3749,10 +3757,12 @@ class TestHogFlowAPI(APIBaseTest):def test_hog_flow_user_blast_radius_routes_to_v2_when_flag_enabled(self):with (- patch("products.workflows.backend.api.hog_flow.use_audience_query_v2", return_value=True),- patch("products.workflows.backend.api.hog_flow.get_person_audience_count_v2") as mock_v2,- patch("products.workflows.backend.api.hog_flow.get_dedupe_audience_count_v2") as mock_dedupe_v2,- patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_v1,+ patch("products.workflows.backend.presentation.views.hog_flow.use_audience_query_v2", return_value=True),+ patch("products.workflows.backend.presentation.views.hog_flow.get_person_audience_count_v2") as mock_v2,+ patch(+ "products.workflows.backend.presentation.views.hog_flow.get_dedupe_audience_count_v2"+ ) as mock_dedupe_v2,+ patch("products.workflows.backend.presentation.views.hog_flow.get_user_blast_radius") as mock_v1,):from products.feature_flags.backend.user_blast_radius import BlastRadiusResult # noqa: PLC0415@@ -3801,7 +3811,7 @@ class TestHogFlowAPI(APIBaseTest):# sampled count here would move workflows numbers outside the workflows rollout.# The routing test above mocks get_user_blast_radius away, so it cannot see this.with (- patch("products.workflows.backend.api.hog_flow.use_audience_query_v2", return_value=False),+ patch("products.workflows.backend.presentation.views.hog_flow.use_audience_query_v2", return_value=False),patch("products.feature_flags.backend.user_blast_radius.use_blast_radius_query_v2", return_value=True),patch("products.feature_flags.backend.user_blast_radius.sampled_person_blast_radius") as mock_sampled,):@@ -3820,7 +3830,9 @@ class TestHogFlowAPI(APIBaseTest):HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS=set(),)def test_hog_flow_user_blast_radius_returns_default_limit_for_unlisted_team(self):- with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.get_user_blast_radius"+ ) as mock_get_user_blast_radius:from products.feature_flags.backend.user_blast_radius import BlastRadiusResult # noqa: PLC0415mock_get_user_blast_radius.return_value = BlastRadiusResult(affected=0, total=0)@@ -3839,7 +3851,9 @@ class TestHogFlowAPI(APIBaseTest):HOGFLOW_BATCH_TRIGGER_LIMIT_ELEVATED=50000,HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS={self.team.id},),- patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius,+ patch(+ "products.workflows.backend.presentation.views.hog_flow.get_user_blast_radius"+ ) as mock_get_user_blast_radius,):from products.feature_flags.backend.user_blast_radius import BlastRadiusResult # noqa: PLC0415@@ -3875,7 +3889,9 @@ class TestHogFlowAPI(APIBaseTest):secure_value=hash_key_value(key),scopes=["hog_flow:read", "person:read"],)- with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.get_user_blast_radius"+ ) as mock_get_user_blast_radius:from products.feature_flags.backend.user_blast_radius import BlastRadiusResult # noqa: PLC0415mock_get_user_blast_radius.return_value = BlastRadiusResult(affected=1, total=10)@@ -3905,7 +3921,9 @@ class TestHogFlowAPI(APIBaseTest):def test_hog_flow_user_blast_radius_rejects_flag_condition(self, _name, properties):# Feature flags can't be sized as a static batch audience — reject with a clean 400 before# the condition reaches the blast-radius query (where it would otherwise 500).- with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.get_user_blast_radius"+ ) as mock_get_user_blast_radius:response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",{"filters": {"properties": properties}},@@ -3917,7 +3935,9 @@ class TestHogFlowAPI(APIBaseTest):@override_settings(INTERNAL_API_SECRET="test-secret-123")def test_internal_user_blast_radius_rejects_flag_condition(self):- with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.get_user_blast_radius"+ ) as mock_get_user_blast_radius:response = self.client.post(f"/api/projects/{self.team.id}/internal/hog_flows/user_blast_radius",{"filters": {"properties": [{"key": "my-other-flag", "type": "flag", "value": "true"}]}},@@ -3932,7 +3952,7 @@ class TestHogFlowAPI(APIBaseTest):@override_settings(INTERNAL_API_SECRET="test-secret-123")def test_internal_user_blast_radius_persons_rejects_flag_condition(self):with patch(- "products.workflows.backend.api.hog_flow.get_batch_audience_person_ids"+ "products.workflows.backend.presentation.views.hog_flow.get_batch_audience_person_ids") as mock_get_batch_audience_person_ids:response = self.client.post(f"/api/projects/{self.team.id}/internal/hog_flows/user_blast_radius_persons",@@ -3954,9 +3974,10 @@ class TestHogFlowAPI(APIBaseTest):@override_settings(INTERNAL_API_SECRET="test-secret-123")def test_internal_user_blast_radius_persons_uses_workflows_query(self, _name, gate_on, expected_timeout_mode):with (- patch("products.workflows.backend.api.hog_flow.use_audience_query_v2", return_value=gate_on),+ patch("products.workflows.backend.presentation.views.hog_flow.use_audience_query_v2", return_value=gate_on),patch(- "products.workflows.backend.api.hog_flow.get_batch_audience_person_ids", return_value=["id-1"]+ "products.workflows.backend.presentation.views.hog_flow.get_batch_audience_person_ids",+ return_value=["id-1"],) as mock_workflows_query,):response = self.client.post(@@ -3991,11 +4012,11 @@ class TestHogFlowAPI(APIBaseTest):with (patch(- "products.workflows.backend.api.hog_flow.get_user_blast_radius",+ "products.workflows.backend.presentation.views.hog_flow.get_user_blast_radius",return_value=BlastRadiusResult(affected=5, total=10),) as mock_legacy_count,patch(- "products.workflows.backend.api.hog_flow.get_batch_audience_count", return_value=3+ "products.workflows.backend.presentation.views.hog_flow.get_batch_audience_count", return_value=3) as mock_deduped_count,patch("posthog.models.team.team.Team.persons_seen_so_far",@@ -5060,7 +5081,7 @@ class TestHogFlowAPI(APIBaseTest):assert HogFlow.objects.filter(id__in=ids).count() == 0assert ActivityLog.objects.filter(scope="HogFlow", activity="deleted", item_id__in=ids).count() == 3- @patch("products.workflows.backend.api.hog_flow.report_user_action")+ @patch("products.workflows.backend.presentation.views.hog_flow.report_user_action")def test_delete_writes_deleted_activity_and_usage_event(self, mock_report):flow_id = self._create_flow(name="Doomed")@@ -5538,7 +5559,8 @@ class TestHogFlowSecretInputs(APIBaseTest):assert "ROTATED-IN-DRAFT" not in json.dumps(flow.draft)with patch(- "products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count", side_effect=Exception("down")+ "products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count",+ side_effect=Exception("down"),):confirm_token = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {}).json()["confirm_token"@@ -5578,7 +5600,8 @@ class TestHogFlowSecretInputs(APIBaseTest):def _publish_confirmed(self, flow_id: str):with patch(- "products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count", side_effect=Exception("down")+ "products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count",+ side_effect=Exception("down"),):token = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {}).json()["confirm_token"@@ -5714,7 +5737,9 @@ class TestHogFlowSecretInputs(APIBaseTest):config = self._flow_payload()self._function_inputs(config)["api_key"] = {"secret": True}- with patch("products.workflows.backend.api.hog_flow.create_hog_flow_invocation_test") as mock_invoke:+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.create_hog_flow_invocation_test"+ ) as mock_invoke:mock_invoke.return_value = MagicMock(status_code=200, json=lambda: {"status": "success"})response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/invocations/",@@ -6115,7 +6140,7 @@ class TestFlagGatedTemplates(APIBaseTest):# workflows through this endpoint directly - without the server-side gate they could# attach the step on any team.with patch(- "products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=flag_enabled+ "products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=flag_enabled) as mock_gate:response = self._post_flow_with_create_task_action()@@ -6133,7 +6158,7 @@ class TestFlagGatedTemplates(APIBaseTest):assert gated_template_enabled("workflow-ai-task-action", self.team) is Falsedef _create_active_flow_with_gated_step(self) -> str:- with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=True):+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=True):response = self._post_flow_with_create_task_action()assert response.status_code == status.HTTP_201_CREATED, response.json()flow_id = response.json()["id"]@@ -6154,7 +6179,7 @@ class TestFlagGatedTemplates(APIBaseTest):# No MCP header: MCP callers can't resend the whole actions array (workflows-patch-graph# owns that), but an active flow validates strictly for every client, so the gate still runs.- with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=False):+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=False):response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}",{"name": "Renamed flow", "actions": HogFlow.objects.get(id=flow_id).actions},@@ -6166,7 +6191,7 @@ class TestFlagGatedTemplates(APIBaseTest):self._create_active_flow_with_gated_step()out = StringIO()- with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=False):+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=False):call_command("refresh_hog_flows", "--team-id", str(self.team.id), stdout=out)assert "Errors: 0" in out.getvalue(), out.getvalue()@@ -6175,7 +6200,7 @@ class TestFlagGatedTemplates(APIBaseTest):# Lenient web draft saves skip the gate, so an unflagged user can store the step in a# draft. Grandfathering must not treat that as authorization: activation re-checks the# flag, or the draft path becomes a gate bypass.- with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=False):+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=False):create = self._post_flow_with_create_task_action_as_web()assert create.status_code == status.HTTP_201_CREATED, create.json()flow_id = create.json()["id"]@@ -6197,7 +6222,7 @@ class TestFlagGatedTemplates(APIBaseTest):"type": "function","config": {"template_id": "template-posthog-create-task", "inputs": {"prompt": {"value": "Another"}}},}- with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=False):+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=False):response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}",{"actions": [*HogFlow.objects.get(id=flow_id).actions, second_step]},@@ -6237,7 +6262,7 @@ class TestCreateTaskActionValidation(APIBaseTest):}# Strict validation, same as any programmatic caller - the path a misconfigured# workflow is actually authored through.- with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=True):+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=True):return self.client.post(f"/api/projects/{self.team.id}/hog_flows",{"name": "Test Flow", "actions": [trigger_action, action], "edges": []},@@ -6254,7 +6279,9 @@ class TestCreateTaskActionValidation(APIBaseTest):def test_accepts_a_connector_the_workflow_owner_can_mount(self):# products.workflows may not depend on products.mcp_store's models directly (tach# boundary) - mocking at the same seam the model-catalogue tests below use.- with patch("products.workflows.backend.api.hog_flow.resolve_connectors", return_value=["some-server-id"]):+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.resolve_connectors", return_value=["some-server-id"]+ ):response = self._post_flow({"connectors": {"value": ["some-server-id"]}})assert response.status_code == status.HTTP_201_CREATED, response.json()@@ -6312,7 +6339,7 @@ class TestCreateTaskActionValidation(APIBaseTest):def test_accepts_a_skill_name_that_exists(self):# products.workflows may not depend on products.skills' models directly (tach# boundary) - mocking at the same seam the connector test above uses.- with patch("products.workflows.backend.api.hog_flow.validate_skill_names", return_value=None):+ with patch("products.workflows.backend.presentation.views.hog_flow.validate_skill_names", return_value=None):response = self._post_flow({"skills": {"value": ["error-triage"]}})assert response.status_code == status.HTTP_201_CREATED, response.json()@@ -6353,7 +6380,7 @@ class TestCreateTaskActionValidation(APIBaseTest):def test_rejects_a_model_outside_the_task_model_catalogue(self):with patch(- "products.workflows.backend.api.hog_flow.available_model_choices",+ "products.workflows.backend.presentation.views.hog_flow.available_model_choices",return_value=(SimpleNamespace(model="claude-opus"),),):response = self._post_flow({"model": {"value": {"model": "not-a-real-model"}}})@@ -6363,7 +6390,7 @@ class TestCreateTaskActionValidation(APIBaseTest):def test_accepts_a_model_in_the_task_model_catalogue(self):with patch(- "products.workflows.backend.api.hog_flow.available_model_choices",+ "products.workflows.backend.presentation.views.hog_flow.available_model_choices",return_value=(SimpleNamespace(model="claude-opus"),),):response = self._post_flow({"model": {"value": {"model": "claude-opus"}}})@@ -6373,7 +6400,7 @@ class TestCreateTaskActionValidation(APIBaseTest):def test_does_not_block_saving_while_the_model_catalogue_is_unreachable(self):# An empty catalogue means the gateway couldn't be reached, not that no model is# valid - a gateway outage must not block every workflow save.- with patch("products.workflows.backend.api.hog_flow.available_model_choices", return_value=()):+ with patch("products.workflows.backend.presentation.views.hog_flow.available_model_choices", return_value=()):response = self._post_flow({"model": {"value": {"model": "whatever-model"}}})assert response.status_code == status.HTTP_201_CREATED, response.json()@@ -6383,7 +6410,7 @@ class TestCreateTaskActionValidation(APIBaseTest):# reasoning_effort is a plain CharField with no cross-check), so a mismatch saved here# would otherwise reach the agent sandbox unvalidated instead of failing anywhere.with patch(- "products.workflows.backend.api.hog_flow.available_model_choices",+ "products.workflows.backend.presentation.views.hog_flow.available_model_choices",return_value=(SimpleNamespace(model="claude-opus", supported_efforts=("low", "high")),),):response = self._post_flow({"model": {"value": {"model": "claude-opus", "reasoning_effort": "ultracode"}}})@@ -6393,7 +6420,7 @@ class TestCreateTaskActionValidation(APIBaseTest):def test_accepts_a_reasoning_effort_the_selected_model_supports(self):with patch(- "products.workflows.backend.api.hog_flow.available_model_choices",+ "products.workflows.backend.presentation.views.hog_flow.available_model_choices",return_value=(SimpleNamespace(model="claude-opus", supported_efforts=("low", "high")),),):response = self._post_flow({"model": {"value": {"model": "claude-opus", "reasoning_effort": "high"}}})@@ -6467,7 +6494,7 @@ class TestRunScoutActionValidation(APIBaseTest):}# Strict validation, same as any programmatic caller - the path a misconfigured# workflow is actually authored through.- with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=True):+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=True):return self.client.post(f"/api/projects/{team.id}/hog_flows",{"name": "Test Flow", "actions": [trigger_action, action], "edges": []},diff --git a/products/workflows/backend/api/test/test_hog_flow_access_control.py b/products/workflows/backend/tests/api/test_hog_flow_access_control.pysimilarity index 99%rename from products/workflows/backend/api/test/test_hog_flow_access_control.pyrename to products/workflows/backend/tests/api/test_hog_flow_access_control.pyindex c16423bd682a..bc0474582683 100644--- a/products/workflows/backend/api/test/test_hog_flow_access_control.py+++ b/products/workflows/backend/tests/api/test_hog_flow_access_control.py@@ -30,7 +30,7 @@ TRIGGER_ACTION = {# Any UUID — the parent workflow's object-level check rejects before the schedule is ever looked up.MISSING_SCHEDULE_ID = "00000000-0000-0000-0000-000000000000"-CANCEL_PROXY = "products.workflows.backend.api.hog_flow.cancel_hog_flow_invocations"+CANCEL_PROXY = "products.workflows.backend.presentation.views.hog_flow.cancel_hog_flow_invocations"class TestHogFlowResourceRegistration(SimpleTestCase):diff --git a/products/workflows/backend/api/test/test_hog_flow_action_email.py b/products/workflows/backend/tests/api/test_hog_flow_action_email.pysimilarity index 99%rename from products/workflows/backend/api/test/test_hog_flow_action_email.pyrename to products/workflows/backend/tests/api/test_hog_flow_action_email.pyindex 758fa1c7128c..249ab9644d2a 100644--- a/products/workflows/backend/api/test/test_hog_flow_action_email.py+++ b/products/workflows/backend/tests/api/test_hog_flow_action_email.py@@ -15,7 +15,7 @@ from products.workflows.backend.models.hog_flow_revision import HogFlowRevisionwebhook_template = MOCK_NODE_TEMPLATES[0]-RENDER_PATH = "products.workflows.backend.api.hog_flow.render_design_html"+RENDER_PATH = "products.workflows.backend.presentation.views.hog_flow.render_design_html"RENDERED_HTML = "<html>rendered</html>"@@ -578,7 +578,7 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):}with patch(- "products.workflows.backend.api.hog_flow.MATERIALIZED_TEMPLATE_CONTENT_MAX_BYTES",+ "products.workflows.backend.presentation.views.hog_flow.MATERIALIZED_TEMPLATE_CONTENT_MAX_BYTES",8000,):response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", flow, HTTP_X_POSTHOG_CLIENT="mcp")diff --git a/products/workflows/backend/api/test/test_hog_flow_cancel.py b/products/workflows/backend/tests/api/test_hog_flow_cancel.pysimilarity index 97%rename from products/workflows/backend/api/test/test_hog_flow_cancel.pyrename to products/workflows/backend/tests/api/test_hog_flow_cancel.pyindex 7abab51e6da6..241ca1cd8548 100644--- a/products/workflows/backend/api/test/test_hog_flow_cancel.py+++ b/products/workflows/backend/tests/api/test_hog_flow_cancel.py@@ -11,8 +11,8 @@ from posthog.uuidt import UUIDTfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob-CANCEL_PROXY = "products.workflows.backend.api.hog_flow.cancel_hog_flow_invocations"-CANCEL_BATCH_PROXY = "products.workflows.backend.api.hog_flow.cancel_hog_flow_batch_job"+CANCEL_PROXY = "products.workflows.backend.presentation.views.hog_flow.cancel_hog_flow_invocations"+CANCEL_BATCH_PROXY = "products.workflows.backend.presentation.views.hog_flow.cancel_hog_flow_batch_job"BATCH_DISPATCH = ("products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation")diff --git a/products/workflows/backend/api/test/test_hog_flow_clock_waits.py b/products/workflows/backend/tests/api/test_hog_flow_clock_waits.pysimilarity index 100%rename from products/workflows/backend/api/test/test_hog_flow_clock_waits.pyrename to products/workflows/backend/tests/api/test_hog_flow_clock_waits.pydiff --git a/products/workflows/backend/api/test/test_hog_flow_delay_until.py b/products/workflows/backend/tests/api/test_hog_flow_delay_until.pysimilarity index 100%rename from products/workflows/backend/api/test/test_hog_flow_delay_until.pyrename to products/workflows/backend/tests/api/test_hog_flow_delay_until.pydiff --git a/products/workflows/backend/api/test/test_hog_flow_draft_publish.py b/products/workflows/backend/tests/api/test_hog_flow_draft_publish.pysimilarity index 98%rename from products/workflows/backend/api/test/test_hog_flow_draft_publish.pyrename to products/workflows/backend/tests/api/test_hog_flow_draft_publish.pyindex 7352b6592888..81b1a478cc4f 100644--- a/products/workflows/backend/api/test/test_hog_flow_draft_publish.py+++ b/products/workflows/backend/tests/api/test_hog_flow_draft_publish.py@@ -10,9 +10,9 @@ from posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom posthog.models.activity_logging.activity_log import ActivityLogfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES-from products.workflows.backend.api.hog_flow import WRITABLE_DRAFT_CONTENT_FIELDSfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_revision import HogFlowRevision+from products.workflows.backend.presentation.views.hog_flow import WRITABLE_DRAFT_CONTENT_FIELDSwebhook_template = MOCK_NODE_TEMPLATES[0]@@ -441,7 +441,7 @@ class TestHogFlowDraftPublish(APIBaseTest):return HogFlow.objects.get(pk=flow_id)def _publish_preview(self, flow_id: str, counts: dict | None = None):- with patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count") as mock_count:+ with patch("products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count") as mock_count:if counts is None:mock_count.side_effect = Exception("count service down")else:@@ -450,7 +450,7 @@ class TestHogFlowDraftPublish(APIBaseTest):assert response.status_code == 200, response.json()return response- @patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count")+ @patch("products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count")def test_publish_without_confirm_returns_impact_only(self, mock_count):mock_count.return_value = MagicMock(status_code=200, json=lambda: {"count": 42, "by_action": {"action_1": 42}, "position_unknown": 0}@@ -476,7 +476,7 @@ class TestHogFlowDraftPublish(APIBaseTest):assert flow.actions == live_actions_beforeassert flow.draft is not None- @patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count")+ @patch("products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count")def test_publish_impact_degrades_to_null_counts_when_unavailable(self, mock_count):mock_count.side_effect = Exception("node service down")flow_id = self._create_active_flow()@@ -488,7 +488,7 @@ class TestHogFlowDraftPublish(APIBaseTest):# Graph-derived impact still renders; only the counts degradeassert response.json()["impact"]["position_unknown"] is None- @patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count")+ @patch("products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count")def test_publish_preview_reports_deleted_step_moves(self, mock_count):mock_count.return_value = MagicMock(status_code=200, json=lambda: {"count": 7, "by_action": {"action_1": 5}, "position_unknown": 2}@@ -622,7 +622,7 @@ class TestHogFlowDraftPublish(APIBaseTest):# ── Test-run from draft ──────────────────────────────────────────- @patch("products.workflows.backend.api.hog_flow.create_hog_flow_invocation_test")+ @patch("products.workflows.backend.presentation.views.hog_flow.create_hog_flow_invocation_test")def test_invocation_with_use_draft_sends_draft_as_configuration(self, mock_invoke):mock_invoke.return_value = MagicMock(status_code=200, json=lambda: {"status": "success"})flow_id = self._create_active_flow()diff --git a/products/workflows/backend/api/test/test_hog_flow_invocation_results.py b/products/workflows/backend/tests/api/test_hog_flow_invocation_results.pysimilarity index 100%rename from products/workflows/backend/api/test/test_hog_flow_invocation_results.pyrename to products/workflows/backend/tests/api/test_hog_flow_invocation_results.pydiff --git a/products/workflows/backend/api/test/test_hog_flow_revisions.py b/products/workflows/backend/tests/api/test_hog_flow_revisions.pysimilarity index 98%rename from products/workflows/backend/api/test/test_hog_flow_revisions.pyrename to products/workflows/backend/tests/api/test_hog_flow_revisions.pyindex abd8ff507ca7..fb8f62c7e683 100644--- a/products/workflows/backend/api/test/test_hog_flow_revisions.py+++ b/products/workflows/backend/tests/api/test_hog_flow_revisions.py@@ -9,8 +9,8 @@ from posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom posthog.models.activity_logging.activity_log import ActivityLogfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES-from products.workflows.backend.api.hog_flow import DRAFT_CONTENT_FIELDSfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.presentation.views.hog_flow import DRAFT_CONTENT_FIELDSwebhook_template = MOCK_NODE_TEMPLATES[0]@@ -104,7 +104,7 @@ class TestHogFlowRevisions(APIBaseTest):assert response.status_code == 200, response.json()def _publish(self, flow_id: str):- with patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count") as mock_count:+ with patch("products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count") as mock_count:mock_count.return_value = MagicMock(status_code=200, json=lambda: {"count": 0, "by_action": {}, "position_unknown": 0})diff --git a/products/workflows/backend/api/test/test_hog_flow_template.py b/products/workflows/backend/tests/api/test_hog_flow_template.pysimilarity index 100%rename from products/workflows/backend/api/test/test_hog_flow_template.pyrename to products/workflows/backend/tests/api/test_hog_flow_template.pydiff --git a/products/workflows/backend/api/test/test_hog_flow_timing_reschedule.py b/products/workflows/backend/tests/api/test_hog_flow_timing_reschedule.pysimilarity index 97%rename from products/workflows/backend/api/test/test_hog_flow_timing_reschedule.pyrename to products/workflows/backend/tests/api/test_hog_flow_timing_reschedule.pyindex 5ada972b51ff..788b428df2ef 100644--- a/products/workflows/backend/api/test/test_hog_flow_timing_reschedule.py+++ b/products/workflows/backend/tests/api/test_hog_flow_timing_reschedule.py@@ -10,7 +10,7 @@ from products.workflows.backend.models.hog_flow.hog_flow import HogFlowwebhook_template = MOCK_NODE_TEMPLATES[0]-TASK_PATH = "products.workflows.backend.api.hog_flow.reschedule_hog_flow_timing"+TASK_PATH = "products.workflows.backend.presentation.views.hog_flow.reschedule_hog_flow_timing"def _actions(delay_duration: str = "7d", webhook_url: str = "https://example.com") -> list[dict]:@@ -137,7 +137,7 @@ class TestHogFlowTimingRescheduleTrigger(APIBaseTest):mock_task.delay.assert_not_called()with patch(- "products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count",+ "products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count",side_effect=Exception("count service down"),):preview = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {})diff --git a/products/workflows/backend/api/test/test_message_assets.py b/products/workflows/backend/tests/api/test_message_assets.pysimilarity index 100%rename from products/workflows/backend/api/test/test_message_assets.pyrename to products/workflows/backend/tests/api/test_message_assets.pydiff --git a/products/workflows/backend/api/test/test_message_preferences_access_control.py b/products/workflows/backend/tests/api/test_message_preferences_access_control.pysimilarity index 100%rename from products/workflows/backend/api/test/test_message_preferences_access_control.pyrename to products/workflows/backend/tests/api/test_message_preferences_access_control.pydiff --git a/products/workflows/backend/api/test/test_message_suppression_access_control.py b/products/workflows/backend/tests/api/test_message_suppression_access_control.pysimilarity index 100%rename from products/workflows/backend/api/test/test_message_suppression_access_control.pyrename to products/workflows/backend/tests/api/test_message_suppression_access_control.pydiff --git a/products/workflows/backend/api/test/test_publish_impact.py b/products/workflows/backend/tests/api/test_publish_impact.pysimilarity index 98%rename from products/workflows/backend/api/test/test_publish_impact.pyrename to products/workflows/backend/tests/api/test_publish_impact.pyindex 854f02a0bf86..6e42b5640d78 100644--- a/products/workflows/backend/api/test/test_publish_impact.py+++ b/products/workflows/backend/tests/api/test_publish_impact.py@@ -4,7 +4,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from products.workflows.backend.api.publish_impact import build_publish_impact, find_variable_references+from products.workflows.backend.presentation.views.publish_impact import build_publish_impact, find_variable_referencesdef _action(action_id: str, name: str | None = None, output_variable: dict | list | None = None, **config) -> dict:diff --git a/products/workflows/backend/api/test/test_workflow_email_pause.py b/products/workflows/backend/tests/api/test_workflow_email_pause.pysimilarity index 100%rename from products/workflows/backend/api/test/test_workflow_email_pause.pyrename to products/workflows/backend/tests/api/test_workflow_email_pause.pydiff --git a/products/workflows/backend/api/test/test_workflow_proposals.py b/products/workflows/backend/tests/api/test_workflow_proposals.pysimilarity index 98%rename from products/workflows/backend/api/test/test_workflow_proposals.pyrename to products/workflows/backend/tests/api/test_workflow_proposals.pyindex 241570848075..c92db32ef7a4 100644--- a/products/workflows/backend/api/test/test_workflow_proposals.py+++ b/products/workflows/backend/tests/api/test_workflow_proposals.py@@ -12,9 +12,9 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES-from products.workflows.backend.api.hog_flow import DRAFT_CONTENT_FIELDSfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.workflow_proposal import WorkflowProposal+from products.workflows.backend.presentation.views.hog_flow import DRAFT_CONTENT_FIELDSwebhook_template = MOCK_NODE_TEMPLATES[0]@@ -40,7 +40,7 @@ def _webhook_action(action_id: str = "action_1", url: str = "https://example.com}-@patch("products.workflows.backend.api.hog_flow.posthoganalytics.feature_enabled", return_value=True)+@patch("products.workflows.backend.presentation.views.hog_flow.posthoganalytics.feature_enabled", return_value=True)class TestWorkflowProposals(APIBaseTest):def setUp(self):super().setUp()@@ -83,7 +83,7 @@ class TestWorkflowProposals(APIBaseTest):return response.json()def _publish(self, flow_id: str):- with patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count") as mock_count:+ with patch("products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count") as mock_count:mock_count.return_value = MagicMock(status_code=200, json=lambda: {"count": 0, "by_action": {}, "position_unknown": 0})@@ -467,7 +467,7 @@ class TestWorkflowProposals(APIBaseTest):self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})self._publish(flow_id)- with patch("products.workflows.backend.api.hog_flow.fetch_app_metric_totals") as mock_totals:+ with patch("products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals") as mock_totals:mock_totals.return_value = SimpleNamespace(totals={})response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"@@ -767,7 +767,7 @@ class TestWorkflowProposals(APIBaseTest):assert [row["id"] for row in listed.json()["results"]] == [str(written_first.id)]-@patch("products.workflows.backend.api.hog_flow.posthoganalytics.feature_enabled", return_value=False)+@patch("products.workflows.backend.presentation.views.hog_flow.posthoganalytics.feature_enabled", return_value=False)class TestWorkflowProposalsFlagOff(APIBaseTest):def setUp(self):super().setUp()diff --git a/products/workflows/backend/api/test/test_workflow_scout_runs_api.py b/products/workflows/backend/tests/api/test_workflow_scout_runs_api.pysimilarity index 98%rename from products/workflows/backend/api/test/test_workflow_scout_runs_api.pyrename to products/workflows/backend/tests/api/test_workflow_scout_runs_api.pyindex a23f33e5169f..d7d23c037f20 100644--- a/products/workflows/backend/api/test/test_workflow_scout_runs_api.py+++ b/products/workflows/backend/tests/api/test_workflow_scout_runs_api.py@@ -18,7 +18,7 @@ from products.workflows.backend.models import HogFlowSECRET = "test-workflow-scout-run-jwt"SCOUT = "signals-scout-error-tracking"-_START_SCOUT = "products.workflows.backend.api.workflow_scout_runs.start_workflow_scout_run"+_START_SCOUT = "products.workflows.backend.presentation.views.workflow_scout_runs.start_workflow_scout_run"def _token(diff --git a/products/workflows/backend/utils/batch_trigger_limit.py b/products/workflows/backend/utils/batch_trigger_limit.pyindex d46b64ac2a25..653efcb1b2b3 100644--- a/products/workflows/backend/utils/batch_trigger_limit.py+++ b/products/workflows/backend/utils/batch_trigger_limit.py@@ -5,7 +5,7 @@ from products.workflows.backend.utils.email_sending_tiers import (resolve_team_email_sending_tier,)-# Kept in sync with _FIXED_TEMPLATE_IDS["function_email"] in products/workflows/backend/api/hog_flow.py.+# Kept in sync with _FIXED_TEMPLATE_IDS["function_email"] in products/workflows/backend/presentation/views/hog_flow.py._EMAIL_TEMPLATE_ID = "template-email"diff --git a/products/workflows/backend/utils/email_sending_tiers.py b/products/workflows/backend/utils/email_sending_tiers.pyindex 3a1612f6c6fb..1131ca9b3376 100644--- a/products/workflows/backend/utils/email_sending_tiers.py+++ b/products/workflows/backend/utils/email_sending_tiers.py@@ -6,6 +6,7 @@ import structlogfrom posthog.dataclasses import frozen+from products.workflows.backend.facade.contracts import EmailSendingTierLimitsfrom products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfiglogger = structlog.get_logger(__name__)@@ -15,16 +16,6 @@ TierMode = Literal["off", "shadow", "enforce"]MIN_EMAIL_SENDING_TIER = 0-@frozen-class EmailSendingTierLimits:- """What a trust tier allows: two send-rate caps and a maximum batch audience."""-- tier: int- per_hour: int- per_day: int- max_batch_audience: int--@frozenclass TeamEmailSendingTier:tier: intdiff --git a/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.ts b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.tsindex 0e489d48a187..30e1d43a838c 100644--- a/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.ts+++ b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.ts@@ -2,7 +2,7 @@// products/workflows/backend/metrics.py.export const MIN_EVIDENCE_SAMPLE = 20-// Mirrors EVIDENCE_UNITS in products/workflows/backend/api/hog_flow.py.+// Mirrors EVIDENCE_UNITS in products/workflows/backend/presentation/views/hog_flow.py.export type EvidenceUnit = 'rate' | 'count'export interface GuardrailReading {diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex 9b641a0f50c0..0c4def52a7b6 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -166,7 +166,7 @@ export function withStagedDraft(workflow: HogFlow): HogFlow {return { ...rest, ...draft } as HogFlow}-// Mirrors DRAFT_CONTENT_FIELDS in products/workflows/backend/api/hog_flow.py: the fields the draft+// Mirrors DRAFT_CONTENT_FIELDS in products/workflows/backend/presentation/views/hog_flow.py: the fields the draft// cycle stages and publish promotes. Keep the two lists in sync.const WORKFLOW_CONTENT_FIELDS = ['actions',diff --git a/products/workflows/frontend/Workflows/workflowSearchMatches.ts b/products/workflows/frontend/Workflows/workflowSearchMatches.tsindex 937472c5e9a7..05195fddd3be 100644--- a/products/workflows/frontend/Workflows/workflowSearchMatches.ts+++ b/products/workflows/frontend/Workflows/workflowSearchMatches.ts@@ -11,7 +11,7 @@ export interface WorkflowStepMatch {const EXCERPT_PADDING = 40-// Mirrors _EMAIL_BODY_TEXT_SQL in the list API (products/workflows/backend/api/hog_flow.py), so the hint+// Mirrors _EMAIL_BODY_TEXT_SQL in the list API (products/workflows/backend/presentation/views/hog_flow.py), so the hint// shows the text the API matched. The tag pattern skips over quoted attribute values, so a '>' inside// one does not end the tag early and leak the rest of the attribute into the searchable text.const HTML_STYLE_BLOCK = /<style[^>]*>[\s\S]*?<\/style>/gidiff --git a/products/workflows/tsconfig.json b/products/workflows/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/workflows/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/pyproject.toml b/pyproject.tomlindex 1aba5c568fb5..d23535acc8c5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -724,6 +724,49 @@ ignore_imports = [# (warehouse_sources, data_modeling, data_tools, cdp, revenue_analytics, batch_exports)# directly. Thin each viewset to parse -> facade -> serialize and delete each entry.# backend:contract-check stays off until this list is empty.+ # TODO: workflows presentation wave — the moved viewsets still reach in-product internals and+ # sibling products (cdp, cohorts, feature_flags, messaging) directly. Thin each viewset to+ # parse -> facade -> serialize and delete each entry. backend:contract-check stays off until+ # this list is empty. Only delete entries here: a new import from these views goes through+ # the facade.+ "products.workflows.backend.presentation.views.hog_flow -> products.cdp.backend.models.hog_function_template",+ "products.workflows.backend.presentation.views.hog_flow -> products.cohorts.backend.models.cohort",+ "products.workflows.backend.presentation.views.hog_flow -> products.cohorts.backend.models.util",+ "products.workflows.backend.presentation.views.hog_flow -> products.feature_flags.backend.person_sampling",+ "products.workflows.backend.presentation.views.hog_flow -> products.feature_flags.backend.user_blast_radius",+ "products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.api.design_operations",+ "products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.api.design_validation",+ "products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.api.message_templates",+ "products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.models",+ "products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.unlayer",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.metrics",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow.hog_flow",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_batch_job",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_revision",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_schedule",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.team_workflows_config",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.workflow_proposal",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.providers.ses",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.account_audience",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.audience_v2",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.batch_audience",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.email_sending_attribution",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.timing_reschedule",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.wait_clock_conditions",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.workflow_email_health",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.tasks.hog_flows",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.batch_trigger_limit",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.durations",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.email_sending_tiers",+ "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.rrule_utils",+ "products.workflows.backend.presentation.views.hog_flow_batch_job -> products.workflows.backend.models.hog_flow_batch_job",+ "products.workflows.backend.presentation.views.hog_flow_template -> products.cdp.backend.models.hog_function_template",+ "products.workflows.backend.presentation.views.hog_flow_template -> products.workflows.backend.models.hog_flow.hog_flow_template",+ "products.workflows.backend.presentation.views.hog_flow_template -> products.workflows.backend.templates",+ "products.workflows.backend.presentation.views.workflow_scout_runs -> products.workflows.backend.models",+ "products.workflows.backend.presentation.views.workflow_scout_runs -> products.workflows.backend.service_jwt",+ "products.workflows.backend.presentation.views.workflow_tasks -> products.workflows.backend.models",+ "products.workflows.backend.presentation.views.workflow_tasks -> products.workflows.backend.service_jwt",# TODO: access-control presentation wave — the consolidated RBAC viewsets carry their ORM# access with them. Thin them to parse -> facade -> serialize and delete each entry."products.access_control.backend.presentation.access_control -> products.access_control.backend.models.access_control",@@ -806,10 +849,6 @@ ignore_imports = ["products.web_analytics.backend.routes -> products.web_analytics.backend.api.web_analytics_achievements","products.web_analytics.backend.routes -> products.web_analytics.backend.api.web_analytics_filter_preset","products.web_analytics.backend.routes -> products.web_analytics.backend.api.web_analytics_path_cleaning_suggestions",- "products.workflows.backend.routes -> products.workflows.backend.api.hog_flow",- "products.workflows.backend.routes -> products.workflows.backend.api.hog_flow_template",- "products.workflows.backend.routes -> products.workflows.backend.api.workflow_scout_runs",- "products.workflows.backend.routes -> products.workflows.backend.api.workflow_tasks",]# webhook_consumers.py is the one module core reads (through posthog.ingress.dispatch.loading)@@ -849,6 +888,7 @@ ignore_imports = ["products.logs.backend.facade.retention_views -> products.logs.backend.presentation.views.retention_api","products.managed_warehouse.backend.facade.api -> products.managed_warehouse.backend.presentation.views","products.tasks.backend.facade.api -> products.tasks.backend.presentation.serializers",+ "products.workflows.backend.facade.api -> products.workflows.backend.presentation.views.hog_flow","products.billing_alerts.backend.facade.api -> rest_framework","products.dashboards.backend.facade.api -> rest_framework","products.experiments.backend.facade.api -> rest_framework",diff --git a/tach.toml b/tach.tomlindex 989857a68f6d..31303c7a5be3 100644--- a/tach.toml+++ b/tach.toml@@ -1110,6 +1110,9 @@ depends_on = [layer = "modules"# Facade + views: the canonical public surface for all isolated products.+# When `hogli lint:tach` rejects an import into a product listed here, do not widen this block or+# add an expose entry or a legacy-leak block for it. Add a function to the product's+# backend/facade/api.py that returns a contract, or a backend/facade/testing.py helper for a test.[[interfaces]]expose = [@@ -1118,7 +1121,7 @@ expose = ["backend\\.routes.*",]from = [- "products\\.(autoresearch|batch_exports|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|managed_warehouse|mcp_analytics|mcp_store|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review|warehouse_sources)",+ "products\\.(autoresearch|batch_exports|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|managed_warehouse|mcp_analytics|mcp_store|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review|warehouse_sources|workflows)",]# TODO: Experiments-specific temporary interface