Skip to main content
Version: 1.1 Last Updated: 2026-03-15 Status: Architecture Research & Enhanced Recommendations Builds On: CROSS_CORE_EVENTS_AUTOMATION_WORKFLOW_DEEP_DIVE.md This document extends the Cross-Core Events, Automation & Workflow Deep Dive with industry research, pattern analysis, and enhanced recommendations for the Platform Foundation (PF) and Forms & Workflow (FW) cores — focusing on business automation, event-driven architecture, and workflow orchestration.

Table of Contents

  1. Executive Summary
  2. Current State Assessment
  3. Industry Research & Pattern Analysis
  4. Gap Analysis: PF Business Automation
  5. Gap Analysis: FW Workflow Engine
  6. Enhanced Recommendations: Platform Foundation
  7. Enhanced Recommendations: FW Workflow Engine
  8. Proposed Architecture: Durable Workflow Execution
  9. Proposed Architecture: Business Rules Engine
  10. Proposed Architecture: Event Mesh & Dead Letter Queue
  11. FHIR Workflow Alignment
  12. Cross-Core Business Process Catalog
  13. Implementation Roadmap
  14. Risk Assessment
  15. References
  16. Appendix A: Supabase Queues (pgmq) — Enhanced Execution Architecture
  17. Appendix B: json-rules-engine — Concrete Business Rules Implementation
  18. Appendix C: FHIR Behavioral Health Alignment — Extended Research
  19. 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)

  1. Queued executions never processedfw_process_domain_event() creates fw_workflow_executions rows with status = 'queued' but no worker picks them up.
  2. Form submission → automation invocation path unclear — No documented or implemented bridge between fw_form_submissions INSERT and automation-executor invocation.
  3. Dual event paths not unified — Table-driven (fw_domain_events) vs HTTP (event-consumer) with no clear routing documentation.
  4. XState workflow machine disconnected — Client-side step machine exists but is not wired to server-side execution.
  5. No dead letter queue — Failed events/executions have no recovery path.
  6. 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
XState 5 is NOT ideal for:
  • 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
Recommendation: Keep XState for client-side workflow visualization and wizard navigation (aligning with current “experimental/reserved” status). Server-side execution should remain in the 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
Recommendation: While full FHIR compliance is not required for MVP, align the workflow engine’s PlanDefinition-equivalent (workflow templates) and Task-equivalent (PF-29) with FHIR semantics to ease future interoperability. Specifically:
  • Workflow template definitions should support action arrays with trigger, 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:
Recommendation: Extend FW-17 (Condition Builder) to support decision tables as a condition evaluation mode. This enables non-technical staff to configure complex business rules without code changes. Store decision tables in a new 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_processes linking to fw_automation_rules and 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?”
Integration points: FW-03 (automation rules), FW-06 (workflow definitions), PF-29 (tasks), PF-10 (notifications)

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/sla exposing createSLA(), checkSLA(), escalateSLA() hooks
  • SLA definition table pf_sla_definitions with: entity type, metric, threshold, escalation chain
  • SLA instance table pf_sla_instances tracking: start time, deadline, current status, escalation level
  • pg_cron job checking approaching/breached SLAs and triggering escalation workflows
  • Dashboard widget showing SLA compliance metrics per core
Integration points: FW-35 (workflow SLAs), PM (authorization deadlines), CL (treatment plan reviews), HR (credentialing timelines)

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_id to pf_tasks (nullable FK to fw_workflow_executions)
  • Add source_automation_rule_id to pf_tasks (nullable FK to fw_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_subscriptions table: integration_id, event_type_pattern, filter_conditions, delivery_config
  • When fw_domain_events receives an event, check pf_event_subscriptions for 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_cron job runs every 10 seconds
  • Calls pg_net to invoke a new Edge Function workflow-executor-worker
  • Worker queries fw_workflow_executions for rows with status IN ('queued', 'retry_pending') AND next_retry_at <= now()
  • For each execution, runs the workflow step-by-step via automation-executor logic
  • 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_steps table 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_events with payload_schema (JSON Schema) and schema_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_seconds to workflow definitions (default: 86400 = 24 hours)
  • Add deadline_at to fw_workflow_executions (set on creation: now() + timeout)
  • pg_cron watchdog 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_id to fw_domain_events and fw_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

Automation opportunities:
  • 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

Automation opportunities:
  • 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

Automation opportunities:
  • 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

Automation opportunities:
  • 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

Automation opportunities:
  • 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

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)

Architecture Documents Created from This Research

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 the pgmq 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:
  1. Worker dequeues message for execution step N
  2. Executes step N
  3. On success: deletes message, enqueues new message for step N+1
  4. On wait (approval/delay): deletes message, sets execution status to ‘waiting’
  5. On approval received: enqueues new message to resume from step N+1
This ensures each Edge Function invocation stays well within the 150-second timeout while supporting workflows that run for days or weeks.

A.4 pgmq Queue Configuration


Appendix B: json-rules-engine — Concrete Business Rules Implementation

B.1 Why json-rules-engine

Research identified json-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
These models can inform the design of Encore OS workflow templates (FW-28 marketplace) — adapting the process flows to the platform’s automation engine rather than implementing BPMN directly.

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:
This “wake up, react, persist, sleep” pattern makes XState viable for Edge Function execution without requiring a long-running process. However, for the Encore OS architecture, this should remain reserved for future use (consistent with the existing “experimental” designation) — the 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

Event-Driven Architecture

Supabase Patterns

XState & Workflow Orchestration

FHIR Workflow

Durable Execution & Saga Patterns

Business Rules Engines