: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): let agents schedule a schedule-trigger workflow without an audience preview (#93383)
Harley Alexander16fa2b31ad1a
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 50719c67cf09..eb7b53d76456 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -2072,6 +2072,15 @@ def _hog_flow_run_idempotency_cache_key(team_id: int, hog_flow_id: str, idempotereturn f"hog_flow_run_idempotency:{team_id}:{hog_flow_id}:{idempotency_key}"+def _trigger_has_audience(hog_flow: HogFlow) -> bool:+ """Whether a dispatch of this workflow fans out to persons matched by the trigger's filters.++ Only the batch trigger does. A schedule trigger fires one person-less run, so there is no+ audience to preview and no blast-radius token to demand.+ """+ return (hog_flow.trigger or {}).get("type") == "batch"++def _email_sending_rates(sent: int, bounced: int, complained: int) -> dict[str, float | int]:# Sends are counted at send time but bounces/complaints at webhook time, so feedback arriving# just inside the window for sends just outside it can push the ratio past 1 (worst case: a@@ -3837,6 +3846,7 @@ class HogFlowViewSet(if not route_to_draft:self._maybe_reschedule_timing_edits(before_update, serializer.instance)+ self._pause_schedules_on_audience_change(before_update, serializer.instance)log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, previous=before_update)self._emit_resource_edited(serializer.instance)@@ -4004,6 +4014,7 @@ class HogFlowViewSet(if not route_to_draft:self._maybe_reschedule_timing_edits(before_update, locked)+ self._pause_schedules_on_audience_change(before_update, locked)# Explicit "updated" (the action name "graph" isn't in ACTIVITY_TYPES, which would fall back to# the indistinct "changed" and miss the describer's per-field rendering).log_activity_from_viewset(self, locked, activity="updated", name=locked.name, previous=before_update)@@ -4140,7 +4151,32 @@ class HogFlowViewSet(lambda: reschedule_hog_flow_timing.delay(team_id=team_id, hog_flow_id=hog_flow_id, action_ids=action_ids))+ def _pause_schedules_on_audience_change(self, before: Optional[HogFlow], after: HogFlow) -> None:+ """Pause every active schedule when the audience a batch dispatch fans out to changes.++ The scheduler reads the live trigger at fire time, so each firing broadcasts to whatever+ the trigger says then, not to what someone confirmed when the schedule was created. Two+ edits break that confirmation: a person-less trigger becoming `batch`, and a batch+ trigger's filters being widened. Both leave a recurring send whose recipient count nobody+ was shown, so the cadence stops until it is created again through the audience preview.++ Called wherever the LIVE trigger changes (direct save, graph edit, publish), never for+ draft writes, which don't change what the scheduler reads.+ """+ if not before or not _trigger_has_audience(after):+ return+ if _trigger_has_audience(before) and (before.trigger or {}).get("filters") == (after.trigger or {}).get(+ "filters"+ ):+ return+ paused = after.schedules.filter(status=HogFlowSchedule.Status.ACTIVE).update(+ status=HogFlowSchedule.Status.PAUSED, next_run_at=None, updated_at=timezone.now()+ )+ if paused:+ self._report_workflow_action("hog_flow_schedules_paused_on_audience_change", after, {"paused": paused})+def _require_audience_confirm_token(self, request: Request, hog_flow: HogFlow) -> None:+ """Only meaningful for triggers that fan out to a person audience; see _trigger_has_audience."""confirm_token = request.data.get("confirm_token")if not confirm_token:raise exceptions.ValidationError(@@ -4303,6 +4339,7 @@ class HogFlowViewSet(locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])self._maybe_reschedule_timing_edits(before_update, locked)+ self._pause_schedules_on_audience_change(before_update, locked)log_activity_from_viewset(self, locked, activity="published", name=locked.name, previous=before_update)self._emit_resource_edited(locked)self._report_workflow_action("hog_flow_draft_published", locked)@@ -5120,10 +5157,11 @@ class HogFlowViewSet(hog_flow = self.get_object()if request.method == "POST":- # A schedule is a recurring batch dispatch - without this, an agent could sidestep the- # batch_jobs token gate by scheduling the send instead. Same scoping: the web builder- # keeps its own confirm UI, headless callers stay token-free.- if get_event_source(request) in AGENT_EVENT_SOURCES:+ # A schedule on a batch trigger is a recurring batch dispatch - without this, an agent+ # could sidestep the batch_jobs token gate by scheduling the send instead. Same scoping:+ # the web builder keeps its own confirm UI, headless callers stay token-free. A schedule+ # trigger runs once per firing with no person audience, so there is nothing to size.+ if get_event_source(request) in AGENT_EVENT_SOURCES and _trigger_has_audience(hog_flow):# A draft's trigger can still be edited after the audience was sized, so a schedule# staged on a draft could fire on a broadened audience once enabled. Same rule the# MCP tool enforces, applied at the API boundary.diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 353d6ade02f8..1b32e38fd4aa 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -38,6 +38,10 @@ from products.workflows.backend.api.hog_flow import ()from products.workflows.backend.models.hog_flow.hog_flow import SUPPORTED_ACTION_TYPES, HogFlowfrom products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import HogFlowBatchJob+from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule++_AUDIENCE_CONDITION = {"key": "email", "type": "person", "value": "x", "operator": "icontains"}+_WIDER_AUDIENCE_CONDITION = {"key": "email", "type": "person", "value": "@", "operator": "icontains"}webhook_template = MOCK_NODE_TEMPLATES[0]@@ -3675,6 +3679,122 @@ class TestHogFlowAPI(APIBaseTest):mock_create_invocation.assert_called_once()assert mock_create_invocation.call_args.kwargs["max_audience_size"] == 50000+ def test_programmatic_schedule_on_schedule_trigger_needs_no_audience_token(self):+ hog_flow, _ = self._create_hog_flow_with_action(+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}+ )+ hog_flow["actions"][0]["config"] = {"type": "schedule"}+ hog_flow["status"] = "active"+ created = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert created.status_code == 201, created.json()++ scheduled = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{created.json()['id']}/schedules",+ {"rrule": "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO", "starts_at": "2026-08-03T09:00:00Z"},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert scheduled.status_code == 201, scheduled.json()++ def test_programmatic_schedule_on_batch_trigger_requires_audience_confirm_token(self):+ # Scheduling a batch trigger is a recurring dispatch - the same gate as batch_jobs applies,+ # or the token check could be sidestepped by scheduling the send instead.+ hog_flow, _ = self._create_hog_flow_with_action(+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}+ )+ hog_flow["actions"][0]["config"] = {"type": "batch", "filters": {"properties": [_AUDIENCE_CONDITION]}}+ hog_flow["status"] = "active"+ created = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert created.status_code == 201, created.json()+ flow_id = created.json()["id"]++ schedule_body = {"rrule": "FREQ=DAILY;INTERVAL=1", "starts_at": "2026-08-01T00:00:00Z"}+ no_token = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/schedules",+ schedule_body,+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert no_token.status_code == 400, no_token.json()+ assert "workflows-blast-radius" in no_token.json()["detail"]++ preview = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",+ {"filters": created.json()["trigger"]["filters"]},+ )+ assert preview.status_code == 200, preview.json()+ token = preview.json()["confirm_token"]++ scheduled = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/schedules",+ {**schedule_body, "confirm_token": token},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert scheduled.status_code == 201, scheduled.json()++ # A draft's trigger can still be edited after previewing, so a schedule staged on a draft+ # could fire on a broadened audience once enabled - programmatic scheduling requires active.+ del hog_flow["status"]+ draft_create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert draft_create.status_code == 201, draft_create.json()+ draft_schedule = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{draft_create.json()['id']}/schedules",+ {**schedule_body, "confirm_token": token},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert draft_schedule.status_code == 400, draft_schedule.json()+ assert "active" in draft_schedule.json()["detail"].lower()++ @parameterized.expand(+ [+ (+ "trigger_converted_to_batch",+ {"type": "schedule"},+ {"type": "batch", "filters": {"properties": [_AUDIENCE_CONDITION]}},+ HogFlowSchedule.Status.PAUSED,+ ),+ (+ "batch_audience_edited",+ {"type": "batch", "filters": {"properties": [_AUDIENCE_CONDITION]}},+ {"type": "batch", "filters": {"properties": [_WIDER_AUDIENCE_CONDITION]}},+ HogFlowSchedule.Status.PAUSED,+ ),+ (+ "batch_audience_unchanged",+ {"type": "batch", "filters": {"properties": [_AUDIENCE_CONDITION]}},+ {"type": "batch", "filters": {"properties": [_AUDIENCE_CONDITION]}},+ HogFlowSchedule.Status.ACTIVE,+ ),+ ]+ )+ def test_live_audience_change_pauses_schedules(self, _name, before_config, after_config, expected_status):+ # Each firing broadcasts to whatever the trigger says at fire time, not to what was confirmed+ # when the schedule was created, so an edit that moves the audience stops the cadence. A save+ # that leaves the audience alone must not, or every resave would silently kill the schedule.+ hog_flow, _ = self._create_hog_flow_with_action(+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}+ )+ hog_flow["actions"][0]["config"] = before_config+ hog_flow["status"] = "active"+ created = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert created.status_code == 201, created.json()++ scheduled = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{created.json()['id']}/schedules",+ {"rrule": "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO", "starts_at": "2026-08-03T09:00:00Z"},+ )+ assert scheduled.status_code == 201, scheduled.json()++ hog_flow["actions"][0]["config"] = after_config+ edited = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{created.json()['id']}",+ {"actions": hog_flow["actions"]},+ )+ assert edited.status_code == 200, edited.json()++ schedule = HogFlowSchedule.objects.get(id=scheduled.json()["id"])+ assert schedule.status == expected_status+ if expected_status == HogFlowSchedule.Status.PAUSED:+ assert schedule.next_run_at is None+@patch("products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation")@@ -3745,39 +3865,6 @@ class TestHogFlowAPI(APIBaseTest):# trigger edit racing the dispatch can't widen the confirmed audience.assert mock_create_invocation.call_args.kwargs["filters"] == trigger_filters- # Scheduling is a recurring dispatch - the same gate applies, or the batch_jobs token- # check could be sidestepped by scheduling the send instead.- schedule_body = {"rrule": "FREQ=DAILY;INTERVAL=1", "starts_at": "2026-08-01T00:00:00Z"}- no_token_schedule = self.client.post(- f"/api/projects/{self.team.id}/hog_flows/{flow_id}/schedules",- schedule_body,- HTTP_X_POSTHOG_CLIENT="mcp",- )- assert no_token_schedule.status_code == 400, no_token_schedule.json()- assert "workflows-blast-radius" in no_token_schedule.json()["detail"]-- scheduled = self.client.post(- f"/api/projects/{self.team.id}/hog_flows/{flow_id}/schedules",- {**schedule_body, "confirm_token": token},- HTTP_X_POSTHOG_CLIENT="mcp",- )- assert scheduled.status_code == 201, scheduled.json()-- # A draft's trigger can still be edited after previewing, so a schedule staged on a draft- # could fire on a broadened audience once enabled - programmatic scheduling requires active.- draft_flow, _ = self._create_hog_flow_with_action(- {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}- )- draft_create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", draft_flow)- assert draft_create.status_code == 201, draft_create.json()- draft_schedule = self.client.post(- f"/api/projects/{self.team.id}/hog_flows/{draft_create.json()['id']}/schedules",- {**schedule_body, "confirm_token": token},- HTTP_X_POSTHOG_CLIENT="mcp",- )- assert draft_schedule.status_code == 400, draft_schedule.json()- assert "active" in draft_schedule.json()["detail"].lower()-# A raw API key is a headless professional surface - no agent in the loop to read a count,# so the two-step would be ceremony. Dispatches in one call, no token. A fresh client keeps# the request session-free so it classifies as API, not WEB.diff --git a/products/workflows/frontend/generated/agentContext.ts b/products/workflows/frontend/generated/agentContext.tsindex b0614f6b9a5d..9b407ba54881 100644--- a/products/workflows/frontend/generated/agentContext.ts+++ b/products/workflows/frontend/generated/agentContext.ts@@ -21,7 +21,7 @@ export const WORKFLOWS_MCP_TOOLS: McpToolSummary[] = [{name: 'workflows-create',description:- "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.",+ "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|schedule|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. A 'schedule' trigger has no audience: it runs once per occurrence, so attach its cadence with workflows-schedule-create and skip the audience preview. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.",},{name: 'workflows-discard-draft',@@ -126,7 +126,7 @@ export const WORKFLOWS_MCP_TOOLS: McpToolSummary[] = [{name: 'workflows-blast-radius',description:- "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes. The response's confirm_token signs the sized audience - pass it to workflows-run-batch along with the acknowledged count; it expires in 15 minutes and goes stale if the audience filters change.",+ "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch, and before schedule-create on a workflow with a 'batch' trigger. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed until they say yes. A 'schedule' trigger has no audience, so skip this and call schedule-create directly. The response's confirm_token signs the sized audience - pass it to workflows-run-batch along with the acknowledged count; it expires in 15 minutes and goes stale if the audience filters change.",},{name: 'workflows-run-batch',@@ -136,7 +136,7 @@ export const WORKFLOWS_MCP_TOOLS: McpToolSummary[] = [{name: 'workflows-schedule-create',description:- "Attach a recurring RRULE schedule to a batch workflow so it re-broadcasts to its trigger audience on a cadence (iCalendar RRULE, e.g. 'FREQ=WEEKLY;BYDAY=MO'; at most one occurrence per hour). Only valid on workflows with a 'batch' trigger, and the workflow must already be active (workflows-enable first). Every firing sends real messages: run workflows-blast-radius, STOP and get the user's explicit confirmation of the count, then pass both acknowledged_affected_count and the confirm_token from that same preview — the API rejects the call without a fresh token (15-minute expiry, stale if the audience filters change). For a one-off send use workflows-run-batch; to change an existing schedule use workflows-update-schedule (schedule IDs appear in workflows-get's 'schedules').",+ "Attach a recurring RRULE schedule to a workflow with a 'batch' or 'schedule' trigger (iCalendar RRULE, e.g. 'FREQ=WEEKLY;BYDAY=MO'; at most one occurrence per hour). A 'schedule' trigger runs once per occurrence with no audience: pass rrule, starts_at and timezone and you are done. A 'batch' trigger re-broadcasts to its trigger audience on every firing, so the workflow must already be active (workflows-enable first) and you must run workflows-blast-radius, STOP and get the user's explicit confirmation of the count, then pass both acknowledged_affected_count and the confirm_token from that same preview — the API rejects a batch schedule without a fresh token (15-minute expiry, stale if the audience filters change). For a one-off send use workflows-run-batch; to change an existing schedule use workflows-update-schedule (schedule IDs appear in workflows-get's 'schedules').",},]@@ -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}`), 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.',+ '# 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` or `schedule` 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`. A `batch` trigger fans out to a person audience, so scheduling it needs the `workflows-blast-radius` preview and its confirm token; a `schedule` trigger runs once per occurrence with no audience, so schedule it directly. 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 broadcast is a `batch` trigger plus a schedule. Editing `config.filters` pauses any schedule attached to it, since the confirmed recipient count no longer holds - preview again and re-create the cadence.\n- `schedule` — `{ "type": "schedule" }`. One person-less run per occurrence, for jobs that act on their own (for example a "Create AI task" step). Attach the cadence with `workflows-schedule-create`; no audience preview is needed. Changing this trigger to `batch` pauses any schedule already attached, because that cadence was never sized against an audience - re-create it after the blast-radius preview.\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/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex 7c09ac2c068d..d5fc0f002898 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -145,7 +145,7 @@ tools:first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on realpeople, and further content edits stage as a draft you must publish (workflows-publish) to take effect.Provide an actions array with exactly one type='trigger' (config.type:- event|webhook|manual|batch|tracking_pixel) plus action nodes+ event|webhook|manual|batch|schedule|tracking_pixel) plus action nodes(function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...)connected by edges. A webhook or manual trigger also needs config.template_id set to the literal'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it@@ -161,8 +161,9 @@ tools:not put one shared current_value condition in top-level properties. A 'batch' trigger broadcasts to anaudience (config.filters.properties: person-property conditions and/or cohort references), one run permatching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with- workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is- unsupported; reject it and explain why.+ workflows-schedule-create. A 'schedule' trigger has no audience: it runs once per occurrence, so attach its+ cadence with workflows-schedule-create and skip the audience preview. Behavioral targeting ('did event X at+ least N times over the last M days') is unsupported; reject it and explain why.ui_app: workflowworkflows-discard-draft:operation: hog_flows_discard_draft_creatediff --git a/products/workflows/skills/building-workflows/SKILL.md b/products/workflows/skills/building-workflows/SKILL.mdindex d73da80c6b39..8e634678eb61 100644--- a/products/workflows/skills/building-workflows/SKILL.md+++ b/products/workflows/skills/building-workflows/SKILL.md@@ -19,7 +19,7 @@ Work the workflow through these stages. Don't jump straight to enabling it.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.-7. **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.+7. **Dispatch (batch/schedule only).** A `batch` or `schedule` 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`. A `batch` trigger fans out to a person audience, so scheduling it needs the `workflows-blast-radius` preview and its confirm token; a `schedule` trigger runs once per occurrence with no audience, so schedule it directly. Confirm with `workflows-get` that `status=='active'` _and_ its read-only `schedules` field has an active entry.8. **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).Full tool catalog, grouped by job: [references/lifecycle-and-debugging.md](references/lifecycle-and-debugging.md).diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.mdindex dd5dd6c72efe..862caf1eee8c 100644--- a/products/workflows/skills/building-workflows/references/graph-schema.md+++ b/products/workflows/skills/building-workflows/references/graph-schema.md@@ -71,7 +71,8 @@ Discriminated on `config.type`:- `webhook` — a POST whose body you control: `"inputs": { "event": { "value": "{request.body.event}" }, "distinct_id": { "value": "{request.body.distinct_id}" } }`.- `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.+- `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 broadcast is a `batch` trigger plus a schedule. Editing `config.filters` pauses any schedule attached to it, since the confirmed recipient count no longer holds - preview again and re-create the cadence.+- `schedule` — `{ "type": "schedule" }`. One person-less run per occurrence, for jobs that act on their own (for example a "Create AI task" step). Attach the cadence with `workflows-schedule-create`; no audience preview is needed. Changing this trigger to `batch` pauses any schedule already attached, because that cadence was never sized against an audience - re-create it after the blast-radius preview.- `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/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 55805302c1eb..ae087eb85995 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -12072,7 +12072,7 @@"feature_flag": "engineering-analytics"},"workflows-create": {- "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.",+ "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|schedule|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. A 'schedule' trigger has no audience: it runs once per occurrence, so attach its cadence with workflows-schedule-create and skip the audience preview. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.","category": "Workflows","feature": "workflows","summary": "Create workflow",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 8c1f6b1346a4..b5a2753fe359 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -12714,7 +12714,7 @@}},"workflows-blast-radius": {- "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes. The response's confirm_token signs the sized audience - pass it to workflows-run-batch along with the acknowledged count; it expires in 15 minutes and goes stale if the audience filters change.",+ "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch, and before schedule-create on a workflow with a 'batch' trigger. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed until they say yes. A 'schedule' trigger has no audience, so skip this and call schedule-create directly. The response's confirm_token signs the sized audience - pass it to workflows-run-batch along with the acknowledged count; it expires in 15 minutes and goes stale if the audience filters change.","category": "Workflows","feature": "workflows","summary": "Size workflow audience",@@ -12728,7 +12728,7 @@}},"workflows-create": {- "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.",+ "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|schedule|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. A 'schedule' trigger has no audience: it runs once per occurrence, so attach its cadence with workflows-schedule-create and skip the audience preview. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.","category": "Workflows","feature": "workflows","summary": "Create workflow",@@ -13022,7 +13022,7 @@}},"workflows-schedule-create": {- "description": "Attach a recurring RRULE schedule to a batch workflow so it re-broadcasts to its trigger audience on a cadence (iCalendar RRULE, e.g. 'FREQ=WEEKLY;BYDAY=MO'; at most one occurrence per hour). Only valid on workflows with a 'batch' trigger, and the workflow must already be active (workflows-enable first). Every firing sends real messages: run workflows-blast-radius, STOP and get the user's explicit confirmation of the count, then pass both acknowledged_affected_count and the confirm_token from that same preview — the API rejects the call without a fresh token (15-minute expiry, stale if the audience filters change). For a one-off send use workflows-run-batch; to change an existing schedule use workflows-update-schedule (schedule IDs appear in workflows-get's 'schedules').",+ "description": "Attach a recurring RRULE schedule to a workflow with a 'batch' or 'schedule' trigger (iCalendar RRULE, e.g. 'FREQ=WEEKLY;BYDAY=MO'; at most one occurrence per hour). A 'schedule' trigger runs once per occurrence with no audience: pass rrule, starts_at and timezone and you are done. A 'batch' trigger re-broadcasts to its trigger audience on every firing, so the workflow must already be active (workflows-enable first) and you must run workflows-blast-radius, STOP and get the user's explicit confirmation of the count, then pass both acknowledged_affected_count and the confirm_token from that same preview — the API rejects a batch schedule without a fresh token (15-minute expiry, stale if the audience filters change). For a one-off send use workflows-run-batch; to change an existing schedule use workflows-update-schedule (schedule IDs appear in workflows-get's 'schedules').","category": "Workflows","feature": "workflows","summary": "Schedule workflow runs",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 0e74e8361eac..33747edd5a62 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -754,7 +754,7 @@}},"workflows-blast-radius": {- "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes. The response's confirm_token signs the sized audience - pass it to workflows-run-batch along with the acknowledged count; it expires in 15 minutes and goes stale if the audience filters change.",+ "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch, and before schedule-create on a workflow with a 'batch' trigger. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed until they say yes. A 'schedule' trigger has no audience, so skip this and call schedule-create directly. The response's confirm_token signs the sized audience - pass it to workflows-run-batch along with the acknowledged count; it expires in 15 minutes and goes stale if the audience filters change.","category": "Workflows","feature": "workflows","summary": "Size workflow audience",@@ -782,7 +782,7 @@}},"workflows-schedule-create": {- "description": "Attach a recurring RRULE schedule to a batch workflow so it re-broadcasts to its trigger audience on a cadence (iCalendar RRULE, e.g. 'FREQ=WEEKLY;BYDAY=MO'; at most one occurrence per hour). Only valid on workflows with a 'batch' trigger, and the workflow must already be active (workflows-enable first). Every firing sends real messages: run workflows-blast-radius, STOP and get the user's explicit confirmation of the count, then pass both acknowledged_affected_count and the confirm_token from that same preview — the API rejects the call without a fresh token (15-minute expiry, stale if the audience filters change). For a one-off send use workflows-run-batch; to change an existing schedule use workflows-update-schedule (schedule IDs appear in workflows-get's 'schedules').",+ "description": "Attach a recurring RRULE schedule to a workflow with a 'batch' or 'schedule' trigger (iCalendar RRULE, e.g. 'FREQ=WEEKLY;BYDAY=MO'; at most one occurrence per hour). A 'schedule' trigger runs once per occurrence with no audience: pass rrule, starts_at and timezone and you are done. A 'batch' trigger re-broadcasts to its trigger audience on every firing, so the workflow must already be active (workflows-enable first) and you must run workflows-blast-radius, STOP and get the user's explicit confirmation of the count, then pass both acknowledged_affected_count and the confirm_token from that same preview — the API rejects a batch schedule without a fresh token (15-minute expiry, stale if the audience filters change). For a one-off send use workflows-run-batch; to change an existing schedule use workflows-update-schedule (schedule IDs appear in workflows-get's 'schedules').","category": "Workflows","feature": "workflows","summary": "Schedule workflow runs",diff --git a/services/mcp/src/tools/workflows/batch.ts b/services/mcp/src/tools/workflows/batch.tsindex 13aa13ac2b5f..f6107a021d24 100644--- a/services/mcp/src/tools/workflows/batch.ts+++ b/services/mcp/src/tools/workflows/batch.ts@@ -126,7 +126,9 @@ export const workflowsRunBatch = (): ToolBase<typeof RunBatchSchema, unknown> =>})const ScheduleCreateSchema = z.object({- workflow_id: z.string().describe('ID of the batch workflow to attach the recurring schedule to.'),+ workflow_id: z+ .string()+ .describe('ID of the workflow to attach the recurring schedule to. Its trigger must be batch or schedule.'),rrule: z.string().describe("iCalendar RRULE (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour."),@@ -135,17 +137,19 @@ const ScheduleCreateSchema = z.object({acknowledged_affected_count: z.number().int()+ .optional().describe(- 'The affected-user count from workflows-blast-radius that you showed the user AND they explicitly ' +- 'confirmed before scheduling. Each firing re-broadcasts to the audience at that time; rejected if it ' +- 'no longer matches.'+ 'Batch triggers only: the affected-user count from workflows-blast-radius that you showed the user ' ++ 'AND they explicitly confirmed before scheduling. Each firing re-broadcasts to the audience at that ' ++ 'time; rejected if it no longer matches. Omit for a schedule trigger, which has no audience.'),confirm_token: z.string()+ .optional().describe(- 'The confirm_token from the same workflows-blast-radius preview whose count the user confirmed. ' +- 'The API rejects schedule creation without it, and it goes stale when the audience filters change ' +- 'or after 15 minutes - re-preview to refresh.'+ 'Batch triggers only: the confirm_token from the same workflows-blast-radius preview whose count the ' ++ 'user confirmed. The API rejects a batch schedule without it, and it goes stale when the audience ' ++ 'filters change or after 15 minutes - re-preview to refresh. Omit for a schedule trigger.'),variables: z.record(z.string(), z.unknown())@@ -160,34 +164,45 @@ export const workflowsScheduleCreate = (): ToolBase<typeof ScheduleCreateSchema,const projectId = await context.stateManager.getProjectId()const { status, trigger } = await fetchWorkflow(context, projectId, params.workflow_id)- if (trigger.type !== 'batch') {+ if (trigger.type !== 'batch' && trigger.type !== 'schedule') {throw new Error(- `workflows-schedule-create only applies to workflows with a 'batch' trigger (this one is ` +- `'${trigger.type ?? 'unknown'}').`+ `workflows-schedule-create only applies to workflows with a 'batch' or 'schedule' trigger (this ` ++ `one is '${trigger.type ?? 'unknown'}').`)}- // Require the workflow to be active before scheduling. A draft's trigger can still be edited in- // place, so scheduling a draft would let the audience be broadened after you acknowledged it (the- // scheduler uses the trigger's filters at fire time). On an active workflow an MCP trigger edit only- // stages a draft, so the acknowledged audience can't change without an explicit publish.- if (status !== 'active') {- throw new Error(- `Workflow is not active (status '${status ?? 'unknown'}') — enable it with workflows-enable before ` +- `scheduling. Scheduling a draft would let the audience change after you sized it.`- )+ // A schedule trigger fires one person-less run per occurrence, so there is no audience to+ // size or confirm. Only a batch trigger fans out to persons and needs the blast-radius step.+ let confirmToken: string | undefined+ if (trigger.type === 'batch') {+ // Require the workflow to be active before scheduling. A draft's trigger can still be edited in+ // place, so scheduling a draft would let the audience be broadened after you acknowledged it (the+ // scheduler uses the trigger's filters at fire time). On an active workflow an MCP trigger edit only+ // stages a draft, so the acknowledged audience can't change without an explicit publish.+ if (status !== 'active') {+ throw new Error(+ `Workflow is not active (status '${status ?? 'unknown'}') — enable it with workflows-enable before ` ++ `scheduling. Scheduling a draft would let the audience change after you sized it.`+ )+ }+ if (params.acknowledged_affected_count === undefined || params.confirm_token === undefined) {+ throw new Error(+ 'A batch trigger schedules a recurring broadcast: preview the audience with workflows-blast-radius, ' ++ 'confirm the count with the user, then pass acknowledged_affected_count and confirm_token.'+ )+ }+ const { affected, limit } = await sizeAudience(context, projectId, triggerFilters(trigger))+ assertAcknowledged(affected, params.acknowledged_affected_count, limit)+ confirmToken = params.confirm_token}- const { affected, limit } = await sizeAudience(context, projectId, triggerFilters(trigger))- assertAcknowledged(affected, params.acknowledged_affected_count, limit)-return await context.api.request({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.workflow_id))}/schedules/`,body: {rrule: params.rrule,starts_at: params.starts_at,- confirm_token: params.confirm_token,+ ...(confirmToken !== undefined ? { confirm_token: confirmToken } : {}),...(params.timezone !== undefined ? { timezone: params.timezone } : {}),...(params.variables !== undefined ? { variables: params.variables } : {}),},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.jsonindex 97d739b964c3..26e9efb4d9e5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.json@@ -2,13 +2,13 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"acknowledged_affected_count": {- "description": "The affected-user count from workflows-blast-radius that you showed the user AND they explicitly confirmed before scheduling. Each firing re-broadcasts to the audience at that time; rejected if it no longer matches.",+ "description": "Batch triggers only: the affected-user count from workflows-blast-radius that you showed the user AND they explicitly confirmed before scheduling. Each firing re-broadcasts to the audience at that time; rejected if it no longer matches. Omit for a schedule trigger, which has no audience.","maximum": 9007199254740991,"minimum": -9007199254740991,"type": "integer"},"confirm_token": {- "description": "The confirm_token from the same workflows-blast-radius preview whose count the user confirmed. The API rejects schedule creation without it, and it goes stale when the audience filters change or after 15 minutes - re-preview to refresh.",+ "description": "Batch triggers only: the confirm_token from the same workflows-blast-radius preview whose count the user confirmed. The API rejects a batch schedule without it, and it goes stale when the audience filters change or after 15 minutes - re-preview to refresh. Omit for a schedule trigger.","type": "string"},"rrule": {@@ -32,10 +32,10 @@"type": "object"},"workflow_id": {- "description": "ID of the batch workflow to attach the recurring schedule to.",+ "description": "ID of the workflow to attach the recurring schedule to. Its trigger must be batch or schedule.","type": "string"}},- "required": ["workflow_id", "rrule", "starts_at", "acknowledged_affected_count", "confirm_token"],+ "required": ["workflow_id", "rrule", "starts_at"],"type": "object"}diff --git a/services/mcp/tests/unit/workflows-batch-handlers.test.ts b/services/mcp/tests/unit/workflows-batch-handlers.test.tsindex 68f7dee153c7..963eac4267c8 100644--- a/services/mcp/tests/unit/workflows-batch-handlers.test.ts+++ b/services/mcp/tests/unit/workflows-batch-handlers.test.ts@@ -273,10 +273,38 @@ describe('workflows batch handlers', () => {expect(calls(request).some((c) => c.path.endsWith('/schedules/'))).toBe(false)})- it('rejects a non-batch trigger (schedule trigger no longer supported)', async () => {+ it('creates the schedule for a schedule trigger without sizing an audience', async () => {const { context, request } = createMockContext({trigger: { type: 'schedule' },blastRadius: { affected: 1, total: 1 },+ status: 'draft',+ })++ const result = await scheduleCreateTool.handler(context, {+ workflow_id: 'wf-1',+ rrule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=MO',+ starts_at: '2026-06-01T09:00:00Z',+ timezone: 'Europe/Lisbon',+ })++ expect(calls(request).some((c) => c.path.endsWith('/user_blast_radius/'))).toBe(false)+ const schedCall = calls(request).find((c) => c.path.endsWith('/schedules/'))+ expect(schedCall).toMatchObject({+ method: 'POST',+ body: {+ rrule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=MO',+ starts_at: '2026-06-01T09:00:00Z',+ timezone: 'Europe/Lisbon',+ },+ })+ expect(schedCall?.body).not.toHaveProperty('confirm_token')+ expect(result).toMatchObject({ id: 'sched-1' })+ })++ it('rejects a batch trigger scheduled without the blast-radius confirmation', async () => {+ const { context, request } = createMockContext({+ trigger: { type: 'batch', filters: BATCH_FILTERS },+ blastRadius: { affected: 3, total: 100 },})await expect(@@ -284,10 +312,24 @@ describe('workflows batch handlers', () => {workflow_id: 'wf-1',rrule: 'FREQ=DAILY;INTERVAL=1',starts_at: '2026-06-01T00:00:00Z',- acknowledged_affected_count: 1,- confirm_token: 'unused',})- ).rejects.toThrow(/batch/)+ ).rejects.toThrow(/workflows-blast-radius/)+ expect(calls(request).some((c) => c.path.endsWith('/schedules/'))).toBe(false)+ })++ it('rejects a trigger that cannot be scheduled', async () => {+ const { context, request } = createMockContext({+ trigger: { type: 'event' },+ blastRadius: { affected: 1, total: 1 },+ })++ await expect(+ scheduleCreateTool.handler(context, {+ workflow_id: 'wf-1',+ rrule: 'FREQ=DAILY;INTERVAL=1',+ starts_at: '2026-06-01T00:00:00Z',+ })+ ).rejects.toThrow(/batch.*schedule/)expect(calls(request).some((c) => c.path.endsWith('/schedules/'))).toBe(false)})})