Designing a rule that fires reliably, fires only when it should, and respects every guardrail (consent, quiet hours, rate limits) is a craft. This article is the playbook: how to think about a rule, how to write its condition DSL, how to wire multi-step flows, how to dry-run before publishing, and the top 10 starter rules every clinic should have on day one. Combined with the handlers library reference, you can author a reliable rule in under 30 minutes.
Where it lives#
- Automations → Built-in automations: the rules list and designer.
- Automations → Custom automations → New automation: the rule designer (form-based today, visual canvas Coming soon).
- Reports → Automations → Run history: every fire, payload, outcome.
- Automations → Custom automations → Preview: test a rule with sample payload without sending.
The rule shape#
- Trigger: event the system emits (or scheduled cron).
- Conditions: filter the trigger to specific cases.
- Actions: what to do (one or more, optionally multi-step).
- Rate limit: max fires per period to prevent flooding.
- Schedule constraints: respect quiet hours, working hours.
- Marketing consent gate: enforced on marketing-category actions.
Trigger types#
Event triggers#
The system emits events as things happen. Common triggers:
- session.created.v2 / arrived.v2 / completed.v2 / cancelled.v2 / no_show.v2
- invoice.created.v2 / paid.v2 / voided.v2
- lead.created.v2 / stage_changed.v2 / lost.v2
- patient.created.v2
- messaging.message.received.v2
- clinical_tests.result.posted.v2 / critical.v2
The examples above are illustrative. Before saving, verify that the trigger name you pick is registered in the picker. Names like inventory.stock.below_reorder_point.v1 and customers.consent.signed.v2 are in the schema but do not yet have a listener wired to the automation engine. A preview evaluates a sample payload; it does not prove that the real event is wired. Confirm the event arrives in Activity during a controlled live test.
Scheduled (cron) triggers#
- Daily at a specific time.
- Weekly on a specific day.
- Monthly on a specific date.
- Custom cron expression.
- Useful for recurring reminders, reports, end-of-day checks.
Manual trigger#
- Admin fires the rule from the rule detail page.
- Useful for one-time campaigns or testing.
Condition DSL#
Structure#
- Conditions combine with AND, OR, NOT.
- Nested groups allowed.
- Each leaf condition: field, operator, value.
Operators#
eq: equal.ne: not equal.gt: greater than.gte: greater than or equal.lt: less than.lte: less than or equal.in: value in list.contains: substring or list contains.starts_with: string starts with.matches: regex match.is_null: value is null or missing.is_empty: empty list or empty string.is_true: boolean true.
Field paths#
- Use dot notation:
patient.tags,session.service.category,invoice.total. - Resolves against event payload + patient context + clinic context.
Examples#
patient.marketing_consent = true AND invoice.total > 500session.type IN ['SERVICE', 'CONSULTATION'] AND NOT patient.tags CONTAINS 'do_not_message'lead.source = 'meta' AND lead.created_at >= now() - 24h
Multi-step rules#
When to use multi-step#
- Sequences over time (T+0 welcome, T+3 follow-up, T+7 offer).
- Branching by condition (paid > 1000 → manager email, else routine).
- Wait for downstream event.
- Parallel actions (send WhatsApp AND create task at once).
Step types#
- action: execute a handler.
- delay: wait N minutes / hours / days.
- condition: evaluate, branch.
- branch: multi-way split.
- parallel: execute branches concurrently.
Example: lead nurture sequence#
- Trigger: lead.created.v2 with condition source = meta.
- Action: send_whatsapp welcome template.
- Delay: 24 hours.
- Condition: lead.stage = open (not converted).
- Action: send_whatsapp follow-up template.
- Delay: 72 hours.
- Condition: lead.stage = open AND lead.last_contacted_at is_null.
- Action: create_task on assigned rep "Call lead now".
Rate limit math#
Per-rule rate limit#
- Cap fires per rule per period.
- Example: max 10 fires per hour.
- Over-cap fires marked rate_limited in ExecutionLog.
- Protects against runaway rules.
Per-recipient daily cap (Coming soon)#
- Cap messages per patient per day across all rules.
- Default 3 transactional + 1 marketing.
- Hit cap: defer to next eligible window.
- Patient quiet hours respected.
Send budget cap (Coming soon)#
- Monthly tenant send budget cap.
- WhatsApp + SMS + email spend visible.
- Approaching cap: alert.
- At cap: marketing pauses.
Quiet hours and working hours#
Do not assume that a messaging action waits for business hours. The generic dispatcher has no universal quiet-hours deferral, per-patient window, or urgent bypass. Set the automation's schedule explicitly. Post-visit review requests are a separate flow with their own tenant quiet-hours guard.
Marketing consent gate#
Marketing sends must respect the patient's opt-out and the selected channel's safeguards. Use actions and templates appropriate to the message purpose. There is no automatic WhatsApp-to-SMS-to-email fallback chain: requesting another action is a separate send, not proof that the first delivery failed.
Testing before you publish#
Preview#
- Save the rule disabled while you prepare it.
- Open it and click Preview. The engine runs the persisted version against a sample payload.
- The drawer returns per-action results. Adjust, save, Preview again.
Limited-scope test#
- Add a condition that pins the rule to a test patient or test branch.
- Trigger a real event in that scope. Verify the action ran.
- Remove the test condition before opening it up.
What we do not have yet#
- Preview resolves actions without sending or writing their live side effects.
- Drafts are not shipped. Keep the rule disabled until it is ready.
- Backfill is not shipped. There is no "run this rule on the last 30 days of events" button. The closest thing is Preview on a single payload.
Preview vs dry-run vs backfill#
Three concepts often get confused. Here is what each one means today:
- Preview evaluates the saved rule against one sample payload in dry-run mode.
- Live execution dispatches the configured actions and can send messages or change records.
- Backfill does not exist. There is no "run on the last N days of real events" button. The only way to re-fire is to wait for the real event to happen again.
Use Preview to inspect the resolved values first. Then use a limited-scope live test to confirm provider delivery; a preview cannot prove that a real event will arrive or that a provider will accept a message.
Replicating a rule across tenants#
Every custom automation lives in the tenant's own schema. There is no one-click clone-to-other-tenant button. The manual path:
- From the source tenant, ask support to export the rule's JSON (trigger_event, conditions, actions, schedule_type, custom_schedule, rate_limit_count, rate_limit_period_minutes).
- In the target tenant, open Automations → Custom automations → New automation and paste fields in, or POST the JSON directly to the API.
- Preview on the target tenant before enabling. The payload variables in templates might reference customer or branch ids that don't exist on the new tenant.
For multi-clinic groups that need the same rule across every tenant, the right pattern is to ask engineering to promote the rule to a locked catalog handler. Then enabling it on a new tenant is a single toggle.
Audit and run history#
- Every fire logged in ExecutionLog with status.
- Payload captured for debugging.
- correlation_id ties to source event in EventAuditTrail.
- Per-rule volume metric.
- Failed actions: investigation queue.
Top 10 starter rules every clinic should have#
1. Welcome new patient#
- Trigger: patient.created.v2.
- Action: send_whatsapp welcome template.
2. Appointment confirmation#
- Trigger: session.created.v2.
- Action: send_whatsapp confirmation template.
3. T-24h reminder#
- Trigger: scheduled relative to session start (-24h).
- Action: send reminder template.
4. T-2h reminder#
- Trigger: scheduled relative to session start (-2h).
- Action: send reminder template.
5. No-show follow-up#
- Trigger: session.no_show.v2.
- Action: create_task on responsible rep "Call to reschedule".
6. Lead SLA breach#
- Trigger: lead.sla_missed.v2.
- Action: notify manager + auto-reassign.
7. Invoice payment reminder D+3#
- Trigger: scheduled cron checking unpaid invoices age 3 days.
- Action: send_whatsapp payment reminder template.
8. Receipt on payment#
- Trigger: invoice.paid.v2.
- Action: send_whatsapp + send_email receipt.
9. Package expiry warning#
- Trigger: scheduled cron T-30 days.
- Condition: package credits remaining > 0.
- Action: send_whatsapp expiry warning template.
10. Critical lab result alert#
- Trigger: clinical_tests.result.critical.v2.
- Action: create_task with must-acknowledge gate on ordering provider + push notification.
Governance discipline#
- Publishing a rule is a single save. There is no draft state today.
- There is no version history per rule. Once you save, the prior version is gone.
- Use the per-rule rate limit on every new rule. It is the only safety net against a runaway misconfiguration.
- Quarterly review: which rules earn their keep, which to retire.
Coming soon#
- Visual drag-drop rule builder.
- Step-level test runner (preview payload + rendered template).
- AI-suggested rules from event patterns.
- Template marketplace per clinic type.
- Per-recipient daily cap (across all rules).
- Send budget cap with alert.
- Backfill UI with dry-run preview.
- A/B variant testing.
- Branch-scoped automation.
- Config versioning + rollback.
- Sandbox tenant flag for staging rules.
- Hold-out audience for measurement.
- Conversion-tracking exit ("stop if invoice paid").
- Manager approval gate for publishing live rules.
Common mistakes#
- No conditions: rule fires for everyone, wrong cohort hit.
- Marketing rules without consent gate: regulator complaint.
- Skipping dry-run: first live fire is to the wrong cohort.
- Wait blocks in wrong unit: 3 instead of 3 hours.
- Hardcoded template instead of variable: every message identical.
- Too many rules: patients blasted, opt out.
- Rule depends on a deprecated event field: silently never fires.
- Forgotten quarterly review: stale rules pollute.
- Trigger picks the wrong event: "session done" can fire from manager override, not just service report submit.
- Webhook to private IP: SSRF guard blocks; misconfiguration.
How rule design connects#
- Automation engine: executes the rule.
- Handlers library: actions called by the rule.
- Event bus: triggers consume events.
- Patient consent: gates marketing actions.
- Notifications: rule actions land in channels.
- Tasks: create_task is the bridge.
- Reports: per-rule volume and outcome.
- Audit log: every fire captured.
