:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): rotate email sends across multiple senders (#83356)
Arthur Moreira de Deus8d49d423f660
diff --git a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.test.ts b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.test.tsindex c537cf44421a..9045f52a0618 100644--- a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.test.ts+++ b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.test.ts@@ -284,6 +284,16 @@ describe('CyclotronJobInputsValidation', () => {expect(result.valid).toBe(true)expect(result.errors).toEqual({})})++ it('errors when a sender rotation contains more than ten senders', () => {+ const result = CyclotronJobInputsValidation.validate(+ nativeEmailInput({ integrationId: 1, integrationIds: Array.from({ length: 11 }, (_, i) => i + 1) }),+ schema+ )++ expect(result.valid).toBe(false)+ expect(result.errors.email).toContain('Choose no more than 10 email senders')+ })})describe('templating validation', () => {diff --git a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.ts b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.tsindex c188e3e2b9a6..c653e378d8bc 100644--- a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.ts+++ b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.ts@@ -1,6 +1,6 @@import { tryJsonParse } from 'lib/utils/json'import { LiquidRenderer } from 'lib/utils/liquid'-import type { EmailTemplate } from 'scenes/hog-functions/email-templater/types'+import { type EmailTemplate, MAX_WORKFLOW_EMAIL_SENDERS } from 'scenes/hog-functions/email-templater/types'import { CyclotronJobInputSchemaType, CyclotronJobInputType } from '~/types'@@ -155,6 +155,13 @@ const validateInput = (input: CyclotronJobInputType, inputSchema: CyclotronJobIn// Pull out the address so it gets the same required + templating validation as every other field —// otherwise a malformed Liquid template in the To field (or an empty address) saves with no error.const toEmail = value.to && typeof value.to === 'object' ? value.to.email : value.to+ const senderLimitError =+ inputSchema.type === 'native_email' &&+ typeof value.from === 'object' &&+ Array.isArray(value.from?.integrationIds) &&+ value.from.integrationIds.length > MAX_WORKFLOW_EMAIL_SENDERS+ ? `Choose no more than ${MAX_WORKFLOW_EMAIL_SENDERS} email senders`+ : undefinedconst emailTemplateErrors: Partial<EmailTemplate> = {html:!value.html && !value.text@@ -168,9 +175,10 @@ const validateInput = (input: CyclotronJobInputType, inputSchema: CyclotronJobIn// keys are templated sender overrides; the legacy `email` type stores a template string.from: !value.from? 'From is required'- : typeof value.from === 'string'- ? getTemplatingError(value.from)- : (getTemplatingError(value.from.email) ?? getTemplatingError(value.from.name)),+ : (senderLimitError ??+ (typeof value.from === 'string'+ ? getTemplatingError(value.from)+ : (getTemplatingError(value.from.email) ?? getTemplatingError(value.from.name)))),to: !toEmail ? 'To is required' : getTemplatingError(toEmail),}diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 907807c4f9f9..e138d418b42b 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -557,6 +557,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analyticsWORKFLOWS_EMAIL_REPUTATION: 'workflows-email-reputation', // owner: #team-workflows+ WORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflowsWORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflowsWORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflowsXAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-featuresdiff --git a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.test.tsx b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.test.tsxnew file mode 100644index 000000000000..4965bb411682--- /dev/null+++ b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.test.tsx@@ -0,0 +1,57 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import { useValues } from 'kea'++import { NativeEmailIntegrationChoice } from './EmailTemplater'++let mockSenderRotationEnabled = false++jest.mock('lib/hooks/useFeatureFlag', () => ({+ useFeatureFlag: () => mockSenderRotationEnabled,+}))++jest.mock('kea', () => ({+ ...jest.requireActual('kea'),+ useValues: jest.fn(),+}))++jest.mock('@posthog/lemon-ui', () => ({+ ...jest.requireActual('@posthog/lemon-ui'),+ LemonInputSelect: () => <div data-attr="multiple-email-sender-select" />,+ LemonSelect: () => <div data-attr="single-email-sender-select" />,+}))++describe('NativeEmailIntegrationChoice', () => {+ afterEach(cleanup)++ beforeEach(() => {+ jest.mocked(useValues).mockReturnValue({+ integrationsLoading: false,+ integrations: [+ {+ id: 1,+ kind: 'email',+ display_name: 'Alice <[email protected]>',+ },+ {+ id: 2,+ kind: 'email',+ display_name: 'Bob <[email protected]>',+ },+ ],+ })+ })++ it.each([+ [false, 'single-email-sender-select'],+ [true, 'multiple-email-sender-select'],+ ])('renders the expected sender picker when the rotation flag is %s', (flagEnabled, expectedPicker) => {+ mockSenderRotationEnabled = flagEnabled++ render(<NativeEmailIntegrationChoice label="From" value={{ integrationId: 1 }} onChange={jest.fn()} />)++ expect(screen.getByTestId(expectedPicker)).toBeInTheDocument()+ expect(screen.getByText('Custom sender')).toBeInTheDocument()+ })+})diff --git a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsxindex 53a95cf58151..076c5009b016 100644--- a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx+++ b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx@@ -6,9 +6,18 @@ import { createPortal } from 'react-dom'import EmailEditor, { EditorRef } from 'react-email-editor'import { IconCollapse, IconExpand, IconExternal, IconPlus, IconX } from '@posthog/icons'-import { LemonButton, LemonCard, LemonLabel, LemonModal, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'+import {+ LemonButton,+ LemonCard,+ LemonInputSelect,+ LemonLabel,+ LemonModal,+ LemonSegmentedButton,+ LemonSelect,+} from '@posthog/lemon-ui'import { CyclotronJobTemplateSuggestionsButton } from 'lib/components/CyclotronJob/CyclotronJobTemplateSuggestions'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'@@ -26,7 +35,7 @@ import { MessageTemplateCard } from 'products/workflows/frontend/TemplateLibraryimport { collapseToolsPanelCustomJs } from './custom-tools/collapseToolsPanel'import { unsubscribeLinkToolCustomJs } from './custom-tools/unsubscribeLinkTool'import { EMAIL_TYPE_SUPPORTED_FIELDS, EmailTemplaterLogicProps, emailTemplaterLogic } from './emailTemplaterLogic'-import { EmailFieldErrors, EmailTemplateFrom } from './types'+import { EmailFieldErrors, EmailTemplateFrom, MAX_WORKFLOW_EMAIL_SENDERS } from './types'export type EmailEditorMode = 'full' | 'preview'@@ -232,7 +241,7 @@ function DestinationEmailTemplaterForm({)}-function NativeEmailIntegrationChoice({+export function NativeEmailIntegrationChoice({label,onChange,value,@@ -244,7 +253,13 @@ function NativeEmailIntegrationChoice({}): JSX.Element {const { integrationsLoading, integrations } = useValues(integrationsLogic)const { logicProps } = useValues(emailTemplaterLogic)+ const senderRotationEnabled = useFeatureFlag('WORKFLOWS_EMAIL_SENDER_ROTATION')const integrationsOfKind = integrations?.filter((x) => x.kind === 'email')+ const selectedIntegrationIds = value?.integrationIds?.length+ ? value.integrationIds+ : value?.integrationId+ ? [value.integrationId]+ : []// Presence of the override keys is what reveals the inputs, so a saved override is// visible again on reopen without any separate reveal state.@@ -252,11 +267,21 @@ function NativeEmailIntegrationChoice({const onChangeIntegration = (integrationId: number): void => {if (integrationId === -1) {- // Open new integration modalwindow.open(urls.workflows('channels'), '_blank')return}- onChange({ ...value, integrationId })+ onChange({ ...value, integrationId, integrationIds: undefined })+ }++ const onChangeIntegrations = (integrationIds: number[]): void => {+ if (integrationIds.length > MAX_WORKFLOW_EMAIL_SENDERS) {+ return+ }+ onChange({+ ...value,+ integrationId: integrationIds[0],+ integrationIds: integrationIds.length > 1 ? integrationIds : undefined,+ })}if (!integrationsLoading && integrationsOfKind?.length === 0) {@@ -284,34 +309,66 @@ function NativeEmailIntegrationChoice({<div className="flex flex-col"><div className="flex gap-2 items-center">{label}- <LemonSelect- className="m-1 flex-1"- type="tertiary"- placeholder="Choose email sender"- loading={integrationsLoading}- options={[- {- title: 'Email senders',- options: (integrationsOfKind || []).map((integration) => ({+ {senderRotationEnabled ? (+ <div className="flex flex-col flex-1">+ <LemonInputSelect<number>+ className="m-1 flex-1"+ mode="multiple"+ placeholder="Choose email senders"+ loading={integrationsLoading}+ options={(integrationsOfKind || []).map((integration) => ({+ key: String(integration.id),label: integration.display_name,value: integration.id,- })),- },- {- options: [- {- label: 'Add new email sender',- icon: <IconExternal />,- value: -1,- },- ],- },- ]}- value={value?.integrationId}- size="small"- fullWidth- onChange={onChangeIntegration}- />+ }))}+ value={selectedIntegrationIds}+ size="small"+ fullWidth+ autoWidth={false}+ onChange={onChangeIntegrations}+ data-attr="workflow-email-sender-select"+ action={{+ children: 'Add new email sender',+ icon: <IconExternal />,+ onClick: () => window.open(urls.workflows('channels'), '_blank'),+ }}+ />+ <span className="px-2 pb-1 text-xs text-muted">+ Choose up to {MAX_WORKFLOW_EMAIL_SENDERS} senders. Each workflow run uses one sender from+ this list.+ </span>+ </div>+ ) : (+ <LemonSelect+ className="m-1 flex-1"+ type="tertiary"+ placeholder="Choose email sender"+ loading={integrationsLoading}+ options={[+ {+ title: 'Email senders',+ options: (integrationsOfKind || []).map((integration) => ({+ label: integration.display_name,+ value: integration.id,+ })),+ },+ {+ options: [+ {+ label: 'Add new email sender',+ icon: <IconExternal />,+ value: -1,+ },+ ],+ },+ ]}+ value={value?.integrationId}+ size="small"+ fullWidth+ onChange={onChangeIntegration}+ data-attr="workflow-email-sender-select"+ />+ )}{!overridesVisible && (<LemonButtonsize="xsmall"@@ -331,7 +388,7 @@ function NativeEmailIntegrationChoice({<div className="flex gap-2 items-center border-t"><LemonLabelclassName="min-w-30 shrink-0"- info="The address to send from. Templates are supported, so the address can come from the triggering event. It must be on the selected sender's verified domain. Leave empty to use the sender's address."+ info="The address to send from. Templates are supported, so the address can come from the triggering event. It must be on every selected sender's verified domain. Leave empty to use the sender's address.">Custom address</LemonLabel>@@ -346,7 +403,7 @@ function NativeEmailIntegrationChoice({icon={<IconX />}className="mr-2"data-attr="email-from-custom-sender-remove"- onClick={() => onChange({ integrationId: value?.integrationId })}+ onClick={() => onChange({ ...value, email: undefined, name: undefined })}tooltip="Remove custom sender"/></div>diff --git a/frontend/src/scenes/hog-functions/email-templater/types.ts b/frontend/src/scenes/hog-functions/email-templater/types.tsindex 404e39c4c184..53d8803bac72 100644--- a/frontend/src/scenes/hog-functions/email-templater/types.ts+++ b/frontend/src/scenes/hog-functions/email-templater/types.ts@@ -2,11 +2,14 @@ import { Editor } from 'react-email-editor'type JSONTemplate = Parameters<Editor['loadDesign']>[0]-// The native email sender: the integration pins the verified domain, while the optional-// templated overrides let a single workflow vary the sender per invocation. The runtime-// rejects an override address that is not on the integration's verified domain.+export const MAX_WORKFLOW_EMAIL_SENDERS = 10++// Native email senders: integrationIds enables stable per-run rotation, while the optional+// templated overrides vary the visible sender. The runtime rejects an override address that+// is not on the selected integration's verified domain.export type EmailTemplateFrom = {integrationId?: number+ integrationIds?: number[]email?: stringname?: string}diff --git a/nodejs/src/cdp/schema/cyclotron.test.ts b/nodejs/src/cdp/schema/cyclotron.test.tsindex 0c831dd3c0ee..561325c5a923 100644--- a/nodejs/src/cdp/schema/cyclotron.test.ts+++ b/nodejs/src/cdp/schema/cyclotron.test.ts@@ -1,5 +1,9 @@import { createHogExecutionGlobals } from '../_tests/fixtures'-import { HogFunctionInvocationGlobalsSchema } from './cyclotron'+import {+ CyclotronInvocationQueueParametersEmailSchema,+ HogFunctionInvocationGlobalsSchema,+ MAX_WORKFLOW_EMAIL_SENDERS,+} from './cyclotron'describe('cyclotron schema', () => {describe('HogFunctionInvocationGlobalsSchema', () => {@@ -36,4 +40,15 @@ describe('cyclotron schema', () => {expect((parsed as any).data.custom).toBe(1)})})++ describe('CyclotronInvocationQueueParametersEmailSchema', () => {+ it('rejects sender rotations larger than the supported limit', () => {+ const from = {+ integrationId: 1,+ integrationIds: Array.from({ length: MAX_WORKFLOW_EMAIL_SENDERS + 1 }, (_, index) => index + 1),+ }++ expect(CyclotronInvocationQueueParametersEmailSchema.shape.from.safeParse(from).success).toBe(false)+ })+ })})diff --git a/nodejs/src/cdp/schema/cyclotron.ts b/nodejs/src/cdp/schema/cyclotron.tsindex ae397cf9df6b..e3349d505adb 100644--- a/nodejs/src/cdp/schema/cyclotron.ts+++ b/nodejs/src/cdp/schema/cyclotron.ts@@ -122,6 +122,8 @@ export const CyclotronInvocationQueueParametersFetchSchema = z.object({aws_sigv4: CyclotronInvocationQueueParametersFetchAwsSigV4Schema.optional(),})+export const MAX_WORKFLOW_EMAIL_SENDERS = 10+export const CyclotronInvocationQueueParametersEmailSchema = z.object({type: z.literal('email'),to: z.object({@@ -131,8 +133,9 @@ export const CyclotronInvocationQueueParametersEmailSchema = z.object({replyTo: z.string().optional(),from: z.object({integrationId: z.number(),+ integrationIds: z.array(z.number()).max(MAX_WORKFLOW_EMAIL_SENDERS).optional(),// Templated per-invocation sender overrides. EmailService requires the rendered- // address to be on the integration's verified domain before it reaches the provider.+ // address to be on the selected integration's verified domain before it reaches the provider.email: z.string().optional(),name: z.string().optional(),}),diff --git a/nodejs/src/cdp/services/messaging/email-sender-selection.test.ts b/nodejs/src/cdp/services/messaging/email-sender-selection.test.tsnew file mode 100644index 000000000000..af2ed1b8229c--- /dev/null+++ b/nodejs/src/cdp/services/messaging/email-sender-selection.test.ts@@ -0,0 +1,46 @@+import { selectEmailSenderIntegrationId } from './email-sender-selection'++describe('selectEmailSenderIntegrationId', () => {+ it.each([+ ['keeps the legacy sender when no rotation is configured', { integrationId: 7 }, 7],+ ['uses the only sender in a configured list', { integrationId: 7, integrationIds: [11] }, 11],+ ['ignores duplicate sender ids', { integrationId: 7, integrationIds: [11, 11] }, 11],+ ])('%s', (_name, sender, expected) => {+ expect(selectEmailSenderIntegrationId('invocation-1', sender)).toBe(expected)+ })++ it('returns the same sender for retries and reordered sender lists', () => {+ const selected = selectEmailSenderIntegrationId('invocation-42', {+ integrationId: 11,+ integrationIds: [11, 22, 33],+ })++ expect(+ selectEmailSenderIntegrationId('invocation-42', {+ integrationId: 33,+ integrationIds: [33, 11, 22],+ })+ ).toBe(selected)+ })++ it('distributes workflow invocations across the configured senders', () => {+ const counts = new Map<number, number>([+ [11, 0],+ [22, 0],+ [33, 0],+ ])++ for (let index = 0; index < 900; index++) {+ const selected = selectEmailSenderIntegrationId(`invocation-${index}`, {+ integrationId: 11,+ integrationIds: [11, 22, 33],+ })+ counts.set(selected, (counts.get(selected) ?? 0) + 1)+ }++ for (const count of counts.values()) {+ expect(count).toBeGreaterThan(250)+ expect(count).toBeLessThan(350)+ }+ })+})diff --git a/nodejs/src/cdp/services/messaging/email-sender-selection.ts b/nodejs/src/cdp/services/messaging/email-sender-selection.tsnew file mode 100644index 000000000000..d3131f1301c7--- /dev/null+++ b/nodejs/src/cdp/services/messaging/email-sender-selection.ts@@ -0,0 +1,20 @@+import { createHash } from 'crypto'++type EmailSenderConfiguration = {+ integrationId: number+ integrationIds?: number[]+}++export function selectEmailSenderIntegrationId(invocationId: string, sender: EmailSenderConfiguration): number {+ const configuredIds = sender.integrationIds?.length ? sender.integrationIds : [sender.integrationId]+ const integrationIds = [...new Set(configuredIds)].sort((a, b) => a - b)++ if (integrationIds.length === 1) {+ return integrationIds[0]+ }++ const hash = createHash('sha256')+ .update(`${invocationId}:${integrationIds.join(',')}`)+ .digest()+ return integrationIds[hash.readUInt32BE(0) % integrationIds.length]+}diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex ed75cb01392b..a3ef867c2c7c 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -250,6 +250,33 @@ describe('EmailService', () => {const result = await service.executeSendEmail(invocation)expect(result.error).toBeUndefined()})++ it('uses and logs the sender selected for this workflow invocation', async () => {+ await insertIntegration(hub.postgres, team.id, {+ id: 4,+ kind: 'email',+ config: {+ email: '[email protected]',+ name: 'Second Sender',+ domain: 'posthog.com',+ verified: true,+ provider: 'ses',+ },+ })+ invocation.id = 'invocation-0'+ invocation.queueParameters = createEmailParams({+ from: { integrationId: 1, integrationIds: [1, 4] },+ })++ const result = await service.executeSendEmail(invocation)++ expect(result.error).toBeUndefined()+ const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }+ expect(sentCommand.input.FromEmailAddress).toBe('"Second Sender" <[email protected]>')+ expect(result.logs.map((log) => log.message)).toContain(+ 'Email sent to [email protected] from Second Sender <[email protected]>'+ )+ })})describe('from overrides', () => {it.each<[string, { email?: string; name?: string }, string, string]>([diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 3b54feff8504..edbe778c480d 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -18,6 +18,7 @@ import { logger } from '~/common/utils/logger'import { IntegrationManagerService } from '../managers/integration-manager.service'import { RecipientManagerRecipient, RecipientsManagerService } from '../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'+import { selectEmailSenderIntegrationId } from './email-sender-selection'import { EmailSuppressionService } from './email-suppression.service'import { addTrackingToEmail, resolveEmailEngagementDistinctId } from './email-tracking.service'import { mailDevTransport, mailDevWebUrl } from './helpers/maildev'@@ -188,7 +189,8 @@ export class EmailService {const addLog = createAddLogFunction(result.logs)const params = invocation.queueParameters- const integration = await this.integrationManager.get(params.from.integrationId)+ const integrationId = selectEmailSenderIntegrationId(invocation.id, params.from)+ const integration = await this.integrationManager.get(integrationId)let success: boolean = falselet throttled: boolean = false@@ -275,7 +277,7 @@ export class EmailService {assetRow = this.messageAssetsService.buildRowForEmail(invocation, params)}const viewEmailToken = assetRow ? ` [Email:${invocation.id}:${invocation.state.actionId ?? ''}]` : ''- addLog('info', `Email sent to ${params.to.email}${viewEmailToken}`)+ addLog('info', `Email sent to ${params.to.email} from ${from.name} <${from.email}>${viewEmailToken}`)success = true} catch (error) {if (error instanceof SESThrottleError) {diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex edae306c55b0..c67e07c05b5a 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -5305,6 +5305,20 @@ class TestIntegrationDeletionWorkflowGuard:assert "Welcome Email Sequence" in response.content.decode()assert Integration.objects.filter(id=self.integration.id).exists()+ def test_destroy_blocked_when_active_workflow_sender_rotation_references_integration(self, client: HttpClient):+ actions = self._email_actions(self.integration.id + 1)+ actions[1]["config"]["inputs"]["email"]["value"]["from"]["integrationIds"] = [+ self.integration.id + 1,+ self.integration.id,+ ]+ self._create_flow(actions=actions)++ response = self._delete(client)++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Welcome Email Sequence" in response.content.decode()+ assert Integration.objects.filter(id=self.integration.id).exists()+@pytest.mark.parametrize("flow_status", ["draft", "archived"])def test_destroy_allowed_when_workflow_not_active(self, flow_status: str, client: HttpClient):self._create_flow(status=flow_status)diff --git a/posthog/cdp/test/test_validation.py b/posthog/cdp/test/test_validation.pyindex 9f21d11a4e0c..7ec16176e1a3 100644--- a/posthog/cdp/test/test_validation.py+++ b/posthog/cdp/test/test_validation.py@@ -538,6 +538,19 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingT"name": "Community",}+ def test_email_sender_rotation_rejects_more_than_ten_senders(self):+ inputs_schema = [{"key": "email", "type": "native_email", "required": True, "templating": "liquid"}]+ value = {+ "from": {"integrationId": 1, "integrationIds": list(range(1, 12))},+ "to": "[email protected]",+ "subject": "hi",+ "text": "hi",+ }++ with pytest.raises(ValidationError) as ctx:+ validate_inputs(inputs_schema, {"email": {"value": value}})+ assert "At most 10 email senders are allowed." in str(ctx.value.detail)+@parameterized.expand([("person", "{person?.id}"),diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.pyindex 5d664947557d..055e8e7db481 100644--- a/posthog/cdp/validation.py+++ b/posthog/cdp/validation.py@@ -28,6 +28,7 @@ logger = logging.getLogger(__name__)CORE_SUPPORTED_FUNCTIONS = {"fetch", "postHogCapture"}+MAX_WORKFLOW_EMAIL_SENDERS = 10PRODUCT_ASYNC_FUNCTIONS: set[str] = set()@@ -485,6 +486,24 @@ class InputsItemSerializer(serializers.Serializer):{"input": f"Expected string {label} for {', '.join(wrong_types)}."})+ integration_ids = from_value.get("integrationIds")+ if integration_ids is not None:+ if not isinstance(integration_ids, list):+ raise serializers.ValidationError(+ {"input": "Expected 'from.integrationIds' to be a list of Integration IDs."}+ )+ if len(integration_ids) > MAX_WORKFLOW_EMAIL_SENDERS:+ raise serializers.ValidationError(+ {"input": f"At most {MAX_WORKFLOW_EMAIL_SENDERS} email senders are allowed."}+ )+ if not all(+ isinstance(integration_id, int) and not isinstance(integration_id, bool)+ for integration_id in integration_ids+ ):+ raise serializers.ValidationError(+ {"input": "Expected 'from.integrationIds' to be a list of Integration IDs."}+ )+if isinstance(value.get("html"), str) and value["html"] and not value.get("design"):# Programmatically authored emails often supply html without a design, which the# visual editor can't open. Wrap it so every stored email has an editable design.diff --git a/products/workflows/backend/services/integration_usage.py b/products/workflows/backend/services/integration_usage.pyindex 72cf05e5c1ae..43c616597ea2 100644--- a/products/workflows/backend/services/integration_usage.py+++ b/products/workflows/backend/services/integration_usage.py@@ -17,6 +17,9 @@ def _node_references_integration(node: Any, integration_id: int, depth: int = 0)value = node.get("integrationId")if value is not None and str(value) == str(integration_id):return True+ values = node.get("integrationIds")+ if isinstance(values, list) and any(str(value) == str(integration_id) for value in values):+ return Truereturn any(_node_references_integration(child, integration_id, depth + 1) for child in node.values())if isinstance(node, list):return any(_node_references_integration(item, integration_id, depth + 1) for item in node)diff --git a/products/workflows/frontend/Workflows/workflowLogic.emailValidation.test.ts b/products/workflows/frontend/Workflows/workflowLogic.emailValidation.test.tsindex aca184f45e45..9b4472329f01 100644--- a/products/workflows/frontend/Workflows/workflowLogic.emailValidation.test.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.emailValidation.test.ts@@ -204,14 +204,20 @@ describe('workflowLogic email step "from" validation', () => {expect(result?.errors.email).toBeUndefined()})- it('does not flag a "from" error when a sender is picked, including valid templated overrides', async () => {+ it.each([+ [+ 'one sender with valid templated overrides',+ {+ integrationId: 42,+ email: '{{ event.properties.sender_email }}',+ name: 'Community team',+ },+ ],+ ['a sender rotation', { integrationId: 42, integrationIds: [42, 43, 44] }],+ ])('does not flag a "from" error when %s has been picked', async (_name, fromValue) => {useMocks({get: {- '/api/environments/:team_id/hog_flows/:id/': makeWorkflow({- integrationId: 42,- email: '{{ event.properties.sender_email }}',- name: 'Community team',- }),+ '/api/environments/:team_id/hog_flows/:id/': makeWorkflow(fromValue),'/api/projects/:team_id/hog_function_templates/': hangingTemplatesEndpoint,},})diff --git a/products/workflows/frontend/generated/agentContext.ts b/products/workflows/frontend/generated/agentContext.tsindex 79b56ec4a48b..d9f956a7d70b 100644--- a/products/workflows/frontend/generated/agentContext.ts+++ b/products/workflows/frontend/generated/agentContext.ts@@ -178,7 +178,7 @@ export const BUILDING_WORKFLOWS_SKILL: EmbeddedSkill = {description:'Build, edit, test, enable, and monitor PostHog workflows over MCP. Author the action/edge graph so it runs and opens cleanly in the visual editor, then change drafts surgically with patch operations. Use when asked to build, set up, automate, change, fix, or debug a workflow, campaign, broadcast, drip sequence, or event-triggered automation in the workflows product.',content:- '# Building workflows\n\nA PostHog **workflow** is a directed graph: a list of **action nodes** (`actions`) wired by **edges** (`edges`), with exactly one `trigger` node that starts every run. You author that graph as JSON and ship it over MCP. Always call it a "workflow" to the user. "Hog flow" is the internal code name (`HogFlow`), not a user-facing term.\n\nThe single biggest failure mode is **getting the graph JSON structurally wrong**. The backend stores `actions`/`config` as loose JSON, but the visual editor parses every node against a strict schema, so a malformed node saves but then **breaks the editor view** for the whole workflow. Before composing or editing any graph, read [references/graph-schema.md](references/graph-schema.md). It is the contract; do not improvise node shapes from these examples alone.\n\n## The lifecycle\n\nWork the workflow through these stages. Don\'t jump straight to enabling it.\n\n1. **Compose the graph.** Build `actions` + `edges` per [references/graph-schema.md](references/graph-schema.md). For any `function` node, don\'t guess the template: list the live catalog with `cdp-function-templates-list` and read its required inputs with `cdp-function-templates-retrieve`.\n2. **Create as a draft.** `workflows-create`. Every workflow is created `draft`; it does not execute yet.\n3. **Test-run it.** `workflows-test-run` runs **one step at a time**. Start at the first step (omit `current_action_id`, or point it at the trigger) with sample `globals` (`{event, person, groups}`); the result includes the next step\'s id (`nextActionId`). Feed that back as `current_action_id` and run again, walking step by step to the end. Skip `delay` nodes by jumping to the action after them (delays aren\'t simulated). Async side effects (HTTP/email/SMS/push) are mocked unless you set `mock_async_functions=false`. Read each step\'s trace to confirm the path taken.\n4. **Read logs while iterating.** `workflows-logs` shows the per-step execution trace (levels DEBUG to ERROR). This is how you see _why_ a step skipped, branched, or errored.\n5. **Edit, then re-test.** Patch the graph with `workflows-patch-graph` (see [Editing a draft](#editing-a-draft)). **Every edit invalidates your earlier test** — re-run the affected path before moving on. On a draft workflow, edits apply directly; on an active one they stage a draft (see [Changing a live workflow](#changing-a-live-workflow)).\n6. **Enable (needs the user\'s explicit sign-off).** `workflows-enable` flips it to `active` and an **event/webhook/manual** trigger starts firing on matching activity. From then on it runs on real people, and every change goes through the draft → test → publish cycle before taking effect — so finish testing, then get the user\'s explicit go before enabling. Don\'t enable on your own initiative.\n7. **Dispatch (batch/schedule only).** A `batch` workflow does **not** fire on enable alone. Send a one-off broadcast with `workflows-run-batch`, or attach a recurring schedule with `workflows-schedule-create`. Confirm with `workflows-get` that `status==\'active\'` _and_ its read-only `schedules` field has an active entry.\n8. **Monitor.** Drill down: `workflows-global-stats` (which workflows are failing) to `workflows-stats` (one workflow\'s trend) to `workflows-list-invocations` (who it failed for) to `workflows-get-invocation` (the triggering payload) to `workflows-logs` (the failing step).\n\nFull tool catalog, grouped by job: [references/lifecycle-and-debugging.md](references/lifecycle-and-debugging.md).\n\n## Editing a draft\n\n**Patch, don\'t replace.** Edit a draft with `workflows-patch-graph`: a small, ordered list of id-addressed operations (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`). `update_action` deep-merges its patch, so changing one email subject is a few lines, not the whole graph. The ops apply atomically server-side (read, apply in order, validate, save only if valid), and the response echoes the **full updated graph**, so you never re-fetch before the next edit. This keeps each round-trip tiny instead of re-transmitting every action and edge.\n\n`workflows-update` covers only what a graph patch can\'t express: top-level fields like name, description, exit_condition, conversion, trigger_masking, and variables. It rejects `actions`/`edges` outright - a partial list would silently drop every step it omits - so every graph change goes through `workflows-patch-graph`.\n\nAfter **any** patch, re-test the path you changed (step 3). A patch that validates structurally can still route the wrong way.\n\nEmail content follows the same rule.\nThe email inside a `function_email` step is edited with **`workflows-patch-action-email`**: the same id-addressed design ops as the template patch, plus an `email_patch` merge for subject/preheader/text/recipients, with the HTML re-rendered server-side so it always matches the design.\nPrefer it over `workflows-patch-graph` `update_action` for email content - an `update_action` that changes `design` leaves the stored `html` stale.\nLibrary templates are edited with **`workflows-patch-email-template`**, not `workflows-update-email-template` (which resends the entire design JSON).\nCompose and edit email designs with the **`designing-email-templates`** skill.\n\n## Changing a live workflow\n\nEditing an active workflow stages a **draft** instead of changing what\'s running: nothing reaches real people until you publish. Work the cycle:\n\n1. **Edit.** `workflows-patch-graph` (or `workflows-update` for content fields) on the active workflow writes to its draft — the first edit copies the live graph into the draft, later edits compose onto it. `workflows-get` shows the staged draft in `draft`; the live config stays in `actions`/`edges`. Metadata (name, description) applies live immediately.\n2. **Test the draft.** `workflows-test-run` with `use_draft=true` executes the staged draft instead of the live config. Re-test every path you changed.\n3. **Publish deliberately.** `workflows-publish` without `confirm` returns `in_flight_runs`, a `confirm_token`, and an `impact` summary: per deleted step, about how many people are parked there and whether they move to a surviving step (`moves_to`) or exit; `empty_variables` that may render empty for people already past their new producer when they reach a reference (a structural warning — it can fire even when everyone in-flight is still upstream of the producer); `schedule_conflicts` where a schedule overrides a variable the draft removes. **Echo the impact to the user and get their go-ahead**, then call again with `confirm=true` and that `confirm_token`. A 409 means the draft changed since the preview and a 400 means the token expired (15 minutes) — preview again and re-confirm either way. Publish revalidates everything, so an invalid draft is rejected and live config stays untouched.\n4. **Or bail.** `workflows-discard-draft` throws the staged draft away.\n\nIn-flight runs follow the live config: once published, people mid-flow continue from their current step on the new version. Steps they already passed don\'t re-run; people parked on a step the publish deletes skip forward to its next surviving step (or exit at a dead end), exactly as the impact preview reported.\n\nTiming edits apply to parked runs gradually, not instantly. Publishing a shortened delay (or a moved wait window) reschedules the runs parked on it via a rate-limited sweep. Runs already due to wake soon keep their original earlier wake untouched; only wakes that the sweep moves earlier are affected, and those land spread out, no sooner than a few minutes after publish (and never later than their original wake). Runs still parked shortly after publishing are expected - tell the user this rather than re-publishing or treating it as a failure.\n\n### Rolling back\n\nEvery live-content change appends a snapshot to the workflow\'s revision history. `workflows-list-revisions` lists versions (newest first); `workflows-get-revision` returns one version\'s full content. To roll back (or forward), `workflows-restore-revision` copies that version\'s content into the draft — it never touches the live config — then the normal publish cycle applies: test with `use_draft=true`, preview, confirm. The preview shows exactly what the rollback does to people in-flight, same as any publish.\n\nA restore returns 409 when a draft is already open; publish or discard it, or pass `overwrite=true` to replace it. Two things a rollback cannot undo: runs that already moved or exited while the newer version was live keep their positions (their side effects happened), and a publish that shortened a delay may have pulled parked wake times earlier — rolling back doesn\'t push them later again.\n\n## What the server owns, never send it\n\nThe server compiles and manages these. Authoring them by hand is the fastest way to a broken workflow:\n\n- **`bytecode`** on any filter, trigger, condition, conversion, or masking. Compiled server-side from the human-readable `properties`/`hash`. Omit it; send `filters: {...}`, not bytecode.\n- **`trigger`** (top-level). _Derived_ from the `trigger` action in `actions`. Read-only. Set the trigger by adding the trigger node, not by setting this field.\n- **`billable_action_types`**, `version`, `id`, `created_*`. Computed/managed.\n\n## Minimal worked example\n\nEvent trigger, wait 1 day, send email, exit. Note: exactly one `trigger`, every non-exit node has an outgoing edge, ids are referenced consistently by `edges`, and no `bytecode` is sent.\n\n```json\n{\n "name": "Nudge after signup",\n "description": "One day after signup, send a reminder.",\n "exit_condition": "exit_only_at_end",\n "actions": [\n {\n "id": "trigger_node",\n "name": "Signed up",\n "type": "trigger",\n "config": {\n "type": "event",\n "filters": { "events": [{ "id": "user signed up", "name": "user signed up", "type": "events", "order": 0 }] }\n }\n },\n {\n "id": "delay_1",\n "name": "Wait 1 day",\n "type": "delay",\n "config": { "delay_duration": "1d" }\n },\n {\n "id": "email_1",\n "name": "Reminder email",\n "type": "function_email",\n "config": {\n "template_id": "template-email",\n "template_uuid": "<uuid returned by workflows-create-email-template>",\n "message_category_type": "marketing",\n "inputs": {\n "email": {\n "value": {\n "to": { "email": "{person.properties.email}", "name": "" },\n "from": { "email": "[email protected]", "name": "Example" }\n }\n }\n }\n }\n },\n {\n "id": "exit_node",\n "name": "Exit",\n "type": "exit",\n "config": { "reason": "Done" }\n }\n ],\n "edges": [\n { "from": "trigger_node", "to": "delay_1", "type": "continue" },\n { "from": "delay_1", "to": "email_1", "type": "continue" },\n { "from": "email_1", "to": "exit_node", "type": "continue" }\n ]\n}\n```\n\nEmail bodies come from the template library, not hand-written html:\n\n1. **Reuse first.** List the library with `workflows-list-email-templates` and pick a template that fits. A drip campaign typically references one base template (say, a branded announcement) from every email step.\n2. **Create only if nothing fits.** Author a new template design-first with the **`designing-email-templates`** skill: compose the `design`, omit `html` (the server renders html from the design).\n3. **Reference it** by putting the template\'s UUID in each step\'s `config.template_uuid`, as above. The save snapshots the template\'s subject, text, html, and design into the step.\n4. **Differentiate per step** with `workflows-patch-action-email` design operations - each step\'s snapshot is edited independently, so five steps from one base template can each carry their own content.\n\nThe snapshot is one-way: editing the library template later does not change steps that already referenced it, and patching a step never touches the library template. If a user expects a template edit to flow into their workflows, correct that - the steps keep their copies, and each one is updated with `workflows-patch-action-email`.\n\nAlways give templates a real plain-text `text` alongside the design: clients that block rich content show only `text`, so filler like "placeholder" reaches real inboxes.\n\n## Hard rules to surface to the user, not work around\n\n- **Behavioral targeting is unsupported.** "Did event X at least N times over the last M days" can\'t be expressed as a trigger or a batch/schedule audience. If asked, reject it and explain; don\'t approximate it with a broken filter. (The backend rejects behavioral cohorts in batch audiences outright.)\n- **Batch audiences target _who a person is_, not what they did.** Person properties and/or static/property-based cohorts only. Event/action filters in a batch audience are silently dropped, so they\'re rejected.\n- **Prefer re-evaluating audiences.** For batch, inline person-property conditions or a dynamic (filter-based) cohort re-evaluate as people qualify; a static cohort is a frozen list, use only for an explicit given set.\n\n# Workflow graph schema\n\nThe contract for `actions` and `edges`. The stored workflow is loose JSON, but **the visual editor validates every node against a strict schema keyed on `type`**. A node that saves successfully but doesn\'t match this contract will **break the editor view for the whole workflow** when someone opens it. Treat the shapes below as required, not advisory.\n\n## Contents\n\n- Node (action) shape\n- Action types and their `config`\n- Edges\n- `function*` inputs\n- Duration strings (`delay_duration`, `max_wait_duration`)\n- Conversion & exit condition\n- Pre-submit checklist\n\n## Node (action) shape\n\nEvery action object has these common fields plus a type-specific `config`:\n\n```json\n{\n "id": "unique_within_workflow",\n "name": "Human label",\n "description": "",\n "type": "<see action types>",\n "config": {},\n "on_error": "continue",\n "filters": null,\n "output_variable": null\n}\n```\n\n- `id` — unique within the workflow; edges reference it by `from`/`to`.\n- `on_error` — optional; **only `continue` or `abort`.** Omit to use the default.\n- `filters` — optional property filters gating the action: `{properties: [<cond>]}`. Send `properties`, not `bytecode`.\n- `output_variable` — optional; store a step result into a workflow variable. `{key, result_path?, spread?}`.\n\n## Action types and their `config`\n\nUse **only** these `type` values — they are the complete supported set. An unknown or unsupported `type` breaks the editor\'s parse for the entire graph.\n\n| `type` | `config` |\n| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |\n| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |\n| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |\n| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |\n| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |\n| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |\n| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don\'t guess the id or its inputs — discover them live (see below). |\n| `function_email` | `{ "template_id?": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email`; omit it and the server infers it from the step type. Reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id` — a UUID sent as `template_id` is moved into `template_uuid` automatically. When `template_uuid` is set and the value has no body keys (`subject`/`text`/`html`/`design`), the server copies the template\'s body into `inputs.email.value` at save (a snapshot — later template edits don\'t propagate); you still supply `from` and `to`. If you author any body key inline, your body wins and `template_uuid` is provenance only. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |\n| `function_sms` | `{ "template_id?": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`; omit it and the server infers it. |\n| `function_push` | `{ "template_id?": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`; omit it and the server infers it. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email\'s — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project\'s push integration ids for `channels`. |\n| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |\n\n### Branch and wait condition filters (the `filters` wrapper is mandatory)\n\n`conditional_branch` and `wait_until_condition` gate on a **`filters` object**, the action-filter shape (`{properties?, events?, actions?, source?, filter_test_accounts?}`). The wrapper is not optional:\n\n- Write `{ "filters": { "properties": [<cond>] } }` on each condition, **never** `{ "properties": [<cond>] }` directly on the condition object. The bare form saves but the visual editor flags it and the branch compiles to a constant, so it never evaluates your condition.\n- `conditional_branch` conditions are **property-only** (person/group `<cond>`s). Event/action filters are rejected here ("Event filters are not allowed in conditionals").\n- `wait_until_condition` is event-aware: its `condition.filters` and each `events?[].filters` may also carry `events`/`actions`. An entry naming neither an event nor an action is dropped (it would match everything).\n- `source` is optional (defaults to `events`). Never send `bytecode`; the server compiles it from `properties`.\n\n### Trigger `config` (the `trigger` node)\n\nDiscriminated on `config.type`:\n\n- `event` — `{ "type": "event", "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events", "order": 0, "properties": [<cond>] }], "properties": [<cond>], "filter_test_accounts": false } }`. Fires on **every** matching occurrence. Throttle repeats with `trigger_masking` (dedup/sampling — not behavioral filtering).\n- `webhook` / `manual` / `tracking_pixel` — `{ "type": "webhook", "template_id": "<literal>", "inputs": { ... } }`. These use a **fixed built-in source template**, not one you look up: `template-source-webhook` for both `webhook` and `manual`, `template-source-webhook-pixel` for `tracking_pixel`. Omitting or guessing it fails the create with `Template not found` against the trigger node. They are `source_webhook` templates and are **not** in the destination catalog (`cdp-function-templates-list` is `type=destination`), so don\'t try to discover them there. Each needs `inputs.event` and `inputs.distinct_id` wrapped in `{value: ...}`, and the right values **differ per trigger type** because a different request reaches the template:\n - `webhook` — a POST whose body you control: `"inputs": { "event": { "value": "{request.body.event}" }, "distinct_id": { "value": "{request.body.distinct_id}" } }`.\n - `manual` — the "trigger manually" button POSTs `{user_id, $variables}`, so the body carries no `event`: use the fixed literal `"inputs": { "event": { "value": "$workflow_triggered" }, "distinct_id": { "value": "{request.body.user_id}" } }`. Pointing `event` at `{request.body.event}` here makes every manual run return 400 (the source template rejects an empty `event`) while the UI still shows a success toast, so the workflow silently never fires.\n - `tracking_pixel` — a bodyless `GET`, so read query params: `"inputs": { "event": { "value": "{request.query.ph_event}" }, "distinct_id": { "value": "{request.query.ph_distinct_id}" } }`. Body references resolve empty here and the pixel still returns its 200 GIF, so every hit is dropped with no error to retry on.\n- `batch` — `{ "type": "batch", "filters": { "properties": [<cond>] } }`. The audience: person-property conditions and/or cohort references. **No event/action filters** (silently dropped, so rejected). Does not fire on enable — dispatch a one-off broadcast with `workflows-run-batch`, or make it **recurring** with `workflows-schedule-create` (attaches an RRULE schedule; each firing re-broadcasts to this same `config.filters.properties` audience). A recurring workflow is a `batch` trigger plus a schedule — there is no separate "schedule" trigger type to author.\n\n### Trigger masking (throttling an event trigger)\n\n`trigger_masking` is a top-level workflow field (not an action) that throttles an already-matching `event` trigger — it dedups/samples firings, it does not decide who enters.\n\n```json\n"trigger_masking": { "hash": "{person.id}", "ttl": 3600, "threshold": null }\n```\n\n- `hash` — HogQL template defining the dedup key. `"{person.id}"` = once per person.\n- `ttl` — seconds to suppress repeats of the same hash (60–94608000).\n- `threshold?` — fire once per N matches of the same hash (a sampler: N=3 fires on the 1st, 4th, 7th…). Omit to fire once then suppress within `ttl`.\n- Don\'t send `bytecode` — compiled server-side from `hash`.\n\n### Condition shape (`<cond>`)\n\nProperty conditions used in trigger/action `filters`, branch conditions, and conversion:\n\n```json\n{ "key": "plan", "value": ["pro"], "operator": "exact", "type": "person" }\n```\n\n`type` is `event` | `person` | `group`. Never include `bytecode` — the server compiles it.\n\n## Edges\n\n```json\n{ "from": "source_id", "to": "target_id", "type": "continue", "index": 0 }\n```\n\n- `type: "continue"` — fall-through: the sequential next step, or the **no-match** path out of a `conditional_branch`. For a `wait_until_condition` it is the **`max_wait_duration` timeout** path.\n- `type: "branch"` — requires `index`, matching `config.conditions[index]` on a `conditional_branch`. A `wait_until_condition` **resolves** (its `condition` matches or an `events` entry fires) out the `branch` edge at **`index: 0`**.\n- **Every non-exit node needs a reachable next action** via an outgoing edge, or execution fails with "No next action found".\n- A `conditional_branch` with N conditions typically has N `branch` edges (`index: 0..N-1`) plus one `continue` edge for the no-match path.\n- A `wait_until_condition` needs a `branch` edge at `index: 0` (resolution) **and** a `continue` edge (timeout). Without the `index: 0` branch it only ever advances on timeout, never on the event/condition firing.\n\n## `function*` inputs\n\nInputs are keyed by the template\'s input schema, each wrapped in `{value: ...}`:\n\n```json\n"inputs": { "url": { "value": "https://example.com/hook" } }\n```\n\n- **Wrap values in `{value: ...}`.** A flat string won\'t enable templating.\n- Templating uses **single-curly** `{person.x}` / `{event.x}` inside the value string. Liquid-style `{{ ... }}` is rejected on hog-templated fields ("Placeholders are not allowed in this context") — the only fields that accept Liquid are ones whose input schema declares `templating: liquid` (the email input on `function_email` does; most others don\'t).\n- **Dictionary input values are template strings too** — write booleans/numbers as single-expression templates: `"{true}"`, `"{42}"`, which evaluate to the typed value.\n- Required inputs must be present, or create fails with "This field is required".\n\n### Discovering function templates (do this, don\'t guess)\n\nThe set of available `function` templates and their required inputs is **live data**, not something to hardcode — it changes as integrations are added. For a `function` node:\n\n1. `cdp-function-templates-list` (filter `type=destination`) to find the right template and its `id`.\n2. `cdp-function-templates-retrieve` with that id to read its **`inputs_schema`** — the exact keys, types, and which are required.\n3. Build `inputs` from that schema. A `template_id` not in the live list fails with "Template not found".\n\n`function_email`, `function_sms`, and `function_push` are the exception — their `template_id` is the fixed literal `template-email` / `template-twilio` / `template-native-push`, so you don\'t look the `template_id` up, and you can omit it entirely: the server infers the literal from the step type. A saved email template\'s UUID goes in `template_uuid` alongside the literal, never in `template_id` (a UUID sent as `template_id` is moved into `template_uuid` automatically). For `function_email`, referencing a template means you only author `from`/`to`: the server materializes the template\'s body at save (see the action-types table). `function_push` still has variable `inputs` (notably `channels`), so retrieve its `inputs_schema` even though the id is fixed.\n\n### `function_push` worked example\n\nRetrieve `template-native-push` with `cdp-function-templates-retrieve` for the full `inputs_schema` (it has many optional Android/iOS keys), but the core shape is:\n\n```json\n{\n "id": "push_1",\n "name": "Re-engagement push",\n "type": "function_push",\n "config": {\n "template_id": "template-native-push",\n "inputs": {\n "distinctId": { "value": "{event.distinct_id}" },\n "channels": { "value": [6, 7] },\n "title": { "value": "Notification from {event.event}" },\n "body": { "value": "Hi {{ person.properties.first_name }}, come finish setting up.", "templating": "liquid" }\n }\n }\n}\n```\n\n- **`channels`** is an `integration_multi` input: its `value` is an array of **integration id numbers** (e.g. `[6, 7]`), not objects. Find the FCM/APNs integration ids with `integrations-list` (look for `kind` `firebase` / `apns`); at least one is required or the send throws "No push channel configured".\n- **Templating differs per input.** `body` is **liquid** — interpolate with `{{ person.x }}` / `{{ event.x }}` (double braces) and set `"templating": "liquid"`. `title` and the other string inputs are **hog** — use `{event.x}` / `{person.x}` (single braces). The wrong brace style leaves the expression as a literal.\n- Required: `distinctId`, `channels`, `title`. Optional: `body`, `image`, `data`, `ttlSeconds`, `android_*`, `ios_*` (retrieve the `inputs_schema` for the full set).\n- Never hand-author `bytecode` — the server compiles it from `value`. Omit `order` too: the editor lays fields out in the template\'s `inputs_schema` order (fixed and consistent), not by the `order` on your inputs, so leaving it off doesn\'t change the form. Push has no delivered/opened/clicked signal (FCM/APNs respond synchronously), so a successful send means "accepted for delivery", nothing more.\n\n## Duration strings (`delay_duration`, `max_wait_duration`)\n\nMust match `^\\d*\\.?\\d+[dhms]$` — a number plus unit `s` | `m` | `h` | `d`. Examples: `30s`, `30m`, `2h`, `1d`, `1.5d` (=36h).\n\n- **No ISO-8601.** Fractions are allowed in every unit.\n- Per-unit caps are **silently clamped**: `s`≤60, `m`≤60, `h`≤24, `d`≤30. Max total 30d. Use the larger unit (`90m` → use `1.5h`) to avoid surprise clamping.\n\n## Conversion & exit condition\n\n- `exit_condition`: `exit_only_at_end` (default), `exit_on_conversion`, `exit_on_trigger_not_matched`, `exit_on_trigger_not_matched_or_conversion`.\n- The `…conversion` variants require a `conversion` goal with two slots plus a window:\n - `filters` — **property conditions only**, an array `[{key, value, operator, type}, ...]` (empty array = any event in the window converts).\n - `events` — **event-based goals**, `[{ "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events" }] } }]`.\n - `window_minutes` — minutes after entry (`null` = no window).\n- **An event goal goes in `events`, never in `filters`.** An event object stuffed into `filters` is invisible to the conversion matcher and breaks the conversion picker. Without a goal the `…conversion` exit is a silent no-op. Server compiles the bytecode.\n\n## Pre-submit checklist\n\n- [ ] Exactly **one** `type: "trigger"` action; usually exactly one `exit`.\n- [ ] Every action `type` and `config` matches a row above (no types outside the supported set).\n- [ ] `on_error` is only `continue` or `abort`.\n- [ ] `function_email.template_id == "template-email"`, `function_sms.template_id == "template-twilio"`, `function_push.template_id == "template-native-push"`.\n- [ ] A `webhook` / `manual` trigger sets `template_id == "template-source-webhook"` (a `tracking_pixel` uses `"template-source-webhook-pixel"`) — these are built-in source templates, not catalog lookups.\n- [ ] That trigger\'s `inputs.event` / `inputs.distinct_id` match its own type: `{request.body.*}` for `webhook`, `$workflow_triggered` + `{request.body.user_id}` for `manual`, `{request.query.ph_*}` for `tracking_pixel`. The wrong pair saves fine and then fails at trigger time.\n- [ ] Every non-exit node has an outgoing edge; `branch` edges have an `index` matching a condition.\n- [ ] Every `conditional_branch` / `wait_until_condition` condition is wrapped: `{filters: {properties: [...]}}`, not `{properties: [...]}`.\n- [ ] All durations match `^\\d*\\.?\\d+[dhms]$` and dodge the silent per-unit clamp.\n- [ ] Function inputs are `{key: {value: ...}}`; no hand-written `bytecode` anywhere; no top-level `trigger` field set.',+ '# Building workflows\n\nA PostHog **workflow** is a directed graph: a list of **action nodes** (`actions`) wired by **edges** (`edges`), with exactly one `trigger` node that starts every run. You author that graph as JSON and ship it over MCP. Always call it a "workflow" to the user. "Hog flow" is the internal code name (`HogFlow`), not a user-facing term.\n\nThe single biggest failure mode is **getting the graph JSON structurally wrong**. The backend stores `actions`/`config` as loose JSON, but the visual editor parses every node against a strict schema, so a malformed node saves but then **breaks the editor view** for the whole workflow. Before composing or editing any graph, read [references/graph-schema.md](references/graph-schema.md). It is the contract; do not improvise node shapes from these examples alone.\n\n## The lifecycle\n\nWork the workflow through these stages. Don\'t jump straight to enabling it.\n\n1. **Compose the graph.** Build `actions` + `edges` per [references/graph-schema.md](references/graph-schema.md). For any `function` node, don\'t guess the template: list the live catalog with `cdp-function-templates-list` and read its required inputs with `cdp-function-templates-retrieve`.\n2. **Create as a draft.** `workflows-create`. Every workflow is created `draft`; it does not execute yet.\n3. **Test-run it.** `workflows-test-run` runs **one step at a time**. Start at the first step (omit `current_action_id`, or point it at the trigger) with sample `globals` (`{event, person, groups}`); the result includes the next step\'s id (`nextActionId`). Feed that back as `current_action_id` and run again, walking step by step to the end. Skip `delay` nodes by jumping to the action after them (delays aren\'t simulated). Async side effects (HTTP/email/SMS/push) are mocked unless you set `mock_async_functions=false`. Read each step\'s trace to confirm the path taken.\n4. **Read logs while iterating.** `workflows-logs` shows the per-step execution trace (levels DEBUG to ERROR). This is how you see _why_ a step skipped, branched, or errored.\n5. **Edit, then re-test.** Patch the graph with `workflows-patch-graph` (see [Editing a draft](#editing-a-draft)). **Every edit invalidates your earlier test** — re-run the affected path before moving on. On a draft workflow, edits apply directly; on an active one they stage a draft (see [Changing a live workflow](#changing-a-live-workflow)).\n6. **Enable (needs the user\'s explicit sign-off).** `workflows-enable` flips it to `active` and an **event/webhook/manual** trigger starts firing on matching activity. From then on it runs on real people, and every change goes through the draft → test → publish cycle before taking effect — so finish testing, then get the user\'s explicit go before enabling. Don\'t enable on your own initiative.\n7. **Dispatch (batch/schedule only).** A `batch` workflow does **not** fire on enable alone. Send a one-off broadcast with `workflows-run-batch`, or attach a recurring schedule with `workflows-schedule-create`. Confirm with `workflows-get` that `status==\'active\'` _and_ its read-only `schedules` field has an active entry.\n8. **Monitor.** Drill down: `workflows-global-stats` (which workflows are failing) to `workflows-stats` (one workflow\'s trend) to `workflows-list-invocations` (who it failed for) to `workflows-get-invocation` (the triggering payload) to `workflows-logs` (the failing step).\n\nFull tool catalog, grouped by job: [references/lifecycle-and-debugging.md](references/lifecycle-and-debugging.md).\n\n## Editing a draft\n\n**Patch, don\'t replace.** Edit a draft with `workflows-patch-graph`: a small, ordered list of id-addressed operations (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`). `update_action` deep-merges its patch, so changing one email subject is a few lines, not the whole graph. The ops apply atomically server-side (read, apply in order, validate, save only if valid), and the response echoes the **full updated graph**, so you never re-fetch before the next edit. This keeps each round-trip tiny instead of re-transmitting every action and edge.\n\n`workflows-update` covers only what a graph patch can\'t express: top-level fields like name, description, exit_condition, conversion, trigger_masking, and variables. It rejects `actions`/`edges` outright - a partial list would silently drop every step it omits - so every graph change goes through `workflows-patch-graph`.\n\nAfter **any** patch, re-test the path you changed (step 3). A patch that validates structurally can still route the wrong way.\n\nEmail content follows the same rule.\nThe email inside a `function_email` step is edited with **`workflows-patch-action-email`**: the same id-addressed design ops as the template patch, plus an `email_patch` merge for subject/preheader/text/recipients, with the HTML re-rendered server-side so it always matches the design.\nPrefer it over `workflows-patch-graph` `update_action` for email content - an `update_action` that changes `design` leaves the stored `html` stale.\nLibrary templates are edited with **`workflows-patch-email-template`**, not `workflows-update-email-template` (which resends the entire design JSON).\nCompose and edit email designs with the **`designing-email-templates`** skill.\n\n## Changing a live workflow\n\nEditing an active workflow stages a **draft** instead of changing what\'s running: nothing reaches real people until you publish. Work the cycle:\n\n1. **Edit.** `workflows-patch-graph` (or `workflows-update` for content fields) on the active workflow writes to its draft — the first edit copies the live graph into the draft, later edits compose onto it. `workflows-get` shows the staged draft in `draft`; the live config stays in `actions`/`edges`. Metadata (name, description) applies live immediately.\n2. **Test the draft.** `workflows-test-run` with `use_draft=true` executes the staged draft instead of the live config. Re-test every path you changed.\n3. **Publish deliberately.** `workflows-publish` without `confirm` returns `in_flight_runs`, a `confirm_token`, and an `impact` summary: per deleted step, about how many people are parked there and whether they move to a surviving step (`moves_to`) or exit; `empty_variables` that may render empty for people already past their new producer when they reach a reference (a structural warning — it can fire even when everyone in-flight is still upstream of the producer); `schedule_conflicts` where a schedule overrides a variable the draft removes. **Echo the impact to the user and get their go-ahead**, then call again with `confirm=true` and that `confirm_token`. A 409 means the draft changed since the preview and a 400 means the token expired (15 minutes) — preview again and re-confirm either way. Publish revalidates everything, so an invalid draft is rejected and live config stays untouched.\n4. **Or bail.** `workflows-discard-draft` throws the staged draft away.\n\nIn-flight runs follow the live config: once published, people mid-flow continue from their current step on the new version. Steps they already passed don\'t re-run; people parked on a step the publish deletes skip forward to its next surviving step (or exit at a dead end), exactly as the impact preview reported.\n\nTiming edits apply to parked runs gradually, not instantly. Publishing a shortened delay (or a moved wait window) reschedules the runs parked on it via a rate-limited sweep. Runs already due to wake soon keep their original earlier wake untouched; only wakes that the sweep moves earlier are affected, and those land spread out, no sooner than a few minutes after publish (and never later than their original wake). Runs still parked shortly after publishing are expected - tell the user this rather than re-publishing or treating it as a failure.\n\n### Rolling back\n\nEvery live-content change appends a snapshot to the workflow\'s revision history. `workflows-list-revisions` lists versions (newest first); `workflows-get-revision` returns one version\'s full content. To roll back (or forward), `workflows-restore-revision` copies that version\'s content into the draft — it never touches the live config — then the normal publish cycle applies: test with `use_draft=true`, preview, confirm. The preview shows exactly what the rollback does to people in-flight, same as any publish.\n\nA restore returns 409 when a draft is already open; publish or discard it, or pass `overwrite=true` to replace it. Two things a rollback cannot undo: runs that already moved or exited while the newer version was live keep their positions (their side effects happened), and a publish that shortened a delay may have pulled parked wake times earlier — rolling back doesn\'t push them later again.\n\n## What the server owns, never send it\n\nThe server compiles and manages these. Authoring them by hand is the fastest way to a broken workflow:\n\n- **`bytecode`** on any filter, trigger, condition, conversion, or masking. Compiled server-side from the human-readable `properties`/`hash`. Omit it; send `filters: {...}`, not bytecode.\n- **`trigger`** (top-level). _Derived_ from the `trigger` action in `actions`. Read-only. Set the trigger by adding the trigger node, not by setting this field.\n- **`billable_action_types`**, `version`, `id`, `created_*`. Computed/managed.\n\n## Minimal worked example\n\nEvent trigger, wait 1 day, send email, exit. Note: exactly one `trigger`, every non-exit node has an outgoing edge, ids are referenced consistently by `edges`, and no `bytecode` is sent.\n\n```json\n{\n "name": "Nudge after signup",\n "description": "One day after signup, send a reminder.",\n "exit_condition": "exit_only_at_end",\n "actions": [\n {\n "id": "trigger_node",\n "name": "Signed up",\n "type": "trigger",\n "config": {\n "type": "event",\n "filters": { "events": [{ "id": "user signed up", "name": "user signed up", "type": "events", "order": 0 }] }\n }\n },\n {\n "id": "delay_1",\n "name": "Wait 1 day",\n "type": "delay",\n "config": { "delay_duration": "1d" }\n },\n {\n "id": "email_1",\n "name": "Reminder email",\n "type": "function_email",\n "config": {\n "template_id": "template-email",\n "template_uuid": "<uuid returned by workflows-create-email-template>",\n "message_category_type": "marketing",\n "inputs": {\n "email": {\n "value": {\n "to": { "email": "{person.properties.email}", "name": "" },\n "from": { "email": "[email protected]", "name": "Example" }\n }\n }\n }\n }\n },\n {\n "id": "exit_node",\n "name": "Exit",\n "type": "exit",\n "config": { "reason": "Done" }\n }\n ],\n "edges": [\n { "from": "trigger_node", "to": "delay_1", "type": "continue" },\n { "from": "delay_1", "to": "email_1", "type": "continue" },\n { "from": "email_1", "to": "exit_node", "type": "continue" }\n ]\n}\n```\n\nEmail bodies come from the template library, not hand-written html:\n\n1. **Reuse first.** List the library with `workflows-list-email-templates` and pick a template that fits. A drip campaign typically references one base template (say, a branded announcement) from every email step.\n2. **Create only if nothing fits.** Author a new template design-first with the **`designing-email-templates`** skill: compose the `design`, omit `html` (the server renders html from the design).\n3. **Reference it** by putting the template\'s UUID in each step\'s `config.template_uuid`, as above. The save snapshots the template\'s subject, text, html, and design into the step.\n4. **Differentiate per step** with `workflows-patch-action-email` design operations - each step\'s snapshot is edited independently, so five steps from one base template can each carry their own content.\n\nThe snapshot is one-way: editing the library template later does not change steps that already referenced it, and patching a step never touches the library template. If a user expects a template edit to flow into their workflows, correct that - the steps keep their copies, and each one is updated with `workflows-patch-action-email`.\n\nAlways give templates a real plain-text `text` alongside the design: clients that block rich content show only `text`, so filler like "placeholder" reaches real inboxes.\n\n## Hard rules to surface to the user, not work around\n\n- **Behavioral targeting is unsupported.** "Did event X at least N times over the last M days" can\'t be expressed as a trigger or a batch/schedule audience. If asked, reject it and explain; don\'t approximate it with a broken filter. (The backend rejects behavioral cohorts in batch audiences outright.)\n- **Batch audiences target _who a person is_, not what they did.** Person properties and/or static/property-based cohorts only. Event/action filters in a batch audience are silently dropped, so they\'re rejected.\n- **Prefer re-evaluating audiences.** For batch, inline person-property conditions or a dynamic (filter-based) cohort re-evaluate as people qualify; a static cohort is a frozen list, use only for an explicit given set.\n\n# Workflow graph schema\n\nThe contract for `actions` and `edges`. The stored workflow is loose JSON, but **the visual editor validates every node against a strict schema keyed on `type`**. A node that saves successfully but doesn\'t match this contract will **break the editor view for the whole workflow** when someone opens it. Treat the shapes below as required, not advisory.\n\n## Contents\n\n- Node (action) shape\n- Action types and their `config`\n- Edges\n- `function*` inputs\n- Duration strings (`delay_duration`, `max_wait_duration`)\n- Conversion & exit condition\n- Pre-submit checklist\n\n## Node (action) shape\n\nEvery action object has these common fields plus a type-specific `config`:\n\n```json\n{\n "id": "unique_within_workflow",\n "name": "Human label",\n "description": "",\n "type": "<see action types>",\n "config": {},\n "on_error": "continue",\n "filters": null,\n "output_variable": null\n}\n```\n\n- `id` — unique within the workflow; edges reference it by `from`/`to`.\n- `on_error` — optional; **only `continue` or `abort`.** Omit to use the default.\n- `filters` — optional property filters gating the action: `{properties: [<cond>]}`. Send `properties`, not `bytecode`.\n- `output_variable` — optional; store a step result into a workflow variable. `{key, result_path?, spread?}`.\n\n## Action types and their `config`\n\nUse **only** these `type` values — they are the complete supported set. An unknown or unsupported `type` breaks the editor\'s parse for the entire graph.\n\n| `type` | `config` |\n| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |\n| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |\n| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |\n| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |\n| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |\n| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |\n| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don\'t guess the id or its inputs — discover them live (see below). |\n| `function_email` | `{ "template_id?": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email`; omit it and the server infers it from the step type. Reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id` — a UUID sent as `template_id` is moved into `template_uuid` automatically. When `template_uuid` is set and the value has no body keys (`subject`/`text`/`html`/`design`), the server copies the template\'s body into `inputs.email.value` at save (a snapshot — later template edits don\'t propagate); you still supply `from` and `to`. Set `from` to `{integrationId: <sender id>}` for one sender. To rotate across up to 10 senders, also set `integrationIds: [<sender id>, ...]`; keep `integrationId` as the first sender for compatibility. Workflow runs using the same sender list resolve to the same sender, including across multiple email steps. If you author any body key inline, your body wins and `template_uuid` is provenance only. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |\n| `function_sms` | `{ "template_id?": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`; omit it and the server infers it. |\n| `function_push` | `{ "template_id?": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`; omit it and the server infers it. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email\'s — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project\'s push integration ids for `channels`. |\n| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |\n\n### Branch and wait condition filters (the `filters` wrapper is mandatory)\n\n`conditional_branch` and `wait_until_condition` gate on a **`filters` object**, the action-filter shape (`{properties?, events?, actions?, source?, filter_test_accounts?}`). The wrapper is not optional:\n\n- Write `{ "filters": { "properties": [<cond>] } }` on each condition, **never** `{ "properties": [<cond>] }` directly on the condition object. The bare form saves but the visual editor flags it and the branch compiles to a constant, so it never evaluates your condition.\n- `conditional_branch` conditions are **property-only** (person/group `<cond>`s). Event/action filters are rejected here ("Event filters are not allowed in conditionals").\n- `wait_until_condition` is event-aware: its `condition.filters` and each `events?[].filters` may also carry `events`/`actions`. An entry naming neither an event nor an action is dropped (it would match everything).\n- `source` is optional (defaults to `events`). Never send `bytecode`; the server compiles it from `properties`.\n\n### Trigger `config` (the `trigger` node)\n\nDiscriminated on `config.type`:\n\n- `event` — `{ "type": "event", "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events", "order": 0, "properties": [<cond>] }], "properties": [<cond>], "filter_test_accounts": false } }`. Fires on **every** matching occurrence. Throttle repeats with `trigger_masking` (dedup/sampling — not behavioral filtering).\n- `webhook` / `manual` / `tracking_pixel` — `{ "type": "webhook", "template_id": "<literal>", "inputs": { ... } }`. These use a **fixed built-in source template**, not one you look up: `template-source-webhook` for both `webhook` and `manual`, `template-source-webhook-pixel` for `tracking_pixel`. Omitting or guessing it fails the create with `Template not found` against the trigger node. They are `source_webhook` templates and are **not** in the destination catalog (`cdp-function-templates-list` is `type=destination`), so don\'t try to discover them there. Each needs `inputs.event` and `inputs.distinct_id` wrapped in `{value: ...}`, and the right values **differ per trigger type** because a different request reaches the template:\n - `webhook` — a POST whose body you control: `"inputs": { "event": { "value": "{request.body.event}" }, "distinct_id": { "value": "{request.body.distinct_id}" } }`.\n - `manual` — the "trigger manually" button POSTs `{user_id, $variables}`, so the body carries no `event`: use the fixed literal `"inputs": { "event": { "value": "$workflow_triggered" }, "distinct_id": { "value": "{request.body.user_id}" } }`. Pointing `event` at `{request.body.event}` here makes every manual run return 400 (the source template rejects an empty `event`) while the UI still shows a success toast, so the workflow silently never fires.\n - `tracking_pixel` — a bodyless `GET`, so read query params: `"inputs": { "event": { "value": "{request.query.ph_event}" }, "distinct_id": { "value": "{request.query.ph_distinct_id}" } }`. Body references resolve empty here and the pixel still returns its 200 GIF, so every hit is dropped with no error to retry on.\n- `batch` — `{ "type": "batch", "filters": { "properties": [<cond>] } }`. The audience: person-property conditions and/or cohort references. **No event/action filters** (silently dropped, so rejected). Does not fire on enable — dispatch a one-off broadcast with `workflows-run-batch`, or make it **recurring** with `workflows-schedule-create` (attaches an RRULE schedule; each firing re-broadcasts to this same `config.filters.properties` audience). A recurring workflow is a `batch` trigger plus a schedule — there is no separate "schedule" trigger type to author.\n\n### Trigger masking (throttling an event trigger)\n\n`trigger_masking` is a top-level workflow field (not an action) that throttles an already-matching `event` trigger — it dedups/samples firings, it does not decide who enters.\n\n```json\n"trigger_masking": { "hash": "{person.id}", "ttl": 3600, "threshold": null }\n```\n\n- `hash` — HogQL template defining the dedup key. `"{person.id}"` = once per person.\n- `ttl` — seconds to suppress repeats of the same hash (60–94608000).\n- `threshold?` — fire once per N matches of the same hash (a sampler: N=3 fires on the 1st, 4th, 7th…). Omit to fire once then suppress within `ttl`.\n- Don\'t send `bytecode` — compiled server-side from `hash`.\n\n### Condition shape (`<cond>`)\n\nProperty conditions used in trigger/action `filters`, branch conditions, and conversion:\n\n```json\n{ "key": "plan", "value": ["pro"], "operator": "exact", "type": "person" }\n```\n\n`type` is `event` | `person` | `group`. Never include `bytecode` — the server compiles it.\n\n## Edges\n\n```json\n{ "from": "source_id", "to": "target_id", "type": "continue", "index": 0 }\n```\n\n- `type: "continue"` — fall-through: the sequential next step, or the **no-match** path out of a `conditional_branch`. For a `wait_until_condition` it is the **`max_wait_duration` timeout** path.\n- `type: "branch"` — requires `index`, matching `config.conditions[index]` on a `conditional_branch`. A `wait_until_condition` **resolves** (its `condition` matches or an `events` entry fires) out the `branch` edge at **`index: 0`**.\n- **Every non-exit node needs a reachable next action** via an outgoing edge, or execution fails with "No next action found".\n- A `conditional_branch` with N conditions typically has N `branch` edges (`index: 0..N-1`) plus one `continue` edge for the no-match path.\n- A `wait_until_condition` needs a `branch` edge at `index: 0` (resolution) **and** a `continue` edge (timeout). Without the `index: 0` branch it only ever advances on timeout, never on the event/condition firing.\n\n## `function*` inputs\n\nInputs are keyed by the template\'s input schema, each wrapped in `{value: ...}`:\n\n```json\n"inputs": { "url": { "value": "https://example.com/hook" } }\n```\n\n- **Wrap values in `{value: ...}`.** A flat string won\'t enable templating.\n- Templating uses **single-curly** `{person.x}` / `{event.x}` inside the value string. Liquid-style `{{ ... }}` is rejected on hog-templated fields ("Placeholders are not allowed in this context") — the only fields that accept Liquid are ones whose input schema declares `templating: liquid` (the email input on `function_email` does; most others don\'t).\n- **Dictionary input values are template strings too** — write booleans/numbers as single-expression templates: `"{true}"`, `"{42}"`, which evaluate to the typed value.\n- Required inputs must be present, or create fails with "This field is required".\n\n### Discovering function templates (do this, don\'t guess)\n\nThe set of available `function` templates and their required inputs is **live data**, not something to hardcode — it changes as integrations are added. For a `function` node:\n\n1. `cdp-function-templates-list` (filter `type=destination`) to find the right template and its `id`.\n2. `cdp-function-templates-retrieve` with that id to read its **`inputs_schema`** — the exact keys, types, and which are required.\n3. Build `inputs` from that schema. A `template_id` not in the live list fails with "Template not found".\n\n`function_email`, `function_sms`, and `function_push` are the exception — their `template_id` is the fixed literal `template-email` / `template-twilio` / `template-native-push`, so you don\'t look the `template_id` up, and you can omit it entirely: the server infers the literal from the step type. A saved email template\'s UUID goes in `template_uuid` alongside the literal, never in `template_id` (a UUID sent as `template_id` is moved into `template_uuid` automatically). For `function_email`, referencing a template means you only author `from`/`to`: the server materializes the template\'s body at save (see the action-types table). `function_push` still has variable `inputs` (notably `channels`), so retrieve its `inputs_schema` even though the id is fixed.\n\n### `function_push` worked example\n\nRetrieve `template-native-push` with `cdp-function-templates-retrieve` for the full `inputs_schema` (it has many optional Android/iOS keys), but the core shape is:\n\n```json\n{\n "id": "push_1",\n "name": "Re-engagement push",\n "type": "function_push",\n "config": {\n "template_id": "template-native-push",\n "inputs": {\n "distinctId": { "value": "{event.distinct_id}" },\n "channels": { "value": [6, 7] },\n "title": { "value": "Notification from {event.event}" },\n "body": { "value": "Hi {{ person.properties.first_name }}, come finish setting up.", "templating": "liquid" }\n }\n }\n}\n```\n\n- **`channels`** is an `integration_multi` input: its `value` is an array of **integration id numbers** (e.g. `[6, 7]`), not objects. Find the FCM/APNs integration ids with `integrations-list` (look for `kind` `firebase` / `apns`); at least one is required or the send throws "No push channel configured".\n- **Templating differs per input.** `body` is **liquid** — interpolate with `{{ person.x }}` / `{{ event.x }}` (double braces) and set `"templating": "liquid"`. `title` and the other string inputs are **hog** — use `{event.x}` / `{person.x}` (single braces). The wrong brace style leaves the expression as a literal.\n- Required: `distinctId`, `channels`, `title`. Optional: `body`, `image`, `data`, `ttlSeconds`, `android_*`, `ios_*` (retrieve the `inputs_schema` for the full set).\n- Never hand-author `bytecode` — the server compiles it from `value`. Omit `order` too: the editor lays fields out in the template\'s `inputs_schema` order (fixed and consistent), not by the `order` on your inputs, so leaving it off doesn\'t change the form. Push has no delivered/opened/clicked signal (FCM/APNs respond synchronously), so a successful send means "accepted for delivery", nothing more.\n\n## Duration strings (`delay_duration`, `max_wait_duration`)\n\nMust match `^\\d*\\.?\\d+[dhms]$` — a number plus unit `s` | `m` | `h` | `d`. Examples: `30s`, `30m`, `2h`, `1d`, `1.5d` (=36h).\n\n- **No ISO-8601.** Fractions are allowed in every unit.\n- Per-unit caps are **silently clamped**: `s`≤60, `m`≤60, `h`≤24, `d`≤30. Max total 30d. Use the larger unit (`90m` → use `1.5h`) to avoid surprise clamping.\n\n## Conversion & exit condition\n\n- `exit_condition`: `exit_only_at_end` (default), `exit_on_conversion`, `exit_on_trigger_not_matched`, `exit_on_trigger_not_matched_or_conversion`.\n- The `…conversion` variants require a `conversion` goal with two slots plus a window:\n - `filters` — **property conditions only**, an array `[{key, value, operator, type}, ...]` (empty array = any event in the window converts).\n - `events` — **event-based goals**, `[{ "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events" }] } }]`.\n - `window_minutes` — minutes after entry (`null` = no window).\n- **An event goal goes in `events`, never in `filters`.** An event object stuffed into `filters` is invisible to the conversion matcher and breaks the conversion picker. Without a goal the `…conversion` exit is a silent no-op. Server compiles the bytecode.\n\n## Pre-submit checklist\n\n- [ ] Exactly **one** `type: "trigger"` action; usually exactly one `exit`.\n- [ ] Every action `type` and `config` matches a row above (no types outside the supported set).\n- [ ] `on_error` is only `continue` or `abort`.\n- [ ] `function_email.template_id == "template-email"`, `function_sms.template_id == "template-twilio"`, `function_push.template_id == "template-native-push"`.\n- [ ] A `webhook` / `manual` trigger sets `template_id == "template-source-webhook"` (a `tracking_pixel` uses `"template-source-webhook-pixel"`) — these are built-in source templates, not catalog lookups.\n- [ ] That trigger\'s `inputs.event` / `inputs.distinct_id` match its own type: `{request.body.*}` for `webhook`, `$workflow_triggered` + `{request.body.user_id}` for `manual`, `{request.query.ph_*}` for `tracking_pixel`. The wrong pair saves fine and then fails at trigger time.\n- [ ] Every non-exit node has an outgoing edge; `branch` edges have an `index` matching a condition.\n- [ ] Every `conditional_branch` / `wait_until_condition` condition is wrapped: `{filters: {properties: [...]}}`, not `{properties: [...]}`.\n- [ ] All durations match `^\\d*\\.?\\d+[dhms]$` and dodge the silent per-unit clamp.\n- [ ] Function inputs are `{key: {value: ...}}`; no hand-written `bytecode` anywhere; no top-level `trigger` field set.',}export const DESIGNING_EMAIL_TEMPLATES_SKILL: EmbeddedSkill = {diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.mdindex 5cab2c0268e5..5eac11b701b2 100644--- a/products/workflows/skills/building-workflows/references/graph-schema.md+++ b/products/workflows/skills/building-workflows/references/graph-schema.md@@ -38,19 +38,19 @@ Every action object has these common fields plus a type-specific `config`:Use **only** these `type` values — they are the complete supported set. An unknown or unsupported `type` breaks the editor's parse for the entire graph.-| `type` | `config` |-| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |-| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |-| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |-| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |-| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |-| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |-| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don't guess the id or its inputs — discover them live (see below). |-| `function_email` | `{ "template_id?": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email`; omit it and the server infers it from the step type. Reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id` — a UUID sent as `template_id` is moved into `template_uuid` automatically. When `template_uuid` is set and the value has no body keys (`subject`/`text`/`html`/`design`), the server copies the template's body into `inputs.email.value` at save (a snapshot — later template edits don't propagate); you still supply `from` and `to`. If you author any body key inline, your body wins and `template_uuid` is provenance only. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |-| `function_sms` | `{ "template_id?": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`; omit it and the server infers it. |-| `function_push` | `{ "template_id?": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`; omit it and the server infers it. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email's — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project's push integration ids for `channels`. |-| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |+| `type` | `config` |+| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |+| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |+| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |+| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |+| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |+| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |+| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don't guess the id or its inputs — discover them live (see below). |+| `function_email` | `{ "template_id?": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email`; omit it and the server infers it from the step type. Reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id` — a UUID sent as `template_id` is moved into `template_uuid` automatically. When `template_uuid` is set and the value has no body keys (`subject`/`text`/`html`/`design`), the server copies the template's body into `inputs.email.value` at save (a snapshot — later template edits don't propagate); you still supply `from` and `to`. Set `from` to `{integrationId: <sender id>}` for one sender. To rotate across up to 10 senders, also set `integrationIds: [<sender id>, ...]`; keep `integrationId` as the first sender for compatibility. Workflow runs using the same sender list resolve to the same sender, including across multiple email steps. If you author any body key inline, your body wins and `template_uuid` is provenance only. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |+| `function_sms` | `{ "template_id?": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`; omit it and the server infers it. |+| `function_push` | `{ "template_id?": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`; omit it and the server infers it. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email's — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project's push integration ids for `channels`. |+| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |### Branch and wait condition filters (the `filters` wrapper is mandatory)