: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
fix(workflows): evaluate slack trigger filters in test runs (#91572)
Harley Alexander5f1cd2e09f83
diff --git a/nodejs/src/cdp/async-functions/create-task.ts b/nodejs/src/cdp/async-functions/create-task.tsindex f7f8a2d70e7e..cf10a1899ceb 100644--- a/nodejs/src/cdp/async-functions/create-task.ts+++ b/nodejs/src/cdp/async-functions/create-task.ts@@ -63,7 +63,9 @@ registerAsyncFunction('postHogCreateTask', {logs.push({level: 'info',timestamp: DateTime.now(),- message: `Async function 'postHogCreateTask' was mocked with arguments:`,+ message:+ `Async function 'postHogCreateTask' was mocked. No task was created, and the real ` ++ `creation checks (environment configuration, owner eligibility, rate caps) did not run. Arguments:`,})logs.push({level: 'info',diff --git a/nodejs/src/cdp/cdp-api.serial.test.ts b/nodejs/src/cdp/cdp-api.serial.test.tsindex 3376177f29a6..48b19b720df0 100644--- a/nodejs/src/cdp/cdp-api.serial.test.ts+++ b/nodejs/src/cdp/cdp-api.serial.test.ts@@ -993,6 +993,67 @@ describe('CDP API', () => {}})++ const slackMessageFlowConfiguration = {+ id: 'slack-message-flow',+ team_id: 0,+ name: 'Slack message flow',+ actions: [+ {+ id: 'trigger_node',+ name: 'Trigger',+ type: 'trigger',+ config: {+ type: 'internal-event',+ filters: {+ source: 'internal-events',+ events: [{ id: '$slack_message_received', type: 'events' }],+ properties: [{ key: 'channel', value: 'C0ALERTS', operator: 'exact', type: 'event' }],+ // properties.channel == 'C0ALERTS'+ bytecode: ['_H', 1, 32, 'C0ALERTS', 32, 'channel', 32, 'properties', 1, 2, 11],+ },+ },+ },+ { id: 'exit_node', name: 'Exit', type: 'exit', config: {} },+ ],+ edges: [{ from: 'trigger_node', to: 'exit_node', type: 'continue' }],+ }++ it.each([+ ['skips a non-slack event', '$pageview', 'skipped', null],+ ['passes a matching slack message', '$slack_message_received', 'success', 'exit_node'],+ ])(+ '%s against a Slack-connected internal-event trigger',+ async (_, eventName, expectedStatus, expectedNextActionId) => {+ const res = await supertest(app)+ .post(`/api/projects/${team.id}/hog_flows/new/invocations`)+ .send({+ globals: {+ ...globals,+ event: {+ ...globals.event!,+ event: eventName,+ properties: { channel: 'C0ALERTS', text: 'deploy failed' },+ },+ },+ mock_async_functions: true,+ configuration: { ...slackMessageFlowConfiguration, team_id: team.id },+ })++ expect(res.status).toEqual(200)+ expect(res.body.status).toEqual(expectedStatus)+ expect(res.body.nextActionId).toEqual(expectedNextActionId)+ if (expectedStatus === 'skipped') {+ expect(res.body.logs).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message: expect.stringContaining('would not trigger this workflow'),+ }),+ ])+ )+ }+ }+ )})describe('hogflow wait_until_condition test invocations', () => {diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 7d73e7c62bfc..e9755fe71519 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -526,6 +526,7 @@ export function createCdpCoreServices(recipientPreferencesService,emailValidationService,cohortMembershipRepository,+ deps.integrationManager,hogFlowDuplicateObserver,cdpUsageReporter)diff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.tsindex 16e0a4be8b6c..a3c869edf4e7 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts@@ -9,6 +9,7 @@ import { captureException } from '~/common/utils/posthog'import { HealthCheckResult, PluginsServerConfig, Team } from '../../types'import { CdpDataWarehouseEvent, CdpDataWarehouseEventSchema } from '../schema'+import { DWH_SOURCE_TABLE_PROPERTY, WAREHOUSE_SOURCE_ROW_EVENT, WAREHOUSE_VIEW_ROW_EVENT } from '../schema/hogflow'import { HogFlowInvocationPipeline } from '../services/hog-flow-invocation-pipeline.service'import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'import { JobQueue } from '../services/job-queue/job-queue.interface'@@ -21,14 +22,6 @@ import {import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'-// Synthetic event name stamped on the synthetic event built for a warehouse-row trigger.-// Acts as the "this globals object originated from a synced warehouse row" discriminator.-export const WAREHOUSE_SOURCE_ROW_EVENT = '$warehouse_source_row'--// The same, for a row a materialized view run added or updated. Kept distinct from the source-table-// name so a run's origin is legible in logs and test payloads without decoding the trigger config.-export const WAREHOUSE_VIEW_ROW_EVENT = '$warehouse_view_row'-// Filter source / trigger type each kind of warehouse row matches against.const TRIGGER_TYPE_BY_TABLE_TYPE = {source: 'data-warehouse-table',@@ -39,11 +32,6 @@ type WarehouseTableType = keyof typeof TRIGGER_TYPE_BY_TABLE_TYPEconst WAREHOUSE_TRIGGER_TYPES = new Set<string>(Object.values(TRIGGER_TYPE_BY_TABLE_TYPE))-// Special property on the synthetic event holding the dot-notated source table name.-// Used by the pipeline's eligibility predicate to match warehouse-table HogFlow triggers-// against the row's source table without adding a top-level field to globals.-export const DWH_SOURCE_TABLE_PROPERTY = '$source_table'-export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {protected name = 'CdpDatawarehouseEventsConsumer'protected hogTypes: HogFunctionTypeType[] = ['destination']diff --git a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.tsindex 7f3a05e03dca..7b3e09f2c94a 100644--- a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts@@ -9,6 +9,12 @@ import { captureException } from '~/common/utils/posthog'import { HealthCheckResult, PluginsServerConfig } from '../../types'import { CdpInternalEventSchema } from '../schema'+import {+ GITHUB_EVENT_RECEIVED_EVENT,+ SLACK_MESSAGE_RECEIVED_EVENT,+ getInternalEventFilterEventIds,+ hasMatchingInternalEventFilter,+} from '../schema/hogflow'import { HogFlowInvocationPipeline } from '../services/hog-flow-invocation-pipeline.service'import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'import { JobQueue } from '../services/job-queue/job-queue.interface'@@ -17,37 +23,6 @@ import { convertInternalEventToHogFunctionInvocationGlobals } from '../utils'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'-const SLACK_MESSAGE_RECEIVED_EVENT = '$slack_message_received'-const GITHUB_EVENT_RECEIVED_EVENT = '$github_event_received'--function getInternalEventFilterEventIds(filters: unknown): string[] | null {- if (!filters || typeof filters !== 'object') {- return null- }-- const { source, events, actions, data_warehouse } = filters as {- source?: unknown- events?: unknown- actions?: unknown- data_warehouse?: unknown- }- const hasUnsupportedFilters =- (actions !== undefined && (!Array.isArray(actions) || actions.length > 0)) ||- (data_warehouse !== undefined && (!Array.isArray(data_warehouse) || data_warehouse.length > 0))- if (source !== 'internal-events' || !Array.isArray(events) || !events.length || hasUnsupportedFilters) {- return null- }-- const eventIds = events.map((event) => (event && typeof event === 'object' ? (event as { id?: unknown }).id : null))- return eventIds.every((eventId): eventId is string => typeof eventId === 'string' && eventId.trim().length > 0)- ? eventIds- : null-}--function hasMatchingInternalEventFilter(filters: unknown, eventName: string): boolean {- return getInternalEventFilterEventIds(filters)?.includes(eventName) ?? false-}-/*** Whether a GitHub delivery is a write PostHog's own GitHub App made, resolved from the `own_app`* property the emit stamps on the event.diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.tsindex 36e767a9e3ad..61d7ef993371 100644--- a/nodejs/src/cdp/schema/hogflow.ts+++ b/nodejs/src/cdp/schema/hogflow.ts@@ -369,6 +369,73 @@ export function isRowScopedTrigger(trigger: HogFlow['trigger']): trigger is RowS)}+// The internal event a Slack-connected workflow's trigger fires on. Shared by the internal-events+// consumer's eligibility check and the test-run trigger handler so both match the same events.+// The Python producer keeps its own copy in products/slack_app/backend/slack_workflow_events.py.+export const SLACK_MESSAGE_RECEIVED_EVENT = '$slack_message_received'++// The same, for a GitHub delivery. The Python producer keeps its own copy in+// products/workflows/backend/github_workflow_events.py.+export const GITHUB_EVENT_RECEIVED_EVENT = '$github_event_received'++// The event ids an internal-event trigger's filters name, or null when the filters are not the+// shape the internal-events consumer accepts (wrong source, no events, or action/warehouse+// filters, which that stream cannot evaluate). Shared by the consumer's eligibility check and+// the test-run trigger handler so both accept the same filters.+export function getInternalEventFilterEventIds(filters: unknown): string[] | null {+ if (!filters || typeof filters !== 'object') {+ return null+ }++ const { source, events, actions, data_warehouse } = filters as {+ source?: unknown+ events?: unknown+ actions?: unknown+ data_warehouse?: unknown+ }+ const hasUnsupportedFilters =+ (actions !== undefined && (!Array.isArray(actions) || actions.length > 0)) ||+ (data_warehouse !== undefined && (!Array.isArray(data_warehouse) || data_warehouse.length > 0))+ if (source !== 'internal-events' || !Array.isArray(events) || !events.length || hasUnsupportedFilters) {+ return null+ }++ const eventIds = events.map((event) => (event && typeof event === 'object' ? (event as { id?: unknown }).id : null))+ return eventIds.every((eventId): eventId is string => typeof eventId === 'string' && eventId.trim().length > 0)+ ? eventIds+ : null+}++export function hasMatchingInternalEventFilter(filters: unknown, eventName: string): boolean {+ return getInternalEventFilterEventIds(filters)?.includes(eventName) ?? false+}++// Synthetic event name stamped on the row built for a warehouse-row trigger from a synced source+// table. Shared by the warehouse-events consumer's eligibility check and the test-run trigger+// handler so both match the same rows.+export const WAREHOUSE_SOURCE_ROW_EVENT = '$warehouse_source_row'++// The same, for a row a materialized view run added or updated.+export const WAREHOUSE_VIEW_ROW_EVENT = '$warehouse_view_row'++// Property on the synthetic row event holding the dot-notated source table name, read against a+// row-scoped trigger's own `table_name` to confirm a row actually came from that table.+export const DWH_SOURCE_TABLE_PROPERTY = '$source_table'++// The row-scoped trigger type a synthetic warehouse event's name matches, or null for anything+// else. Explicit rather than defaulting to one type, so a caller that can receive an arbitrary+// event - like a workflow test run - does not treat an unrelated event as a warehouse row by+// elimination.+export function rowScopedTriggerTypeForEvent(eventName: string | undefined): RowScopedTrigger['type'] | null {+ if (eventName === WAREHOUSE_VIEW_ROW_EVENT) {+ return 'data-warehouse-view'+ }+ if (eventName === WAREHOUSE_SOURCE_ROW_EVENT) {+ return 'data-warehouse-table'+ }+ return null+}+// NOTE: these are purposefully exported as interfaces to support kea typegenexport interface HogFlow extends z.infer<typeof HogFlowSchema> {}export type HogFlowAction = z.infer<typeof HogFlowActionSchema> & Record<string, unknown>diff --git a/nodejs/src/cdp/services/hogflows/actions/trigger.handler.test.ts b/nodejs/src/cdp/services/hogflows/actions/trigger.handler.test.tsnew file mode 100644index 000000000000..4db5c1faa236--- /dev/null+++ b/nodejs/src/cdp/services/hogflows/actions/trigger.handler.test.ts@@ -0,0 +1,224 @@+import { FixtureHogFlowBuilder } from '~/cdp/_tests/builders/hogflow.builder'+import { createExampleHogFlowInvocation } from '~/cdp/_tests/fixtures-hogflows'+import { HogFlow } from '~/cdp/schema/hogflow'++import { findActionByType } from '../hogflow-utils'+import { ActionHandlerResult } from './action.interface'+import { SlackAppLookup, TriggerHandler } from './trigger.handler'++describe('TriggerHandler', () => {+ // properties.channel == 'C0ALERTS', as the HogQL compiler emits for a channel exact filter+ const CHANNEL_BYTECODE = ['_H', 1, 32, 'C0ALERTS', 32, 'channel', 32, 'properties', 1, 2, 11]+ // properties.status == 'churned'+ const ROW_BYTECODE = ['_H', 1, 32, 'churned', 32, 'status', 32, 'properties', 1, 2, 11]++ // Maps integration id -> the team and app_id stored on that integration, mirroring what+ // IntegrationManagerService.getMany returns (a lookup with no team scoping of its own).+ // Empty by default, so no event looks self-sent unless a test names it. teamId defaults to+ // 1, the fixture hogflow's own team - set it explicitly to simulate another team's row.+ const fakeIntegrationLookup = (apps: Record<number, { appId: string; teamId?: number }> = {}): SlackAppLookup => ({+ getMany: (ids) =>+ Promise.resolve(+ Object.fromEntries(+ ids.map((id) => [+ id,+ id in apps ? { team_id: apps[id].teamId ?? 1, config: { app_id: apps[id].appId } } : null,+ ])+ )+ ),+ })++ const run = async (+ triggerConfig: HogFlow['trigger'],+ event: { event: string; properties?: Record<string, any> },+ integrationLookup: SlackAppLookup = fakeIntegrationLookup()+ ): Promise<{ result: ActionHandlerResult; logs: string[] }> => {+ const hogFlow = new FixtureHogFlowBuilder()+ .withWorkflow({+ actions: {+ trigger: { type: 'trigger', config: triggerConfig as any },+ exit: { type: 'exit', config: {} },+ },+ edges: [{ from: 'trigger', to: 'exit', type: 'continue' }],+ })+ .build()+ const action = findActionByType(hogFlow, 'trigger')!+ const invocation = createExampleHogFlowInvocation(hogFlow, { event: event as any })+ invocation.state.currentAction = { id: action.id, startedAtTimestamp: Date.now() }++ const result = { logs: [] } as any+ const handlerResult = await new TriggerHandler(integrationLookup).execute({ invocation, action, result })+ return { result: handlerResult, logs: result.logs.map((log: { message: string }) => log.message) }+ }++ const slackTrigger = (filters: Record<string, any> = {}): HogFlow['trigger'] =>+ ({+ type: 'internal-event',+ filters: {+ source: 'internal-events',+ events: [{ id: '$slack_message_received', type: 'events' }],+ ...filters,+ },+ }) as HogFlow['trigger']++ it('skips an internal-event trigger when the test event is not one its filters name', async () => {+ const { result, logs } = await run(slackTrigger(), { event: '$pageview' })++ expect(result).toEqual({ finished: true, skipped: true })+ expect(logs).toEqual([+ "This workflow triggers on '$slack_message_received' events. A '$pageview' event would not trigger this workflow.",+ ])+ })++ it('skips an internal-event trigger whose filters name no events', async () => {+ // The consumer's eligibility check never fires such a trigger, so a test run must not+ // pass it either, even though its property filters alone would match anything.+ const { result, logs } = await run(+ { type: 'internal-event', filters: { source: 'internal-events', events: [] } } as any,+ { event: '$slack_message_received' }+ )++ expect(result).toEqual({ finished: true, skipped: true })+ expect(logs).toEqual([+ "This trigger's filters do not name any internal events, so no event would trigger this workflow.",+ ])+ })++ it("skips an internal-event trigger for PostHog's own GitHub App activity", async () => {+ const { result, logs } = await run(+ {+ type: 'internal-event',+ filters: {+ source: 'internal-events',+ events: [{ id: '$github_event_received', type: 'events' }],+ properties: [],+ bytecode: ['_h', 29],+ },+ } as any,+ { event: '$github_event_received', properties: { own_app: true } }+ )++ expect(result).toEqual({ finished: true, skipped: true })+ expect(logs).toEqual(["Activity from PostHog's own GitHub App would not trigger this workflow."])+ })++ it.each([+ ['matching', 'C0ALERTS', 'exit'],+ ['non-matching', 'C0OTHER', null],+ ])('evaluates the trigger property filters against a %s channel', async (_label, channel, expectedNextActionId) => {+ const { result, logs } = await run(+ slackTrigger({ properties: [{ key: 'channel' }], bytecode: CHANNEL_BYTECODE }),+ { event: '$slack_message_received', properties: { channel } }+ )++ if (expectedNextActionId) {+ expect(result.nextAction?.id).toEqual(expectedNextActionId)+ } else {+ expect(result).toEqual({ finished: true, skipped: true })+ expect(logs).toEqual(['Workflow trigger did not match the event.'])+ }+ })++ it('continues an internal-event trigger with no property filters when the event name matches', async () => {+ // A saved flow with no filters carries the server-compiled always-true bytecode.+ const { result } = await run(slackTrigger({ properties: [], bytecode: ['_h', 29] }), {+ event: '$slack_message_received',+ })++ expect(result.nextAction?.id).toEqual('exit')+ })++ it("skips a Slack-triggered workflow for a message PostHog's own connected app posted", async () => {+ const { result, logs } = await run(+ slackTrigger({ properties: [], bytecode: ['_h', 29] }),+ { event: '$slack_message_received', properties: { integration_id: 1, app_id: 'A_OWN_APP' } },+ fakeIntegrationLookup({ 1: { appId: 'A_OWN_APP' } })+ )++ expect(result).toEqual({ finished: true, skipped: true })+ expect(logs).toEqual(["Messages PostHog's own connected Slack app posted would not trigger this workflow."])+ })++ it('continues a Slack-triggered workflow for a message from a different Slack app', async () => {+ const { result } = await run(+ slackTrigger({ properties: [], bytecode: ['_h', 29] }),+ { event: '$slack_message_received', properties: { integration_id: 1, app_id: 'A_OTHER_APP' } },+ fakeIntegrationLookup({ 1: { appId: 'A_OWN_APP' } })+ )++ expect(result.nextAction?.id).toEqual('exit')+ })++ it("does not treat another team's integration as this workflow's own app, even on an app_id match", async () => {+ // integration_id and app_id come straight from the test-run payload, and getMany resolves+ // an id across all teams. Without a team_id check, this is a cross-team oracle: a test+ // run on any workflow can confirm another team's integration_id -> app_id pairing.+ const { result } = await run(+ slackTrigger({ properties: [], bytecode: ['_h', 29] }),+ { event: '$slack_message_received', properties: { integration_id: 1, app_id: 'A_OWN_APP' } },+ fakeIntegrationLookup({ 1: { appId: 'A_OWN_APP', teamId: 999 } })+ )++ expect(result.nextAction?.id).toEqual('exit')+ })++ // A saved trigger with no row filters carries the server-compiled always-true bytecode.+ const NO_FILTERS_BYTECODE = ['_h', 29]++ const warehouseTableTrigger = (+ filters: Record<string, any> = { properties: [], bytecode: NO_FILTERS_BYTECODE }+ ): HogFlow['trigger'] =>+ ({+ type: 'data-warehouse-table',+ table_name: 'postgres.public.accounts',+ filters,+ }) as HogFlow['trigger']++ it.each([+ ['matching', 'churned', 'exit'],+ ['non-matching', 'active', null],+ ])('evaluates warehouse-row trigger filters against a %s row', async (_label, status, expectedNextActionId) => {+ const { result } = await run(+ warehouseTableTrigger({ properties: [{ key: 'status' }], bytecode: ROW_BYTECODE }),+ { event: '$warehouse_source_row', properties: { status, $source_table: 'postgres.public.accounts' } }+ )++ if (expectedNextActionId) {+ expect(result.nextAction?.id).toEqual(expectedNextActionId)+ } else {+ expect(result).toEqual({ finished: true, skipped: true })+ }+ })++ // A freshly created warehouse trigger has empty filters, which match unconditionally - so+ // without a row-kind/table check any event would otherwise pass it, the same false positive+ // this handler already closes for internal-event triggers.+ it.each([+ ['a non-warehouse event', '$pageview', {}],+ ['the wrong row kind', '$warehouse_view_row', { $source_table: 'postgres.public.accounts' }],+ ['a row from another table', '$warehouse_source_row', { $source_table: 'postgres.public.orders' }],+ ])('skips a data-warehouse-table trigger with no filters given %s', async (_label, eventName, properties) => {+ const { result } = await run(warehouseTableTrigger(), { event: eventName, properties })++ expect(result).toEqual({ finished: true, skipped: true })+ })++ it('continues a data-warehouse-view trigger given a matching view row', async () => {+ const { result } = await run(+ {+ type: 'data-warehouse-view',+ table_name: 'materialized_active_users',+ filters: { properties: [], bytecode: NO_FILTERS_BYTECODE },+ } as HogFlow['trigger'],+ { event: '$warehouse_view_row', properties: { $source_table: 'materialized_active_users' } }+ )++ expect(result.nextAction?.id).toEqual('exit')+ })++ it('continues a trigger type without filters regardless of the event', async () => {+ const { result } = await run({ type: 'schedule' } as HogFlow['trigger'], { event: '$pageview' })++ expect(result.nextAction?.id).toEqual('exit')+ })+})diff --git a/nodejs/src/cdp/services/hogflows/actions/trigger.handler.ts b/nodejs/src/cdp/services/hogflows/actions/trigger.handler.tsindex 7f1433de84b9..7be5f04e1858 100644--- a/nodejs/src/cdp/services/hogflows/actions/trigger.handler.ts+++ b/nodejs/src/cdp/services/hogflows/actions/trigger.handler.ts@@ -1,26 +1,121 @@import { DateTime } from 'luxon'-import { HogFlowAction } from '~/cdp/schema/hogflow'+import {+ DWH_SOURCE_TABLE_PROPERTY,+ GITHUB_EVENT_RECEIVED_EVENT,+ HogFlowAction,+ SLACK_MESSAGE_RECEIVED_EVENT,+ getInternalEventFilterEventIds,+ isRowScopedTrigger,+ rowScopedTriggerTypeForEvent,+} from '~/cdp/schema/hogflow'import { filterFunctionInstrumented } from '~/cdp/utils/hog-function-filtering'import { findContinueAction } from '../hogflow-utils'import { ActionHandler, ActionHandlerOptions, ActionHandlerResult } from './action.interface'+// The slice of IntegrationManagerService the own-app check needs, so this handler and its tests+// don't depend on the concrete Postgres-backed service. getMany has no team scoping of its own+// (it's a raw lookup by id, see IntegrationManagerService.fetchIntegrations), so team_id travels+// with the result and every caller must check it - the same contract hog-inputs.service.ts uses.+export interface SlackAppLookup {+ getMany(+ integrationIds: number[]+ ): Promise<Record<number, { team_id: number; config?: { app_id?: string | null } } | null>>+}+// NOTE: This is not an actively used action as the triggering is done by the scheduler// but useful for testing the hogflow executorexport class TriggerHandler implements ActionHandler {+ constructor(private integrationManager: SlackAppLookup) {}+async execute({invocation,action,result,}: ActionHandlerOptions<Extract<HogFlowAction, { type: 'trigger' }>>): Promise<ActionHandlerResult> {- if (action.config.type !== 'event') {+ const trigger = action.config+ const event = invocation.state.event++ if (trigger.type === 'internal-event') {+ // Test runs accept arbitrary globals, so mirror the eligibility checks the+ // internal-events consumer applies before a real invocation is ever created: the+ // trigger only fires on the internal events its filters name.+ const eventIds = getInternalEventFilterEventIds(trigger.filters)+ if (!eventIds) {+ result.logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message:+ "This trigger's filters do not name any internal events, so no event would trigger this workflow.",+ })+ return { finished: true, skipped: true }+ }+ if (!event?.event || !eventIds.includes(event.event)) {+ result.logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `This workflow triggers on '${eventIds.join("', '")}' events. A '${event?.event}' event would not trigger this workflow.`,+ })+ return { finished: true, skipped: true }+ }++ // Mirrors the consumer's own-app exclusion: a message PostHog's own connected Slack+ // app posted never reaches a real invocation, so a workflow can't retrigger itself+ // off its own reply. Without this, a hand-written payload naming that app passes.+ if (+ event.event === SLACK_MESSAGE_RECEIVED_EVENT &&+ (await this.isOwnSlackMessage(event.properties, invocation.teamId))+ ) {+ result.logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: "Messages PostHog's own connected Slack app posted would not trigger this workflow.",+ })+ return { finished: true, skipped: true }+ }++ // The GitHub equivalent, resolved from the own_app property the emit stamps on the+ // event (see isOwnGithubEvent in the internal-events consumer).+ if (event.event === GITHUB_EVENT_RECEIVED_EVENT && event.properties?.own_app === true) {+ result.logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: "Activity from PostHog's own GitHub App would not trigger this workflow.",+ })+ return { finished: true, skipped: true }+ }+ }++ // Mirrors the warehouse-events consumer's eligibility check: a warehouse-row trigger only+ // fires on a row of its own kind (source table vs materialized view) from its own table.+ // Without this, any event - a $pageview included - passes a warehouse trigger whose+ // filters are empty, which is the default for a freshly created one. isRowScopedTrigger+ // also covers internal-event, which has no table_name to check here and is handled by+ // its own eligibility checks above.+ if (trigger.type === 'data-warehouse-table' || trigger.type === 'data-warehouse-view') {+ const sourceTable = event?.properties?.[DWH_SOURCE_TABLE_PROPERTY]+ const rowTriggerType = rowScopedTriggerTypeForEvent(event?.event)+ if (rowTriggerType !== trigger.type || sourceTable !== trigger.table_name) {+ result.logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `This workflow triggers on rows from '${trigger.table_name}'. A '${event?.event}' event with source table '${sourceTable ?? 'none'}' would not trigger it.`,+ })+ return { finished: true, skipped: true }+ }+ }++ // The filter-carrying trigger types, the same set buildHogFlowInvocations evaluates before+ // creating a real invocation. The remaining types (webhook, manual, schedule, batch,+ // tracking_pixel) carry no event filters, so they continue unconditionally.+ if (trigger.type !== 'event' && !isRowScopedTrigger(trigger)) {return { nextAction: findContinueAction(invocation) }}const filterResults = await filterFunctionInstrumented({fn: invocation.hogFlow,- filters: action.config.filters,+ filters: trigger.filters,filterGlobals: invocation.filterGlobals,})@@ -39,4 +134,18 @@ export class TriggerHandler implements ActionHandler {return { nextAction: findContinueAction(invocation) }}++ private async isOwnSlackMessage(properties: Record<string, any> | undefined, teamId: number): Promise<boolean> {+ const integrationId = properties?.integration_id+ const appId = properties?.app_id+ if (typeof integrationId !== 'number' || typeof appId !== 'string') {+ return false+ }+ const integrations = await this.integrationManager.getMany([integrationId])+ const integration = integrations[integrationId]+ // integration_id and app_id come from an untrusted test-run payload, and getMany can+ // resolve an id belonging to any team - never trust its config without checking team_id+ // first, or a test run becomes a cross-team oracle for another team's Slack app_id.+ return integration?.team_id === teamId && integration?.config?.app_id === appId+ }}diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex b8c60750f734..9938e40ba56c 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -178,7 +178,8 @@ describe('Hogflow Executor', () => {hogFlowFunctionsService,recipientPreferencesService,emailValidationService,- stubCohortMembershipRepository+ stubCohortMembershipRepository,+ hub.integrationManager)})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 326209fc3c75..524f536dc866 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -33,7 +33,7 @@ import { DelayHandler } from './actions/delay'import { ExitHandler } from './actions/exit.handler'import { HogFunctionHandler } from './actions/hog_function'import { RandomCohortBranchHandler } from './actions/random_cohort_branch'-import { TriggerHandler } from './actions/trigger.handler'+import { SlackAppLookup, TriggerHandler } from './actions/trigger.handler'import { WaitUntilTimeWindowHandler } from './actions/wait_until_time_window'import { buildConversionWatcher } from './conversion-watcher'import { HogFlowDuplicateObserverService } from './hogflow-duplicate-observer.service'@@ -117,6 +117,7 @@ export class HogFlowExecutorService {recipientPreferencesService: RecipientPreferencesService,emailValidationService: EmailValidationService,cohortMembershipRepository: CohortMembershipRepository,+ integrationManager: SlackAppLookup,duplicateObserver?: HogFlowDuplicateObserverService,usageReporter?: CdpUsageReporterService) {@@ -145,7 +146,7 @@ export class HogFlowExecutorService {)this.actionHandlers = {- trigger: new TriggerHandler(),+ trigger: new TriggerHandler(integrationManager),conditional_branch: new ConditionalBranchHandler(cohortMembershipRepository),wait_until_condition: new ConditionalBranchHandler(cohortMembershipRepository),delay: new DelayHandler(),diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex f34064c3d35c..0ca046b6009e 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -3074,7 +3074,14 @@ class HogFlowInvocationSerializer(serializers.Serializer):write_only=True, required=False, help_text="Optional override; omit to use saved definition.")globals = serializers.DictField(- write_only=True, required=False, help_text="Test trigger payload, typically {event, person, groups}."+ write_only=True,+ required=False,+ help_text=(+ "Test trigger payload, typically {event, person, groups}. Shape it like the trigger's real payload: "+ "an event matching the trigger filters for event triggers, or for an internal-event trigger an event "+ "named in its filters.events (e.g. $slack_message_received with Slack properties like channel, user, "+ "text, ts) and no person."+ ),)mock_async_functions = serializers.BooleanField(default=True,diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorPanelTest.tsx b/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorPanelTest.tsxindex 58df9e3a31e3..437e8eab2133 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorPanelTest.tsx+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorPanelTest.tsx@@ -232,6 +232,8 @@ export function HogFlowEditorPanelTest(): JSX.Element | null {<Link to={url} className="flex gap-2 items-center"><span className="font-semibold">{display}</span></Link>+ ) : sampleGlobals ? (+ <span className="text-muted">No associated person</span>) : (<span className="text-muted">Loading...</span>)}{' '}diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.tsindex 35d0303dab20..3bba8f5e6c81 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts@@ -8,6 +8,8 @@ import { groupsModel } from '~/models/groupsModel'import { initKeaTests } from '~/test/init'import { AvailableFeature, GroupType, GroupTypeIndex, OrganizationType } from '~/types'+import { encodeSlackFilters } from '../../registry/triggers/slackTriggerFilters'+import { createExampleEventForTrigger } from '../../testEventFactory'import {createGlobalsFromResponse,groupSelectColumns,@@ -146,6 +148,117 @@ describe('hogFlowEditorTestLogic', () => {})})+ describe('createExampleEventForTrigger', () => {+ it('builds a slack message example for Slack-connected triggers, seeded from the channel filter', () => {+ const properties = encodeSlackFilters({+ channel: 'C0ALERTS|#alerts',+ posterMode: 'anyone',+ posterIds: [],+ topLevelOnly: false,+ additional: [],+ })++ const globals = createExampleEventForTrigger(+ {+ type: 'internal-event',+ filters: {+ source: 'internal-events',+ events: [{ id: '$slack_message_received', type: 'events' }],+ properties,+ },+ },+ 1,+ 'wf'+ )++ expect(globals.event.event).toEqual('$slack_message_received')+ expect(globals.event.properties.channel).toEqual('C0ALERTS')+ // Slack-triggered runs are person-less, so the example must not invent one+ expect(globals.person).toBeUndefined()+ // The flat property bag the webhook emitter produces, which trigger filters read+ expect(globals.event.properties).toMatchObject({+ channel_type: 'channel',+ subtype: null,+ thread_ts: null,+ is_thread_reply: false,+ is_ext_shared_channel: false,+ })+ expect(Object.keys(globals.event.properties)).toEqual(+ expect.arrayContaining([+ 'integration_id',+ 'slack_team_id',+ 'user',+ 'bot_id',+ 'app_id',+ 'text',+ 'ts',+ 'slack_event',+ ])+ )+ })++ it('falls back to a default channel when the trigger has no channel filter', () => {+ const globals = createExampleEventForTrigger(+ {+ type: 'internal-event',+ filters: { source: 'internal-events', events: [{ id: '$slack_message_received', type: 'events' }] },+ },+ 1,+ 'wf'+ )++ expect(globals.event.event).toEqual('$slack_message_received')+ expect(typeof globals.event.properties.channel).toEqual('string')+ })++ // Each native poster mode compiles to a different property filter (slackTriggerFilters.ts).+ // A sample seeding only channel satisfies 'anyone' by accident and rejects every other mode.+ it.each([+ ['people', [] as string[], (props: Record<string, any>) => expect(props.bot_id).toBeNull()],+ ['apps', [] as string[], (props: Record<string, any>) => expect(props.bot_id).not.toBeNull()],+ [+ 'specific_people',+ ['U0999999999'],+ (props: Record<string, any>) => expect(props.user).toEqual('U0999999999'),+ ],+ [+ 'specific_apps',+ ['A0999999999'],+ (props: Record<string, any>) => expect(props.app_id).toEqual('A0999999999'),+ ],+ ])('seeds a sample that satisfies the %s poster filter', (posterMode, posterIds, assertion) => {+ const properties = encodeSlackFilters({+ channel: 'C0ALERTS',+ posterMode: posterMode as any,+ posterIds,+ topLevelOnly: false,+ additional: [],+ })++ const globals = createExampleEventForTrigger(+ {+ type: 'internal-event',+ filters: {+ source: 'internal-events',+ events: [{ id: '$slack_message_received', type: 'events' }],+ properties,+ },+ },+ 1,+ 'wf'+ )++ assertion(globals.event.properties)+ })++ it('returns the standard example event for event triggers', () => {+ const globals = createExampleEventForTrigger({ type: 'event', filters: {} }, 1, 'wf')++ expect(globals.event.event).toEqual('$pageview')+ expect(globals.person).not.toBeUndefined()+ })+ })+beforeEach(() => {initKeaTests()useMocks({ get: { '/api/environments/:team_id/hog_flows/:id/': WORKFLOW_FIXTURE } })diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.tsindex df4fdd254839..ecd8b56122ad 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts@@ -28,8 +28,9 @@ import {import { WorkflowLogicProps, workflowLogic } from '../../../workflowLogic'import type { TriggerAction } from '../../../workflowLogic'import { hogFlowEditorLogic } from '../../hogFlowEditorLogic'+import { isSlackMessageTriggerConfig } from '../../registry/triggers/slackTriggerFilters'import { HogflowTestResult } from '../../steps/types'-import { createExampleEvent } from '../../testEventFactory'+import { createExampleEvent, createExampleEventForTrigger } from '../../testEventFactory'import type { HogFlow } from '../../types'// Time range constants for event search@@ -827,19 +828,23 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([const response = await performWideEventsQueryInTwoPhases(query)if (!response?.results?.[0]) {- // No matching events found, use standard example event- const exampleGlobals = createExampleEvent(values.workflow.team_id, values.workflow.name)+ // No matching events found, use a trigger-appropriate example event+ const exampleGlobals = createExampleEventForTrigger(+ values.triggerAction?.config,+ values.workflow.team_id,+ values.workflow.name+ )if (extendedSearch) {// Extended search also failedactions.setSampleGlobalsError(- `No "${eventName}" events found in the last ${EXTENDED_SEARCH_DAYS} days. Using an example $pageview event instead.`+ `No "${eventName}" events found in the last ${EXTENDED_SEARCH_DAYS} days. Using an example ${exampleGlobals.event.event} event instead.`)actions.setCanTryExtendedSearch(false)} else {// First search failed, allow extended searchactions.setSampleGlobalsError(- `No "${eventName}" events found in the last ${STANDARD_SEARCH_DAYS} days. Using an example $pageview event instead.`+ `No "${eventName}" events found in the last ${STANDARD_SEARCH_DAYS} days. Using an example ${exampleGlobals.event.event} event instead.`)actions.setCanTryExtendedSearch(true)}@@ -1051,8 +1056,17 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([actions.loadSampleGlobals()} else {// Only use example event if we can't load actual events- const exampleGlobals = createExampleEvent(values.workflow.team_id, values.workflow.name)+ const exampleGlobals = createExampleEventForTrigger(+ values.triggerAction?.config,+ values.workflow.team_id,+ values.workflow.name+ )actions.loadSampleGlobalsSuccess(exampleGlobals)+ if (isSlackMessageTriggerConfig(values.triggerAction?.config)) {+ actions.setSampleGlobalsError(+ "A real Slack message can't be loaded here. This example matches your channel and who-can-start-a-run filters. Edit it to test any other filters, such as message text."+ )+ }}}),])diff --git a/products/workflows/frontend/Workflows/hogflows/testEventFactory.ts b/products/workflows/frontend/Workflows/hogflows/testEventFactory.tsindex 0659a8d9ad3e..3d34558047be 100644--- a/products/workflows/frontend/Workflows/hogflows/testEventFactory.ts+++ b/products/workflows/frontend/Workflows/hogflows/testEventFactory.ts@@ -3,6 +3,12 @@ import { uuid } from 'lib/utils/dom'import { CyclotronJobInvocationGlobals } from '~/types'+import {+ SlackTriggerFilters,+ decodeSlackFilters,+ isSlackMessageTriggerConfig,+} from './registry/triggers/slackTriggerFilters'+// A pure, kea-free factory for a synthetic test event/person - kept out of hogFlowEditorTestLogic// so callers that only need example data don't pull in the workflow editor's kea logic graph.export const createExampleEvent = (@@ -49,3 +55,95 @@ export const createExampleEvent = (},}}++// Mirrors the flat property bag the Slack webhook handler emits for $slack_message_received+// (products/slack_app/backend/slack_workflow_events.py), so the test payload has the same shape+// a real trigger fire delivers. Slack-triggered runs carry no person.+//+// `filters` seeds the fields the trigger's own channel and poster-mode filters read, so the+// generated sample matches those native filters by construction. It cannot seed an advanced+// filter added through `additional` (e.g. on `text` or `subtype`) - those still need manual edits.+export const createExampleSlackMessageEvent = (+ teamId?: number,+ workflowName?: string | null,+ filters: Partial<SlackTriggerFilters> = {}+): CyclotronJobInvocationGlobals => {+ const resolvedTeamId = teamId || 1+ const projectUrl = `${window.location.origin}/project/${resolvedTeamId}`+ const channel = filters.channel ?? 'C0123456789'+ const posterId = filters.posterIds?.[0]+ // Defaults satisfy 'anyone' and 'people' (no bot_id); each other native poster mode+ // overrides only the field its own filter reads.+ let user: string | null = 'U0123456789'+ let botId: string | null = null+ let appId: string | null = null+ switch (filters.posterMode) {+ case 'apps':+ botId = 'B0123456789'+ appId = 'A0123456789'+ user = null+ break+ case 'specific_apps':+ appId = posterId ?? 'A0123456789'+ botId = 'B0123456789'+ user = null+ break+ case 'specific_people':+ user = posterId ?? user+ break+ }+ const text = 'This is an example Slack message'+ const ts = `${dayjs().unix()}.000100`+ return {+ event: {+ uuid: uuid(),+ distinct_id: user ?? botId ?? channel,+ timestamp: dayjs().toISOString(),+ elements_chain: '',+ url: '',+ event: '$slack_message_received',+ properties: {+ integration_id: 1,+ channel,+ channel_type: 'channel',+ slack_team_id: 'T0123456789',+ user,+ bot_id: botId,+ app_id: appId,+ subtype: null,+ text,+ ts,+ thread_ts: null,+ is_thread_reply: false,+ is_ext_shared_channel: false,+ slack_event: { type: 'message', channel, channel_type: 'channel', user, text, ts },+ this_is_an_example_event: true,+ },+ },+ groups: {},+ project: {+ id: resolvedTeamId,+ name: 'Default project',+ url: projectUrl,+ },+ source: {+ name: workflowName ?? 'Unnamed',+ url: window.location.href.split('#')[0],+ },+ }+}++// The example globals for a trigger type. A Slack-connected internal-event trigger gets a+// message shaped like the real internal event, seeded with the trigger's own channel and poster+// filters so it matches those by default.+export const createExampleEventForTrigger = (+ triggerConfig: unknown,+ teamId?: number,+ workflowName?: string | null+): CyclotronJobInvocationGlobals => {+ if (isSlackMessageTriggerConfig(triggerConfig)) {+ const decoded = decodeSlackFilters(triggerConfig.filters.properties)+ return createExampleSlackMessageEvent(teamId, workflowName, decoded)+ }+ return createExampleEvent(teamId, workflowName)+}diff --git a/products/workflows/frontend/generated/agentContext.ts b/products/workflows/frontend/generated/agentContext.tsindex c69296d4ba0b..b0614f6b9a5d 100644--- a/products/workflows/frontend/generated/agentContext.ts+++ b/products/workflows/frontend/generated/agentContext.ts@@ -101,7 +101,7 @@ export const WORKFLOWS_MCP_TOOLS: McpToolSummary[] = [{name: 'workflows-test-run',description:- "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS/push) are mocked by default; set mock_async_functions=false to fire real side effects. The trigger step evaluates its filters against globals and returns status=skipped when they do not match. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of its live config — always do this before workflows-publish. use_draft requires a staged draft to exist (workflows-get shows it in 'draft'); on a workflow with nothing staged, omit it.",+ "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}), shaped like what the trigger really receives: for event triggers, an event matching the trigger filters; for internal-event triggers, the event MUST be named in the trigger's filters.events (the Slack trigger fires on $slack_message_received with Slack properties like channel, channel_type, user, bot_id, app_id, subtype, text, ts, thread_ts) and carry no person; copy a real payload from workflows-get-invocation when a past run exists. The trigger step evaluates event, internal-event, and warehouse-row trigger filters against globals and returns status=skipped when the event name or filters do not match: fix a fabricated payload to match the trigger, but treat a skip on a real, copied payload as a broken trigger filter instead. Other trigger types are not filtered. Async actions (HTTP/email/SMS/push) are mocked by default; set mock_async_functions=false to fire real side effects. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of its live config — always do this before workflows-publish. use_draft requires a staged draft to exist (workflows-get shows it in 'draft'); on a workflow with nothing staged, omit it.",},{name: 'workflows-update',@@ -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- Waiting until a date (`delay_until`)\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" }`, or `{ "delay_until": {"expression": "<HogQL date>", "offset?": "-1d"}, "max_delay_duration?": "30d" }` to wait for a per-person date. Exactly one of the two. See duration rules and `delay_until` 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## Waiting until a date (`delay_until`)\n\nA `delay` waits either a fixed span or until a date carried by the person or the event. Use `delay_until` when the date differs per person, which a duration cannot express (a trial expiry, a renewal date, a booked appointment).\n\n```json\n{\n "id": "delay_1",\n "type": "delay",\n "config": {\n "delay_until": { "expression": "person.properties.trial_expiration_at", "offset": "-1d" },\n "max_delay_duration": "30d"\n }\n}\n```\n\n- **Exactly one of `delay_duration` and `delay_until`.** Both together are rejected; so is neither.\n- `expression` is HogQL resolving to a datetime. An ISO string, a `HogDateTime`, and unix seconds all resolve to the same instant, so a stored date works whichever shape the customer set it in. A bare number is read as **seconds**: a millisecond timestamp (what `Date.now()` and most SDKs produce) is rejected rather than read as a date tens of thousands of years out. Divide it by 1000 in the expression, or store the date as an ISO string.\n- `offset` shifts that instant and is **signed**: `^-?\\d*\\.?\\d+[dhms]$`. `-1d` is a day before the date, `2h` is two hours after. Omit it to wait for the date itself. Keep the arithmetic here rather than in the expression, so the builder can still read the step back as a property plus an offset.\n- Unlike `delay_duration`, an offset is **not** clamped per unit: `-45d` means 45 days, not 30. `max_delay_duration` bounds the wait instead.\n- `timezone`, `use_person_timezone` and `fallback_timezone` work as they do on `wait_until_time_window`, and decide which zone a date **with no offset of its own** is read in (a bare `2026-03-01`, or `2026-03-01T09:00:00`). A date that states an offset, a `HogDateTime`, and unix seconds are absolute and ignore them. Default `UTC`, so a date-only value means midnight UTC unless you set a zone.\n- `max_delay_duration` caps how far past the step\'s start the wait may run (default `30d`, same duration rules as above). It exists so a far-future date cannot park a run indefinitely.\n- **Never send `bytecode`.** The server compiles the expression at save time and discards anything the client sent. A broken expression fails the save with the parse error.\n- The expression is re-read on **every wake**, not only on entry, and the only wake a parked delay schedules is the instant it computed. So a date that **moves further out** is honored: the run wakes at the old instant and parks again to the new one. A date that **moves closer** is not: nothing wakes the run early, so it waits for the original instant and then continues at once, later than the new date asked for.\n- A date that cannot be resolved aborts the run whatever `on_error` says, because a wait that cannot work out when to act has nothing safe to fall through to.\n- A person property is `person.properties.<key>`; an **event property is `properties.<key>`, with no `event.` prefix**. The expression runs against the same globals as a filter, where `event` is the event\'s name, so `event.properties.<key>` resolves to nothing and aborts the run.\n- The builder writes those two shapes (bracketed when the key is not a bare identifier). Any other expression saves fine but shows in the editor as a read-only custom expression instead of a property pick.\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- [ ] Every `delay` sets exactly one of `delay_duration` and `delay_until`, and no `delay_until` carries hand-written `bytecode`.\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}`), shaped like the trigger\'s real payload: an `event` trigger needs an event matching its filters, and an `internal-event` trigger needs an event named in its `filters.events` (for the Slack trigger, a `$slack_message_received` event with the Slack property bag) and no person (see [references/graph-schema.md](references/graph-schema.md)). A `status=skipped` result means this payload would not fire the trigger: if you fabricated the payload, fix it to match the trigger; if it came from a real past run (`workflows-get-invocation`), the trigger\'s filter is wrong, not the payload. 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- Waiting until a date (`delay_until`)\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" }`, or `{ "delay_until": {"expression": "<HogQL date>", "offset?": "-1d"}, "max_delay_duration?": "30d" }` to wait for a per-person date. Exactly one of the two. See duration rules and `delay_until` 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- `internal-event` (flag-gated) — `{ "type": "internal-event", "filters": { "source": "internal-events", "events": [{ "id": "<event>", "type": "events" }], "properties": [<cond>] } }`. Fires once for each matching event on the internal-events stream; `filters.events` must name at least one allowed event id. Runs have no associated person, so person-dependent steps are unavailable. Test-run with an event named in `filters.events` and no person; any other event name is skipped at the trigger. The Slack trigger is this with `$slack_message_received` in `filters.events`: the run\'s event carries properties `integration_id`, `channel`, `channel_type`, `slack_team_id`, `user`, `bot_id`, `app_id`, `subtype`, `text`, `ts`, `thread_ts`, `is_thread_reply`, `is_ext_shared_channel`, and `slack_event` (the raw Slack payload), and a workflow leaving draft must include an exact `channel` property filter. The GitHub trigger uses `$github_event_received` and requires exact `repository` and `event_type` filters.\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## Waiting until a date (`delay_until`)\n\nA `delay` waits either a fixed span or until a date carried by the person or the event. Use `delay_until` when the date differs per person, which a duration cannot express (a trial expiry, a renewal date, a booked appointment).\n\n```json\n{\n "id": "delay_1",\n "type": "delay",\n "config": {\n "delay_until": { "expression": "person.properties.trial_expiration_at", "offset": "-1d" },\n "max_delay_duration": "30d"\n }\n}\n```\n\n- **Exactly one of `delay_duration` and `delay_until`.** Both together are rejected; so is neither.\n- `expression` is HogQL resolving to a datetime. An ISO string, a `HogDateTime`, and unix seconds all resolve to the same instant, so a stored date works whichever shape the customer set it in. A bare number is read as **seconds**: a millisecond timestamp (what `Date.now()` and most SDKs produce) is rejected rather than read as a date tens of thousands of years out. Divide it by 1000 in the expression, or store the date as an ISO string.\n- `offset` shifts that instant and is **signed**: `^-?\\d*\\.?\\d+[dhms]$`. `-1d` is a day before the date, `2h` is two hours after. Omit it to wait for the date itself. Keep the arithmetic here rather than in the expression, so the builder can still read the step back as a property plus an offset.\n- Unlike `delay_duration`, an offset is **not** clamped per unit: `-45d` means 45 days, not 30. `max_delay_duration` bounds the wait instead.\n- `timezone`, `use_person_timezone` and `fallback_timezone` work as they do on `wait_until_time_window`, and decide which zone a date **with no offset of its own** is read in (a bare `2026-03-01`, or `2026-03-01T09:00:00`). A date that states an offset, a `HogDateTime`, and unix seconds are absolute and ignore them. Default `UTC`, so a date-only value means midnight UTC unless you set a zone.\n- `max_delay_duration` caps how far past the step\'s start the wait may run (default `30d`, same duration rules as above). It exists so a far-future date cannot park a run indefinitely.\n- **Never send `bytecode`.** The server compiles the expression at save time and discards anything the client sent. A broken expression fails the save with the parse error.\n- The expression is re-read on **every wake**, not only on entry, and the only wake a parked delay schedules is the instant it computed. So a date that **moves further out** is honored: the run wakes at the old instant and parks again to the new one. A date that **moves closer** is not: nothing wakes the run early, so it waits for the original instant and then continues at once, later than the new date asked for.\n- A date that cannot be resolved aborts the run whatever `on_error` says, because a wait that cannot work out when to act has nothing safe to fall through to.\n- A person property is `person.properties.<key>`; an **event property is `properties.<key>`, with no `event.` prefix**. The expression runs against the same globals as a filter, where `event` is the event\'s name, so `event.properties.<key>` resolves to nothing and aborts the run.\n- The builder writes those two shapes (bracketed when the key is not a bare identifier). Any other expression saves fine but shows in the editor as a read-only custom expression instead of a property pick.\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- [ ] Every `delay` sets exactly one of `delay_duration` and `delay_until`, and no `delay_until` carries hand-written `bytecode`.\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/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex b6cb900d1ce7..3c9a346c8749 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -951,14 +951,14 @@ export interface HogInvocationResultsCountApi {}/**- * Test trigger payload, typically {event, person, groups}.+ * Test trigger payload, typically {event, person, groups}. Shape it like the trigger's real payload: an event matching the trigger filters for event triggers, or for an internal-event trigger an event named in its filters.events (e.g. $slack_message_received with Slack properties like channel, user, text, ts) and no person.*/export type HogFlowInvocationApiGlobals = { [key: string]: unknown }export interface HogFlowInvocationApi {/** Optional override; omit to use saved definition. */configuration?: HogFlowApi- /** Test trigger payload, typically {event, person, groups}. */+ /** Test trigger payload, typically {event, person, groups}. Shape it like the trigger's real payload: an event matching the trigger filters for event triggers, or for an internal-event trigger an event named in its filters.events (e.g. $slack_message_received with Slack properties like channel, user, text, ts) and no person. */globals?: HogFlowInvocationApiGlobals/** True (default) mocks HTTP/email/SMS. False fires real side effects. */mock_async_functions?: booleandiff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex 910f76f0a711..53b352c6e28b 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -2274,7 +2274,9 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({globals: zod.record(zod.string(), zod.unknown()).optional()- .describe('Test trigger payload, typically {event, person, groups}.'),+ .describe(+ "Test trigger payload, typically {event, person, groups}. Shape it like the trigger's real payload: an event matching the trigger filters for event triggers, or for an internal-event trigger an event named in its filters.events (e.g. $slack_message_received with Slack properties like channel, user, text, ts) and no person."+ ),mock_async_functions: zod.boolean().default(hogFlowsInvocationsCreateBodyMockAsyncFunctionsDefault)diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex e630ba544acb..7c09ac2c068d 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -440,12 +440,19 @@ tools:includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omitcurrent_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat.To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action- after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}).- Async actions (HTTP/email/SMS/push) are mocked by default; set mock_async_functions=false to fire real side- effects. The trigger step evaluates its filters against globals and returns status=skipped when they do not- match. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of- its live config — always do this before workflows-publish. use_draft requires a staged draft to exist- (workflows-get shows it in 'draft'); on a workflow with nothing staged, omit it.+ after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}),+ shaped like what the trigger really receives: for event triggers, an event matching the trigger filters; for+ internal-event triggers, the event MUST be named in the trigger's filters.events (the Slack trigger fires on+ $slack_message_received with Slack properties like channel, channel_type, user, bot_id, app_id, subtype,+ text, ts, thread_ts) and carry no person; copy a real payload from workflows-get-invocation when a past run+ exists. The trigger step evaluates event, internal-event, and warehouse-row trigger filters against globals+ and returns status=skipped when the event name or filters do not match: fix a fabricated payload to match+ the trigger, but treat a skip on a real, copied payload as a broken trigger filter instead. Other trigger+ types are not filtered. Async actions (HTTP/email/SMS/push) are mocked by default; set+ mock_async_functions=false to fire real side effects. Returns the step's execution trace. Set use_draft=true+ to test a workflow's staged draft instead of its live config — always do this before workflows-publish.+ use_draft requires a staged draft to exist (workflows-get shows it in 'draft'); on a workflow with nothing+ staged, omit it.exclude_params:- configurationworkflows-update:diff --git a/products/workflows/skills/building-workflows/SKILL.md b/products/workflows/skills/building-workflows/SKILL.mdindex 2d66f1773378..d73da80c6b39 100644--- a/products/workflows/skills/building-workflows/SKILL.md+++ b/products/workflows/skills/building-workflows/SKILL.md@@ -15,7 +15,7 @@ Work the workflow through these stages. Don't jump straight to enabling it.1. **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`.2. **Create as a draft.** `workflows-create`. Every workflow is created `draft`; it does not execute yet.-3. **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.+3. **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}`), shaped like the trigger's real payload: an `event` trigger needs an event matching its filters, and an `internal-event` trigger needs an event named in its `filters.events` (for the Slack trigger, a `$slack_message_received` event with the Slack property bag) and no person (see [references/graph-schema.md](references/graph-schema.md)). A `status=skipped` result means this payload would not fire the trigger: if you fabricated the payload, fix it to match the trigger; if it came from a real past run (`workflows-get-invocation`), the trigger's filter is wrong, not the payload. 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.4. **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.5. **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)).6. **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.diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.mdindex e252af99b0ff..dd5dd6c72efe 100644--- a/products/workflows/skills/building-workflows/references/graph-schema.md+++ b/products/workflows/skills/building-workflows/references/graph-schema.md@@ -72,6 +72,7 @@ Discriminated on `config.type`:- `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.- `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.- `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.+- `internal-event` (flag-gated) — `{ "type": "internal-event", "filters": { "source": "internal-events", "events": [{ "id": "<event>", "type": "events" }], "properties": [<cond>] } }`. Fires once for each matching event on the internal-events stream; `filters.events` must name at least one allowed event id. Runs have no associated person, so person-dependent steps are unavailable. Test-run with an event named in `filters.events` and no person; any other event name is skipped at the trigger. The Slack trigger is this with `$slack_message_received` in `filters.events`: the run's event carries properties `integration_id`, `channel`, `channel_type`, `slack_team_id`, `user`, `bot_id`, `app_id`, `subtype`, `text`, `ts`, `thread_ts`, `is_thread_reply`, `is_ext_shared_channel`, and `slack_event` (the raw Slack payload), and a workflow leaving draft must include an exact `channel` property filter. The GitHub trigger uses `$github_event_received` and requires exact `repository` and `event_type` filters.### Trigger masking (throttling an event trigger)diff --git a/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md b/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.mdindex 7f1019e46eff..936c824ba079 100644--- a/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md+++ b/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md@@ -19,7 +19,7 @@ The MCP tools for the workflows product, grouped by job. The lifecycle that stri**Test & inspect**-- `workflows-test-run` — runs **one step at a time**, it does not traverse the whole graph in one call. Omit `current_action_id` (or set it to the trigger) to run the first step; the result gives you `nextActionId`, which you pass as `current_action_id` on the next call. Walk the workflow step by step this way; to test a specific branch, set `current_action_id` to that node. Skip `delay` nodes by jumping to the action after them (delays aren't simulated). Pass test data via `globals` (`{event, person, groups}`). Async actions (HTTP/email/SMS) mocked by default; `mock_async_functions=false` fires real side effects. Returns the step's execution trace. `use_draft=true` tests an active workflow's staged draft instead of its live config — always do this before `workflows-publish`.+- `workflows-test-run` — runs **one step at a time**, it does not traverse the whole graph in one call. Omit `current_action_id` (or set it to the trigger) to run the first step; the result gives you `nextActionId`, which you pass as `current_action_id` on the next call. Walk the workflow step by step this way; to test a specific branch, set `current_action_id` to that node. Skip `delay` nodes by jumping to the action after them (delays aren't simulated). Pass test data via `globals` (`{event, person, groups}`), shaped like the trigger's real payload: an `event` trigger needs an event matching its filters, and an `internal-event` trigger needs an event named in its `filters.events` (for the Slack trigger, a `$slack_message_received` event with the Slack property bag) and no person (see [graph-schema.md](graph-schema.md)), best copied from a past run via `workflows-get-invocation`. The trigger step evaluates filters for `event`, `internal-event`, and warehouse-row triggers; `status=skipped` means this payload would not fire the trigger. Fix a fabricated payload to match the trigger; treat a skip on a real, copied payload as a broken trigger filter instead. Other trigger types pass any payload through. Async actions (HTTP/email/SMS) mocked by default; `mock_async_functions=false` fires real side effects. Returns the step's execution trace. `use_draft=true` tests an active workflow's staged draft instead of its live config — always do this before `workflows-publish`.- `workflows-logs` — execution log entries (timestamp, level DEBUG/LOG/INFO/WARN/ERROR, message). Filter by level, text, time range, limit.**Batch & schedules**diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex b720e510e9f0..0eed2d9f2cab 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -12308,7 +12308,7 @@}},"workflows-test-run": {- "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS/push) are mocked by default; set mock_async_functions=false to fire real side effects. The trigger step evaluates its filters against globals and returns status=skipped when they do not match. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of its live config — always do this before workflows-publish. use_draft requires a staged draft to exist (workflows-get shows it in 'draft'); on a workflow with nothing staged, omit it.",+ "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}), shaped like what the trigger really receives: for event triggers, an event matching the trigger filters; for internal-event triggers, the event MUST be named in the trigger's filters.events (the Slack trigger fires on $slack_message_received with Slack properties like channel, channel_type, user, bot_id, app_id, subtype, text, ts, thread_ts) and carry no person; copy a real payload from workflows-get-invocation when a past run exists. The trigger step evaluates event, internal-event, and warehouse-row trigger filters against globals and returns status=skipped when the event name or filters do not match: fix a fabricated payload to match the trigger, but treat a skip on a real, copied payload as a broken trigger filter instead. Other trigger types are not filtered. Async actions (HTTP/email/SMS/push) are mocked by default; set mock_async_functions=false to fire real side effects. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of its live config — always do this before workflows-publish. use_draft requires a staged draft to exist (workflows-get shows it in 'draft'); on a workflow with nothing staged, omit it.","category": "Workflows","feature": "workflows","summary": "Test-run workflow",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex e38260a5c611..f52393389205 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -13006,7 +13006,7 @@}},"workflows-test-run": {- "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS/push) are mocked by default; set mock_async_functions=false to fire real side effects. The trigger step evaluates its filters against globals and returns status=skipped when they do not match. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of its live config — always do this before workflows-publish. use_draft requires a staged draft to exist (workflows-get shows it in 'draft'); on a workflow with nothing staged, omit it.",+ "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}), shaped like what the trigger really receives: for event triggers, an event matching the trigger filters; for internal-event triggers, the event MUST be named in the trigger's filters.events (the Slack trigger fires on $slack_message_received with Slack properties like channel, channel_type, user, bot_id, app_id, subtype, text, ts, thread_ts) and carry no person; copy a real payload from workflows-get-invocation when a past run exists. The trigger step evaluates event, internal-event, and warehouse-row trigger filters against globals and returns status=skipped when the event name or filters do not match: fix a fabricated payload to match the trigger, but treat a skip on a real, copied payload as a broken trigger filter instead. Other trigger types are not filtered. Async actions (HTTP/email/SMS/push) are mocked by default; set mock_async_functions=false to fire real side effects. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of its live config — always do this before workflows-publish. use_draft requires a staged draft to exist (workflows-get shows it in 'draft'); on a workflow with nothing staged, omit it.","category": "Workflows","feature": "workflows","summary": "Test-run workflow",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4a787e0146c4..8f29a6e6a51b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42219,14 +42219,14 @@ export namespace Schemas {}/**- * Test trigger payload, typically {event, person, groups}.+ * Test trigger payload, typically {event, person, groups}. Shape it like the trigger's real payload: an event matching the trigger filters for event triggers, or for an internal-event trigger an event named in its filters.events (e.g. $slack_message_received with Slack properties like channel, user, text, ts) and no person.*/export type HogFlowInvocationGlobals = { [key: string]: unknown };export interface HogFlowInvocation {/** Optional override; omit to use saved definition. */configuration?: HogFlow;- /** Test trigger payload, typically {event, person, groups}. */+ /** Test trigger payload, typically {event, person, groups}. Shape it like the trigger's real payload: an event matching the trigger filters for event triggers, or for an internal-event trigger an event named in its filters.events (e.g. $slack_message_received with Slack properties like channel, user, text, ts) and no person. */globals?: HogFlowInvocationGlobals;/** True (default) mocks HTTP/email/SMS. False fires real side effects. */mock_async_functions?: boolean;diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex ae0ce62e1153..98899d45035f 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -887,7 +887,9 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({globals: zod.record(zod.string(), zod.unknown()).optional()- .describe('Test trigger payload, typically {event, person, groups}.'),+ .describe(+ "Test trigger payload, typically {event, person, groups}. Shape it like the trigger's real payload: an event matching the trigger filters for event triggers, or for an internal-event trigger an event named in its filters.events (e.g. $slack_message_received with Slack properties like channel, user, text, ts) and no person."+ ),mock_async_functions: zod.boolean().default(hogFlowsInvocationsCreateBodyMockAsyncFunctionsDefault)diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-test-run.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-test-run.jsonindex 658b7a0d45b1..19a73b4d2915 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-test-run.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-test-run.json@@ -7,7 +7,7 @@},"globals": {"additionalProperties": {},- "description": "Test trigger payload, typically {event, person, groups}.",+ "description": "Test trigger payload, typically {event, person, groups}. Shape it like the trigger's real payload: an event matching the trigger filters for event triggers, or for an internal-event trigger an event named in its filters.events (e.g. $slack_message_received with Slack properties like channel, user, text, ts) and no person.","propertyNames": {"type": "string"},