Table of Contents
- Executive Summary
- Current State Assessment
- Industry Research & Pattern Analysis
- Gap Analysis: PF Business Automation
- Gap Analysis: FW Workflow Engine
- Enhanced Recommendations: Platform Foundation
- Enhanced Recommendations: FW Workflow Engine
- Proposed Architecture: Durable Workflow Execution
- Proposed Architecture: Business Rules Engine
- Proposed Architecture: Event Mesh & Dead Letter Queue
- FHIR Workflow Alignment
- Cross-Core Business Process Catalog
- Implementation Roadmap
- Risk Assessment
- References
- Appendix A: Supabase Queues (pgmq) — Enhanced Execution Architecture
- Appendix B: json-rules-engine — Concrete Business Rules Implementation
- Appendix C: FHIR Behavioral Health Alignment — Extended Research
- Appendix D: Industry Sources
1. Executive Summary
The Encore OS platform has a strong foundation for forms (FW-01/02), automation rules (FW-03), visual workflows (FW-06), event publishing (FW-16), and approval chains (FW-34). However, the deep dive identified critical gaps in execution durability, event delivery guarantees, and business rules orchestration that must be addressed before production-grade business automation. This research identifies 18 enhanced recommendations organized into three tracks:
Key insight: The platform’s Supabase-native architecture is well-suited for a durable execution model using
pg_cron + Edge Functions + fw_workflow_executions as the state store — without introducing external orchestration tools (Temporal, Inngest). This keeps the stack unified while achieving the reliability guarantees healthcare workflows demand.
2. Current State Assessment
2.1 Platform Foundation (PF) — Business Automation Capabilities
2.2 Forms & Workflow (FW) — Automation Capabilities
2.3 Critical Gaps (from Deep Dive)
- Queued executions never processed —
fw_process_domain_event()createsfw_workflow_executionsrows withstatus = 'queued'but no worker picks them up. - Form submission → automation invocation path unclear — No documented or implemented bridge between
fw_form_submissionsINSERT andautomation-executorinvocation. - Dual event paths not unified — Table-driven (fw_domain_events) vs HTTP (event-consumer) with no clear routing documentation.
- XState workflow machine disconnected — Client-side step machine exists but is not wired to server-side execution.
- No dead letter queue — Failed events/executions have no recovery path.
- No event schema versioning — Event payloads can change without consumer awareness.
3. Industry Research & Pattern Analysis
3.1 Healthcare Workflow Automation — Industry Patterns
Behavioral health ERP systems require workflow automation patterns that differ from general-purpose ERP:
Key industry insight: Leading healthcare platforms (Epic, Cerner/Oracle Health, athenahealth) implement workflow as a state machine with durable execution — not as simple trigger→action rules. The workflow engine must survive restarts, handle long-running processes (days/weeks for authorizations), and support human-in-the-loop pauses.
3.2 Event-Driven Architecture — Best Practices
At-least-once delivery with idempotent consumers is the proven pattern for healthcare event systems:
Supabase-specific patterns:
3.3 Durable Execution Patterns (Temporal/Inngest/Trigger.dev)
Modern workflow orchestration tools share common patterns that can be adapted to a Supabase-native engine:
Recommendation: Do NOT introduce Temporal or Inngest as dependencies. Instead, build a Supabase-native durable execution engine using the patterns above. The
fw_workflow_executions table is already the right foundation — it needs a worker loop and step-level checkpointing.
3.4 XState v5 — Workflow Orchestration Assessment
XState 5 is excellent for:- Client-side UI state (form wizards, multi-step dialogs)
- Visualization of state transitions
- Type-safe state machines with TypeScript
- Server-side durable execution (no built-in persistence, no distributed execution)
- Long-running workflows (days/weeks) — XState machines are in-memory
- Multi-tenant execution — no built-in tenant isolation
automation-executor + fw_workflow_executions model. If a future need arises for complex client-side approval UIs, XState can drive the UI while the server remains the source of truth.
3.5 FHIR Workflow Patterns — Behavioral Health Relevance
HL7 FHIR defines workflow resources that map to Encore OS concepts:
Behavioral health specific:
- ASAM Criteria workflow: Assessment → Level of Care determination → Authorization → Admission — maps to a multi-step workflow with clinical decision support
- Treatment plan review cycles: 30/60/90-day reviews with escalation — maps to date-relative triggers + approval chains
- Discharge planning: Multi-step process spanning CL, RH, FA, CE — maps to cross-core choreography
- Workflow template definitions should support
actionarrays withtrigger,condition,input,output(mirroring PlanDefinition.action) - Tasks created by workflows should carry
intent,status,priority,for(patient reference) fields
3.6 Business Rules Engines — Healthcare Application
Healthcare business rules operate at multiple levels:
DMN (Decision Model and Notation) provides a standard for expressing business rules as decision tables:
fw_decision_tables entity linked to automation rules or workflow condition nodes.
4. Gap Analysis: PF Business Automation
4.1 Missing Platform Capabilities for Business Automation
4.2 PF Modules Critical for Business Automation (Spec-Only, Need Implementation)
5. Gap Analysis: FW Workflow Engine
5.1 Execution Model Gaps
5.2 Event System Gaps
6. Enhanced Recommendations: Platform Foundation
R-PF-01: Business Process Registry (NEW — PF-82)
Priority: HIGH Rationale: As automation rules and workflows grow across cores, operators need a single view of “what automated processes exist, what triggers them, and what they do.” Proposed capabilities:- Registry table
pf_business_processeslinking tofw_automation_rulesand workflow definitions - Each process has: name, description, owning core, trigger summary, status (active/draft/disabled)
- Dashboard page showing all active business processes with execution stats
- Search/filter by core, trigger type, status
- Impact analysis: “If I disable this process, what downstream effects occur?”
R-PF-02: SLA Management Platform Layer (NEW — PF-83)
Priority: HIGH Rationale: Healthcare operations have strict SLAs — prior authorization response times, treatment plan review deadlines, discharge notification windows. FW-35 defines per-workflow SLAs; the platform needs a unified SLA tracking service. Proposed capabilities:- Platform service
@/platform/slaexposingcreateSLA(),checkSLA(),escalateSLA()hooks - SLA definition table
pf_sla_definitionswith: entity type, metric, threshold, escalation chain - SLA instance table
pf_sla_instancestracking: start time, deadline, current status, escalation level pg_cronjob checking approaching/breached SLAs and triggering escalation workflows- Dashboard widget showing SLA compliance metrics per core
R-PF-03: Business Calendar Service (NEW — PF-84)
Priority: MEDIUM Rationale: Workflows that involve deadlines, SLAs, and scheduling need awareness of business hours, holidays, and staff availability. Currently, date-relative triggers (FW-16) use calendar days, not business days. Proposed capabilities:- Organization-scoped business calendars (
pf_business_calendars) - Business hour definitions (e.g., Mon-Fri 8am-6pm EST)
- Holiday management (federal, state, organization-specific)
- Utility functions:
addBusinessDays(),isBusinessHour(),nextBusinessDay() - Integration with FW-16 date-relative triggers to support “5 business days before discharge”
R-PF-04: Enhanced Task-Workflow Integration (PF-29 Enhancement)
Priority: HIGH Rationale: Tasks created by workflow automation should maintain a bidirectional link to the workflow execution for traceability and lifecycle management. Proposed changes:- Add
source_workflow_execution_idtopf_tasks(nullable FK tofw_workflow_executions) - Add
source_automation_rule_idtopf_tasks(nullable FK tofw_automation_rules) - When a workflow creates a task, task completion should optionally resume the waiting workflow step
- Task detail view shows workflow context (which step created it, what happens next)
- Workflow execution view shows linked tasks with their status
R-PF-05: Integration Hub Event Forwarding (PF-35 Enhancement)
Priority: MEDIUM Rationale: External systems (EHRs, clearinghouses, payer portals) need to receive domain events. PF-35 has outbound webhooks but they are not connected to the domain event system. Proposed changes:- Add
pf_event_subscriptionstable: integration_id, event_type_pattern, filter_conditions, delivery_config - When
fw_domain_eventsreceives an event, checkpf_event_subscriptionsfor matching subscriptions - Deliver via existing outbound webhook infrastructure (PF-35) with retry logic
- Event payload transformation templates per subscription
- Delivery tracking and DLQ for failed external deliveries
7. Enhanced Recommendations: FW Workflow Engine
R-FW-01: Durable Execution Worker (CRITICAL)
Priority: CRITICAL — Blocks all event-triggered automation Implements: FW-GA-01 (queued execution processing) Architecture (detailed in Section 8):pg_cronjob runs every 10 seconds- Calls
pg_netto invoke a new Edge Functionworkflow-executor-worker - Worker queries
fw_workflow_executionsfor rows withstatus IN ('queued', 'retry_pending')ANDnext_retry_at <= now() - For each execution, runs the workflow step-by-step via
automation-executorlogic - Updates execution status after each step (checkpointing)
- On failure, applies retry policy from FW-25 or moves to DLQ
R-FW-02: Dead Letter Queue (CRITICAL)
Priority: CRITICAL — Required for production reliability Proposed implementation:- New table
fw_dead_letter_queue: - Events/executions moved to DLQ after exhausting retry budget
- Admin UI for reviewing, retrying, or discarding DLQ items
- Alerting when DLQ depth exceeds threshold (via PF-10 notifications)
- DLQ items retain full context for debugging
R-FW-03: Step-Level Checkpointing (HIGH)
Priority: HIGH — Enables long-running workflows Proposed implementation:fw_execution_stepstable tracking each node execution within a workflow:- Worker resumes from last completed step on restart
- Each step is independently retryable without re-running completed steps
- Step output feeds into next step’s input (variable binding from FW-18)
R-FW-04: Decision Tables (MEDIUM)
Priority: MEDIUM — Enables configurable business rules Proposed implementation:- New entity
fw_decision_tables: - Integration with FW-17 Condition Builder as a “decision table” condition type
- Integration with FW-06 Workflow Builder as a “decision” node type
- UI for editing decision tables (spreadsheet-like grid)
- Hit policies following DMN standard:
- First: First matching rule wins
- Unique: Exactly one rule must match (error if multiple)
- Collect: All matching rules contribute to output
- Priority: Highest-priority matching rule wins
R-FW-05: Event Schema Registry (MEDIUM)
Priority: MEDIUM — Prevents breaking changes to event consumers Proposed implementation:- Extend
fw_workflow_eventswithpayload_schema(JSON Schema) andschema_version publishEvent()validates payload against registered schema before INSERT- Schema evolution rules: new fields are allowed (additive); removed fields require version bump
- Consumer documentation auto-generated from schema
- Breaking change detection in CI pipeline
R-FW-06: Execution Timeout & Watchdog (HIGH)
Priority: HIGH — Prevents resource leaks Proposed implementation:- Add
timeout_secondsto workflow definitions (default: 86400 = 24 hours) - Add
deadline_attofw_workflow_executions(set on creation:now() + timeout) pg_cronwatchdog job runs every 5 minutes, finds executions past deadline- Timed-out executions: status → ‘timed_out’, trigger compensation actions if defined
- Notification sent to workflow owner on timeout
R-FW-07: Event Correlation & Business Process Tracking (MEDIUM)
Priority: MEDIUM — Enables end-to-end business process visibility Proposed implementation:- Add
correlation_idtofw_domain_eventsandfw_workflow_executions - Business processes (e.g., “Patient Intake for John Doe”) share a correlation ID across all events and executions
- New view: “Business Process Timeline” showing all correlated events and workflow steps
- Enables questions like: “Show me everything that happened during this patient’s intake”
8. Proposed Architecture: Durable Workflow Execution
8.1 Architecture Diagram
8.2 Worker Execution Loop (Pseudocode)
8.3 Database Claim Function
8.4 Retry Policy Application
9. Proposed Architecture: Business Rules Engine
9.1 Decision Table Integration
9.2 Healthcare Business Rules Examples
Authorization Rules (FA/PM):
Staffing Rules (HR/RH):
Clinical Escalation Rules (CL):
These rules currently live in code or are ad-hoc. A decision table system makes them configurable, auditable, and tenant-specific without code deploys.
10. Proposed Architecture: Event Mesh & Dead Letter Queue
10.1 Unified Event Architecture
10.2 Event Schema Versioning Strategy
11. FHIR Workflow Alignment
11.1 Mapping to FHIR Resources
To future-proof interoperability, align workflow concepts with FHIR semantics:11.2 Behavioral Health Specific FHIR Extensions
12. Cross-Core Business Process Catalog
The following are the primary cross-core business processes that the workflow engine must support. Each process spans multiple cores and requires reliable, auditable automation.12.1 Patient Intake & Admission
- Auto-create intake appointment when referral accepted
- Auto-assign BHT based on census and specialization rules (decision table)
- Auto-initiate insurance verification on admission
- Auto-create treatment plan template on admission
- SLA: Insurance verification within 48 hours of admission
12.2 Treatment Plan Review Cycle
- Date-relative trigger: 7 days before review due → notify therapist
- Date-relative trigger: 3 days before review due → escalate to clinical director
- Auto-submit re-authorization when treatment plan updated (decision table for payer rules)
- SLA: Treatment plan review within 5 business days of due date
12.3 Discharge Planning
- Approval workflow: discharge requires clinical director sign-off (FW-34)
- Auto-generate final billing on discharge approval
- Auto-create room turnover task for facility management
- Auto-send aftercare referral packets
- SLA: Final billing submitted within 72 hours of discharge
12.4 Staff Onboarding & Credentialing
- Auto-create credentialing checklist on hire
- Date-relative trigger: 60 days before license expiration → notify HR
- Auto-assign required training modules based on role (decision table)
- Auto-activate provider in scheduling when all credentials verified
- SLA: Credentialing complete within 30 days of hire
12.5 Financial Cycle: Claims → Payment → Reconciliation
- Auto-generate charges on encounter completion (FW-03 trigger)
- Decision table: service code → fee schedule → charge amount by payer
- Auto-submit claims in batch (daily at 6pm via pg_cron)
- Auto-post ERA payments and flag discrepancies
- SLA: Claims submitted within 48 hours of service; denials worked within 14 days
13. Implementation Roadmap
Phase 1: Close the Execution Loop (Weeks 1-3) — CRITICAL
Exit criteria: Event-triggered workflows execute reliably with retry and DLQ.
Phase 2: Step-Level Reliability (Weeks 4-6) — HIGH
Exit criteria: Long-running workflows survive step failures and resume correctly.
Phase 3: Business Rules & SLA (Weeks 7-10) — HIGH
Exit criteria: Non-technical staff can configure authorization rules and SLA policies.
Phase 4: Event Architecture Maturity (Weeks 11-13) — MEDIUM
Exit criteria: Events are versioned, validated, and deliverable to external systems.
Phase 5: Advanced Orchestration (Weeks 14-18) — MEDIUM
Exit criteria: Complex multi-step, multi-approval, cross-core workflows run reliably.
14. Risk Assessment
15. References
Internal Documents
- CROSS_CORE_EVENTS_AUTOMATION_WORKFLOW_DEEP_DIVE.md — Foundation document
- EVENT_CONTRACTS.md — Event channels and payloads
- PLATFORM_INTEGRATION_LAYERS.md — Platform layer index
- API_CONTRACTS.md — Synchronous API contracts
- DATA_FLOW.md — Request lifecycle and automation flow
- FORMS_WIZARDS_WORKFLOWS_AUTOMATIONS_RECOMMENDATIONS.md (archived)
- REAL_TIME_ARCHITECTURE.md — Realtime layer architecture
src/platform/events/README.md— Platform events APIsrc/platform/workflow/README.md— Workflow visualization APIsrc/cores/fw/AGENTS.md— FW automation and workflow patterns
Specs Referenced (Existing)
- FW-03: Automation Engine
- FW-06: Advanced Workflow Builder
- FW-16: Event-Based Workflow Triggers
- FW-17: Advanced Condition Builder
- FW-25: Advanced Error Recovery & Retry (enriched 2026-03-15)
- FW-34: Approval Workflows
- FW-35: SLA Deadline Management
- FW-40: Quorum-Based Approval
- FW-41: Sub-Workflow Orchestration
- FW-43: Workflow Audit Trail & Compliance Reporting (enriched 2026-03-15)
- PF-04: Audit Logging
- PF-10: Notifications System
- PF-29: Unified Task System
- PF-35: Integration Hub
- PF-42: Rate Limiting & Throttling
- PF-47: Bulk Operations Framework
- PF-66: Platform Realtime Layer
New Specs Created from This Research (2026-03-15)
- FW-45: Decision Tables — from R-FW-07
- FW-46: Durable Execution Worker — from R-FW-01 (CRITICAL)
- FW-47: Dead Letter Queue — from R-FW-02
- FW-48: Execution Step Checkpointing — from R-FW-03
- FW-49: Execution Timeout & Watchdog — from R-FW-06
- FW-16 Phase 2: Event Schema Expansion — from R-FW-08
- PF-82: Business Process Registry — from PF recommendations
- PF-83: SLA Management Platform Layer — from PF recommendations
- PF-84: Business Calendar Service — from PF recommendations
- PF-85: Automation Observability Dashboard — from PF recommendations
- PF-10 Phase 5: Workflow-Aware Templates — from PF-10 enhancement
- PF-29 Phase 4: Task-Workflow Linking — from PF-29 enhancement
- PF-35 Phase 2: Event Forwarding — from PF-35 enhancement
- PF-36 Phase 3: Automation Health — from PF-36 enhancement
Architecture Documents Created from This Research
- EVENT_DELIVERY_ARCHITECTURE.md — from R-FW-12
Industry Standards & Research
- HL7 FHIR PlanDefinition (R4/R5) — Workflow definition standard
- HL7 FHIR Task Resource — Work item lifecycle
- DMN 1.3 (Decision Model and Notation) — Business rules standard
- Temporal.io — Durable execution patterns
- Inngest — Event-driven function execution patterns
- Saga Pattern (Garcia-Molina & Salem, 1987) — Long-running transaction compensation
- CQRS/Event Sourcing (Greg Young) — Event-driven architecture patterns
- Supabase pg_net / pg_cron / pgmq — PostgreSQL-native async execution and queuing
- SAMHSA/ASAM — Behavioral health treatment level determination criteria
- 42 CFR Part 2 — Substance use disorder record confidentiality
- BPM+ Health (Trisotech) — Pre-built healthcare workflow/decision models
- US Behavioral Health Profiles IG (HL7) — FHIR profiles for behavioral health
- json-rules-engine — JSON-based business rules evaluation for Node.js/Deno
Appendix A: Supabase Queues (pgmq) — Enhanced Execution Architecture
A.1 Why pgmq Over Raw pg_cron Polling
Online research revealed that Supabase now provides Supabase Queues built on thepgmq extension — a PostgreSQL-native durable message queue. This is a superior alternative to the raw pg_cron + FOR UPDATE SKIP LOCKED pattern described in Section 8 for several reasons:
A.2 Revised Execution Architecture with pgmq
A.3 Step-Per-Message Pattern
For long-running workflows (>150s Edge Function timeout), use a one-step-per-message pattern:- Worker dequeues message for execution step N
- Executes step N
- On success: deletes message, enqueues new message for step N+1
- On wait (approval/delay): deletes message, sets execution status to ‘waiting’
- On approval received: enqueues new message to resume from step N+1
A.4 pgmq Queue Configuration
Appendix B: json-rules-engine — Concrete Business Rules Implementation
B.1 Why json-rules-engine
Research identifiedjson-rules-engine as the most practical rules engine for a React + Supabase stack:
- JSON-defined rules — storable in Postgres JSONB columns, no code deploys to change rules
- Forward-chaining evaluation — supports nested AND/OR/NOT conditions
- Custom operators — extensible for healthcare-specific evaluations (score ranges, date comparisons)
- Isomorphic — runs in both Edge Functions (Deno) and browser for real-time preview
- Most popular — 189+ npm dependents, active maintenance
B.2 Integration with FW-17 Condition Builder
Decision tables (proposed FW-45) can be implemented as json-rules-engine rule sets stored in JSONB:B.3 Server-Side Evaluation in Edge Functions
B.4 Audit Trail for Compliance
Every rule evaluation must be audited for healthcare compliance:Appendix C: FHIR Behavioral Health Alignment — Extended Research
C.1 US Behavioral Health Profiles Implementation Guide
The HL7 US Behavioral Health Profiles IG (v0.1.0, in development) standardizes FHIR profiles for:- Substance use disorder conditions and treatment episodes
- Behavioral health encounter types (IOP, PHP, residential, outpatient)
- Mental health screening instruments (PHQ-9, GAD-7, CSSRS, ASAM)
- 42 CFR Part 2 consent management via FHIR Consent resource
C.2 BPM+ Health Pre-Built Models
BPM+ Health (Trisotech) provides ~1,000 free, evidence-based workflow and decision models using BPMN/DMN/CMMN, including:- Care pathways and clinical guidelines
- Healthcare calculators (LACE Score, APACHE, etc.)
- CDC immunization decision support
- Claims processing workflows
- Patient eligibility verification
C.3 42 CFR Part 2 Workflow Implications
Substance use disorder records require special handling that affects workflow design:- Consent-gated data sharing: Workflows that share patient data across providers must check 42 CFR Part 2 consent status before proceeding
- Data segmentation: FHIR R5 Consent resource + CDS Hooks-based data segmentation are the emerging standard
- Break-the-glass: Emergency override for substance use data requires audit trail and justification — model as an approval workflow step with enhanced logging
- Re-disclosure prohibition: Outbound event forwarding (PF-35 enhancement) must exclude 42 CFR Part 2 protected data unless consent is verified
C.4 XState v5 Persistence Pattern for Server-Side Workflows
Research confirmed XState v5 supports full snapshot persistence:automation-executor + fw_workflow_executions model is simpler and already implemented. XState persistence becomes relevant when/if complex client-side workflow UIs need server-synchronized state.
Appendix D: Industry Sources
Healthcare Workflow Automation
- Workflow Automation for Behavioural Health (Q3Tech)
- Top 10 Healthcare Workflow Automations (Sully AI)
- AI and Automation in Healthcare 2026 Predictions
- Priorities to Accelerate Workflow Automation in Health Care (PMC)
Event-Driven Architecture
- Event Versioning Strategies (theburningmonk)
- Simple Patterns for Event Schema Versioning (Event-Driven.io)
- Deduplication in Distributed Systems (Architecture Weekly)
- Idempotency and Ordering (CockroachDB)
- On Idempotency Keys (Gunnar Morling)
- Reliable Reprocessing and Dead Letter Queues (Uber)
- DLQ Guide (SRE School)
Supabase Patterns
- Supabase Queues (pgmq) Documentation
- PGMQ Extension Documentation
- Supabase Cron Documentation
- pg_net Documentation
- Database Webhooks Documentation
- Background Jobs with Supabase Tables and Edge Functions
XState & Workflow Orchestration
- Stately Docs: Persistence
- XState v5 Persistent Serverless State Machines (Restate)
- Workflow Automation with XState and React (Apploi)
FHIR Workflow
- FHIR Workflow Module (v5.0.0)
- FHIR Workflow Patterns (Medplum)
- US Behavioral Health Profiles IG
- Behavioral Health Workflow Automation (Dock Health)
Durable Execution & Saga Patterns
- Ultimate Guide to TypeScript Orchestration (Temporal vs Inngest vs Trigger.dev)
- Temporal: How It Works
- Mastering Saga Patterns (Temporal)
- Saga Pattern (microservices.io)