Skip to main content
EnFlow Labs
Phase 02 Deliverable — Confidential

Automation
Architecture

ClientSerene & Co.
IndustryMedical Aesthetics
DateMay 2026
LeadEnFlow Labs

Engagement Scope

Audit reference

Phase 01 AI Operations Audit — April 2026

Locations in scope

4 — Tampa, St. Petersburg, Clearwater, Sarasota

Architecture duration

May 5 → May 16, 2026 (2 weeks)

EnFlow OS modules configured

Pipelines · ScoreFlow · AutoFlow · CampaignFlow · InsightFlow

Agents specified

5 — Intake, Post-Visit, Membership Retention, New Client Intake, Reporting

Build plan horizon

90 days — 4 sprints, all P1 initiatives


Architecture Summary — Key Numbers

6
Workflows redesigned in this architecture
12
Automation rules specified for AutoFlow
5
AI agents included in build plan
~$35K
Total estimated Phase 03 build investment

Version

v1.0 — Final

Approved by

Serene & Co. — May 16, 2026

Section 01

Executive Summary


Serene & Co. enters this Architecture phase with a clear diagnostic in hand: the April 2026 Audit identified $317,000 in annual labor cost concentrated in four workflows — lead intake, post-visit follow-up, membership retention, and monthly reporting — all of which are manual, inconsistent, and directly replaceable by automated systems. This Architecture document translates those findings into a precise technical specification. Every system, pipeline, agent, and integration defined here is derived from a specific audit finding. Nothing is designed speculatively.

The core architectural decision in this engagement is to establish HubSpot as the operational brain of Serene & Co.'s client lifecycle — connected in real time to Vagaro as the system of record for appointments and bookings, and powered by EnFlow OS for automation logic, behavioral scoring, follow-up sequencing, and performance intelligence. The current state, where Vagaro and HubSpot operate as isolated silos with no data flow between them, ends at go-live. From that point forward, every appointment event in Vagaro triggers a corresponding action in the system — no human coordination required.

At the end of Phase 03 Implementation, Serene & Co. will have: a live AI intake agent handling every inbound inquiry across Instagram, Google, and the web; an automated follow-up system running across all four locations simultaneously; a ScoreFlow model monitoring membership health and triggering reactivation before clients lapse; and a real-time InsightFlow dashboard delivering performance data to ownership every Monday morning without a single hour of management assembly. The 90-day build plan in Section 14 sequences this work to deliver measurable ROI within the first four weeks of implementation.


Primary Architectural Decisions

1.

HubSpot as the operational CRM layer — not Vagaro.

Vagaro is the booking and transaction system of record. HubSpot is the pipeline, scoring, and automation host. The two systems serve different functions and are designed to integrate, not compete. Vagaro events trigger HubSpot actions via API. This avoids over-engineering Vagaro beyond its intended scope and leverages HubSpot's existing $680/month investment that has gone unrealized.

2.

SMS as the primary communication channel for CampaignFlow sequences.

Appointment-based businesses operate on mobile. Serene & Co.'s client base has demonstrated preference for SMS through the informal iMessage process at Sarasota. SMS open rates (97%) outperform email (21%) for time-sensitive communications like post-visit follow-ups and rebooking prompts. Email is secondary for longer-form content and review requests.

3.

A single unified intake agent across all four locations — not four separate agents.

One agent trained on all locations, services, and pricing handles inquiry routing by location preference. This reduces training overhead, ensures brand consistency, and produces a larger data set for ongoing improvement. Location-specific knowledge is stored as context in the agent's knowledge base, not as separate agent instances.

4.

ScoreFlow churn detection at 30 days — not the 90-day threshold used in the Audit bottleneck analysis.

The Audit identified members as "at-risk" at 30, 60, and 90-day thresholds. Architecture sets the intervention point at 30 days because medical aesthetics clients on treatment plans (Botox, filler, facials) have predictable rebooking windows. A 30-day signal catches drift before it becomes a pattern. Intervention at 90 days is too late for most service categories.

5.

InsightFlow dashboard is live from Day 1 of Sprint 1 — not deferred to the intelligence layer sprint.

Ownership has had no real-time performance visibility for two-plus years. The InsightFlow connection to Vagaro's API is simple (read-only) and can go live immediately once credentials are provisioned. Deferring it to Week 10 denies the business four weeks of decision support while the build is in progress.


What This Architecture Enables

Once this system is live, every inbound inquiry from any channel receives a response within 60 seconds — not 5.5 hours. Every completed appointment triggers a post-visit sequence without a front desk staff member deciding to send it. Every member whose visit frequency drops below their personal baseline is flagged and contacted before the 30-day mark. Ownership reviews live performance data across all four locations at 7:00 AM every Monday without a single manager spending time assembling it. The 112 hours per week currently consumed by rule-based, repeatable work shift to client experience, upselling, and the high-touch work that automated systems cannot replace.

Section 02

Audit Inputs Summary


Every system specified in this Architecture traces back to a finding in the April 2026 AI Operations Audit. This section documents the carried-forward findings and P1 automation opportunities that shape the build. The logic chain — Audit finding → Architecture response → Build deliverable — is explicit throughout this document.

Carried-Forward Audit Findings

#Audit FindingFunctionAnnual Labor CostArchitecture ResponseSection Reference
1Lead intake is fully manual across all four locations — 5.5-hour average response time, 18–22% of inquiries unbooked.Lead Ops$42,000/yr labor + $85–110K missed revenueAI intake agent + AutoFlow pipeline entry§08 Agent 1 · §07 Pipelines · §09 Auto-01
2Post-visit follow-up absent at 3 of 4 locations. Sarasota manual process produces 31% higher rebooking rate.Retention$38,000/yr laborCampaignFlow 3-touch post-visit sequence triggered by Vagaro completion event§07 CampaignFlow · §09 Auto-03
3Membership retention is reactive — at-risk clients identified monthly in meetings, too late to prevent churn.Retention$61,000/yr at-risk ARRScoreFlow Client Health Score + 5-touch reactivation sequence at 30-day threshold§07 ScoreFlow · §08 Agent 3
4HubSpot CRM installed but unused — no pipeline, scoring, or automation. $680/month with zero operational output.CRM$18,000/yr in unrealized value + $8,160/yr sunk costFull HubSpot configuration: pipeline stages, contact schema, ScoreFlow, Vagaro API sync§05 Data Model · §06 Integration Map · §07 Pipelines
5Monthly reporting consumes 16 hours of management time across four locations with no real-time visibility between cycles.Reporting$22,000/yr laborInsightFlow real-time dashboard + automated Monday digest replacing manual process entirely§07 InsightFlow · §10 Dashboard Specs · §08 Agent 5
6Digital intake forms absent at two locations — paper forms transcribed manually into Vagaro by front desk staff.Admin$9,500/yr laborAutomated digital intake form via SMS on new-client booking confirmation§09 Auto-06 · §08 Agent 4
7Meta Ads spend of $3,200/month produces leads that land in Instagram inbox with no routing, tracking, or attribution.MarketingEst. $28,000/yr in unattributed or lost ad spendMeta Ads → HubSpot lead routing integration; intake agent covers Instagram DM channel§06 Integration Map · §07 Pipelines
8Appointment reminders are Vagaro generic only — no prep instructions, no upsell touchpoint, no add-on confirmation.Ops / Revenue$12,000/yr in unrealized upsell revenueCampaignFlow pre-appointment 2-touch sequence: prep + upsell nudge at 48 hrs and 2 hrs§07 CampaignFlow · §09 Auto-04

P1 Automation Opportunities Carried Forward

OpportunityPriorityLabor Offset / YrEnFlow ModuleArchitecture Treatment
AI intake agent — Instagram DM, Google, web formP1$42,000AutoFlow + AI AgentFully specified in §08 Agent 1. Build sprint: Wk 7–9.
Post-visit follow-up sequence (3-touch, all 4 locations)P1$38,000CampaignFlow + AutoFlowSequence map in §07 CampaignFlow. Trigger spec in §09 Auto-03.
Membership churn prediction + reactivation sequenceP1$61,000ScoreFlow + CampaignFlowScoring model in §07 ScoreFlow. Reactivation sequence in §07 CampaignFlow.
Vagaro → HubSpot bidirectional API syncP1$18,000Pipelines + AutoFlowIntegration spec in §06. Webhook catalog documented. Sprint: Wk 4–5.
InsightFlow real-time dashboard (4 locations)P1$22,000InsightFlowKPI definitions and dashboard specs in §10. Dashboard live from Sprint 1.
Total P1 labor offset$181,000 / yr

Open Items From the Audit

Three items flagged in the Audit required resolution before Architecture could be finalized. All three were addressed in the Phase 02 kickoff session on May 5, 2026.

Open item 1: TCPA consent status of existing client list

Resolved: Serene & Co. confirmed that Vagaro booking flow collects SMS consent via opt-in checkbox. Consent field confirmed present on existing client records for ~78% of active contacts. The remaining 22% will be handled by a one-time re-consent campaign before CampaignFlow sequences go live. Documented in §13 Security & Compliance.

Open item 2: Vagaro API tier and webhook availability

Resolved: Confirmed on Business tier (4-location plan). Webhook events available: appointment.completed, appointment.created, appointment.cancelled, appointment.noshow, client.created, membership.payment_failed. All P1 integration triggers are supported. API credentials to be provisioned at Sprint 1 kickoff.

Open item 3: HubSpot HIPAA compliance status for intake form data

Resolved: HubSpot HIPAA Business Associate Agreement (BAA) is available on Professional tier. Serene & Co. to upgrade from Starter to Professional before intake form go-live. Digital intake forms will use a separate HIPAA-compliant form tool (JotForm Health) with data populated into HubSpot via API — PHI fields (medical history, contraindications) stored in JotForm only, not in HubSpot. Architecture reflects this data separation.

Section 03

Client Systems Inventory


Imported and updated from the Phase 01 Audit (Section 02). Each tool is annotated with its architectural role — what it feeds into the system, what it receives, and the action required before or during the build. Action key: Keep + Connect — retained and integrated as-is. Keep + Reconfigure — retained with configuration changes. Replace — decommissioned and replaced by EnFlow OS or a new tool.

CRM & Pipeline Management

ToolPlatformArchitectural RoleIntegration MethodAPI AvailableAction
HubSpotSales Hub Starter → upgrade to ProfessionalPrimary CRM and pipeline host. System of record for contact lifecycle, lead scoring, and automation triggers. All EnFlow OS modules operate through HubSpot.REST API + native webhook receiver. Vagaro sync via custom integration. CampaignFlow sends via HubSpot email API.Yes — fullKeep + Reconfigure
Upgrade to Professional tier. Configure pipeline stages, contact schema, ScoreFlow properties, and AutoFlow workflows.

Scheduling & Booking

ToolPlatformArchitectural RoleIntegration MethodTrigger AvailableAction
VagaroBusiness (4 locations)Primary system of record for appointments, client transaction history, and membership status. Every appointment event fires a downstream AutoFlow trigger. Vagaro does not own automation logic — it feeds it.Vagaro REST API (Business tier confirmed). Webhook events configured for: appointment.completed, appointment.created, appointment.cancelled, appointment.noshow, client.created, membership.payment_failed.Yes — 6 eventsKeep + Connect
No configuration changes to Vagaro. API credentials provisioned at Sprint 1 kickoff. Webhook events mapped to AutoFlow in Sprint 2.

Communication — Email, SMS, Phone

Tool / ChannelPlatformArchitectural RoleIntegration MethodSeq. CapableAction
Twilio (new)Twilio — to be provisionedPrimary SMS delivery layer for all CampaignFlow sequences and AutoFlow notifications. One shared number per location (4 total). All outbound SMS routes through Twilio; replies route back to HubSpot conversation inbox.Twilio REST API integrated into AutoFlow and CampaignFlow. Inbound SMS replies route to HubSpot inbox via Twilio webhook.YesNew — Provision
Provision 4 local numbers (one per location). Configure TCPA opt-out handling. Sprint 2 integration.
HubSpot EmailHubSpot (native)Secondary email delivery for CampaignFlow sequences — review requests, membership offers, longer-form content. No separate ESP required.HubSpot native email tool. CampaignFlow sequences trigger via enrolled workflow. HubSpot handles deliverability, unsubscribe, and open tracking.YesKeep + Connect
Mailchimp decommissioned at CampaignFlow go-live. Contact list migrated to HubSpot.
MailchimpEssentialsNo architectural role. Being replaced by HubSpot email + CampaignFlow. Static list model is incompatible with behavioral sequencing requirements.N/A — decommissioningNoReplace
Decommission at Sprint 3 go-live. Active subscriber list migrated to HubSpot. Cancel subscription post-migration.
iMessage (informal)iPhone — staff personalNo architectural role. Being replaced by Twilio SMS via CampaignFlow. Staff personal messaging creates compliance gaps and no record trail.N/ANoReplace
Deprecated at CampaignFlow go-live. Staff communication moves to HubSpot conversation inbox.

Marketing & Paid Acquisition

Tool / ChannelPlatformArchitectural RoleLead Routing MethodCRM ConnectionAction
Meta AdsMeta Business SuitePaid acquisition channel. Lead ads (new) will route directly to HubSpot via Meta Lead Ads integration. Traffic campaigns feed Instagram inbox, handled by intake agent.Meta Lead Ads → HubSpot native integration (no Zapier). Instagram DMs → AI intake agent via ManyChat or direct API.PendingKeep + Connect
Add Meta Lead Ads form to active campaigns. Connect Meta → HubSpot. Sprint 2 integration. Admin access required.
Instagram (organic)InstagramHighest-volume lead channel. DMs from organic and ad traffic handled by the AI intake agent. Agent deployed via Instagram Messaging API through Meta Business Suite.Instagram Messaging API → AI intake agent → HubSpot contact creation + pipeline entry.PendingKeep + Connect
All 4 Instagram accounts connected to intake agent. Meta Business Suite admin access required. Sprint 3.
Google BusinessGoogleSecondary inbound message channel. Google Business Messages connected to intake agent. Inquiries routed to same agent logic as Instagram.Google Business Messages API → AI intake agent → HubSpot.PendingKeep + Connect
Connect all 4 Google Business profiles to intake agent. Google Business API access required. Sprint 3.

Analytics, Reporting & Data Sources

Tool / SourceTypeKPIs It ProducesConnection MethodDashboard TargetAction
Vagaro ReportsNative reporting / APIRevenue by location, appointment volume, new vs. returning ratio, service category breakdown, membership counts and status.Vagaro REST API (read). InsightFlow pulls on 15-minute refresh interval. No manual export required.InsightFlow — all dashboardsKeep + Connect
API read access scoped to reporting endpoints. No write permissions required. Sprint 1 connection.
HubSpotCRM / pipelinePipeline conversion rates, inquiry-to-booking rate, sequence performance, lead source attribution, ScoreFlow distribution.HubSpot Reports API. InsightFlow native connector.InsightFlow — Pipeline & Campaign dashboardsKeep + Connect
HubSpot reporting permissions granted to InsightFlow service account. Sprint 1.
Meta AdsAd platformAd spend, CPM, CPC, lead form submissions, cost per confirmed booking (attributed).Meta Marketing API. InsightFlow pulls daily.InsightFlow — Executive OverviewKeep + Connect
Meta Marketing API access via Business Suite. Sprint 2 connection.
Google SheetsManual spreadsheetNo architectural role. Was used for manual reporting assembly. Replaced entirely by InsightFlow.N/A — decommissioningNoneReplace
Deprecated at InsightFlow go-live (Sprint 1). Archived for reference.

Internal Operations & Notifications

ToolPlatformArchitectural RoleIntegration MethodData In / OutAction
SlackSlack (new)Internal notification layer for AutoFlow alerts — esthetician intake form alerts, contraindication flags, human escalations from intake agent, revenue threshold breach alerts to ownership.Slack API via AutoFlow webhook action. Separate channels: #esthetician-alerts (per location), #ownership-alerts, #intake-escalations.Inbound from AutoFlowNew — Provision
Provision workspace + 4 location channels. AutoFlow integration configured in Sprint 2. No client-facing use.
JotForm HealthJotForm (new — HIPAA tier)HIPAA-compliant digital intake form. Stores PHI (medical history, contraindications) separately from HubSpot. Non-PHI fields (name, phone, email, service interest) synced to HubSpot via JotForm → HubSpot webhook.JotForm webhook → HubSpot contact property update. JotForm API → Vagaro client record update for non-PHI fields only.PHI stored in JotForm only. Non-PHI pushed to HubSpot and Vagaro.New — Provision
Provision HIPAA tier. Build intake form. Sprint 3 deployment with compliance review.
Section 04

Workflow Redesigns


Each workflow is documented in its redesigned future state. The current state was established in the April 2026 Audit (Section 03). These redesigns are the specifications the Implementation team builds to. Every step marked "Automated" must have a named system, trigger, and action. Human steps are explicit about why judgment is retained.

Workflow 1 — Lead Intake & Qualification

Audit ref: §03 Workflow 1 · Current avg response time: 5.5 hrs → Target: <60 sec
#Step (Future State)OwnerSystemTypeTrigger / LogicEnFlow Module
1Inquiry arrives via Instagram DM, Google Business message, or website formSystemInstagram / Google / WebAutomatedPlatform message eventAutoFlow
2AutoFlow routes inquiry to AI intake agent; HubSpot contact created with source tag and location assignmentSystemAutoFlow + HubSpotAutomatedAny inbound inquiry eventAutoFlow + Pipelines
3Intake agent responds within 60 seconds — brand-aligned greeting, service inquiry, FAQ resolutionAI AgentIntake Agent (Claude)AutomatedAutoFlow trigger on contact creationAutoFlow + AI Agent
4Agent qualifies lead: service interest confirmed, location preference identified, timing establishedAI AgentIntake Agent + HubSpotAutomatedConversation context + LLM logicAutoFlow + Pipelines
5Agent delivers Vagaro booking link pre-filled with location, service, and next available windowSystemIntake Agent + Vagaro APIAutomatedQualification criteria metAutoFlow
6Lead books — Vagaro appointment.created webhook fires; HubSpot pipeline advances to "Booked"; CampaignFlow pre-appointment sequence enrolledSystemVagaro → HubSpotAutomatedVagaro appointment.createdAutoFlow + Pipelines + CampaignFlow
7Edge case — complex objection or request outside agent scope: agent escalates with full conversation summary to front desk via HubSpot + SlackHumanFront Desk + HubSpot + SlackHumanAgent confidence threshold not metAutoFlow

Key design decisions

Single agent covers all four locations — location assignment based on stated preference or detected location from Google Business profile. Vagaro booking link is injected directly into conversation; no booking URL redirect required. Agent does not attempt to handle payment discussions — any pricing conversation beyond standard menu escalates to human.

What disappears from the current state

All manual front desk inbox monitoring across 4 locations (est. 17 hrs/week). 5.5-hour average response delay. Inconsistent lead qualification and follow-up. Manual HubSpot data entry on booking. Instagram DMs with no system record.


Workflow 2 — Pre-Appointment Preparation

New workflow — not in current state. Replaces generic Vagaro reminder only.
#Step (Future State)OwnerSystemTypeTrigger / LogicEnFlow Module
1Appointment confirmed in Vagaro — appointment.created event fires AutoFlow triggerSystemVagaro → AutoFlowAutomatedVagaro appointment.createdAutoFlow
2New client? AutoFlow sends JotForm Health intake form link via SMS — form must be completed before appointmentSystemAutoFlow + TwilioAutomatedIF contact.is_new_client = trueAutoFlow + CampaignFlow
348-hour pre-appointment SMS: personalized prep instructions based on service type (Botox — no blood thinners, avoid alcohol; HydraFacial — arrive makeup-free; etc.) + add-on suggestionSystemCampaignFlow + TwilioAutomated48 hrs before appointment time (Vagaro event timestamp)CampaignFlow
42-hour pre-appointment SMS: appointment confirmation + parking / arrival note for specific locationSystemCampaignFlow + TwilioAutomated2 hrs before appointment timeCampaignFlow
5New client intake form completed — JotForm webhook fires; non-PHI fields update HubSpot and Vagaro; contraindication flags send Slack alert to assigned estheticianSystemJotForm + HubSpot + SlackAutomatedJotForm form submission eventAutoFlow

Key design decisions

Prep instructions are service-specific — a Botox client gets different copy than a HydraFacial client. Service type is pulled from the Vagaro appointment record. PHI from the intake form (contraindications) is stored in JotForm only, never written to HubSpot. The esthetician Slack alert contains only the flag (e.g., "blood thinner noted"), not the full medical record.

What disappears from the current state

Paper intake forms at two locations. Staff transcribing forms into Vagaro. Generic single-reminder from Vagaro with no prep content. Missed upsell touchpoint at 48 hours. No-show rate expected to decrease by 20–30% based on confirmed reminder sequence data from comparable practices.


Workflow 3 — Post-Visit Follow-Up

Audit ref: §03 Workflow 2 · Currently performed at Sarasota only (manual)
#Step (Future State)OwnerSystemTypeTrigger / LogicEnFlow Module
1Appointment marked complete in Vagaro — appointment.completed webhook firesSystemVagaro → AutoFlowAutomatedVagaro appointment.completedAutoFlow
2AutoFlow determines: first-visit or returning client? Routes to appropriate CampaignFlow sequence variantSystemAutoFlow + HubSpotAutomatedIF contact.visit_count = 1 → Sequence A; else → Sequence BAutoFlow
3Touch 1 (Day 1, 24 hrs): Personalized thank-you SMS with esthetician name and service performedSystemCampaignFlow + TwilioAutomated24 hrs after appointment.completed timestampCampaignFlow
4Touch 2 (Day 3, 72 hrs): Rebook prompt with service-specific suggested return window (Botox: 90 days, HydraFacial: 30 days, Filler: 6 months)SystemCampaignFlow + TwilioAutomated72 hrs after appointment.completedCampaignFlow
5Touch 3 (Day 7): Google review request via SMS with direct link. First-visit clients receive longer-form email version.SystemCampaignFlow + Twilio + HubSpot EmailAutomatedDay 7 after appointment.completedCampaignFlow
6Rebook link clicked — sequence closes; Vagaro booking link delivered; HubSpot pipeline stage updatedSystemAutoFlow + Vagaro + HubSpotAutomatedBooking link click event (HubSpot tracking)AutoFlow + Pipelines
7Review link clicked — sequence closes; response logged in HubSpot; no further automation on this touchSystemAutoFlow + HubSpotAutomatedReview link click eventAutoFlow

Key design decisions

Two sequence variants — first-visit and returning — produce different messaging tone. Esthetician name is pulled from Vagaro appointment record and injected into Touch 1. Rebook timing is service-specific, not a single "come back soon" prompt. Sequence terminates on any booking or review action — no unnecessary continuation after goal is met.

What disappears from the current state

Staff-dependent follow-up across 3 locations with no record. Personal iMessage with no opt-out compliance. No review request process at Tampa, St. Pete, and Clearwater. Sarasota's informal process — which produced 31% higher rebooking rate — is now the standard at all four locations, automated.


Workflow 4 — Membership Retention

Audit ref: §04 Bottleneck 3 · Currently reactive — monthly meeting identification, too late
#Step (Future State)OwnerSystemTypeTrigger / LogicEnFlow Module
1ScoreFlow continuously monitors each member's Client Health Score — visit frequency vs. personal 90-day baseline updated on every Vagaro appointment eventSystemScoreFlow + Vagaro APIAutomatedContinuous / updated on each appointment eventScoreFlow
2Client Health Score drops below 60 (30-day visit gap approaching baseline): AutoFlow triggers enrollment in Membership Reactivation Sequence (Stage 1)SystemScoreFlow → AutoFlowAutomatedHealth Score &lt;60 threshold breachScoreFlow + AutoFlow
3Touch 1 (Day 1): Warm personal check-in SMS — no discount language, service suggestion based on visit historySystemCampaignFlow + TwilioAutomatedSequence enrollmentCampaignFlow
4Touch 2 (Day 7): Availability note + easy booking link for their most recently visited serviceSystemCampaignFlow + TwilioAutomatedDay 7, no rebook responseCampaignFlow
5Touch 3 (Day 14): Email with treatment plan reminder and what they're due for based on last service dateSystemCampaignFlow + HubSpot EmailAutomatedDay 14, no responseCampaignFlow
6Touch 4 (Day 21): SMS — brief, direct. One-click booking link only.SystemCampaignFlow + TwilioAutomatedDay 21, no responseCampaignFlow
7Touch 5 (Day 30): Human escalation — HubSpot task assigned to location manager with full engagement history, last service date, and membership valueHumanAutoFlow + HubSpot + SlackHumanDay 30, no response to any touchAutoFlow
8Membership payment failure — separate trigger: immediate AutoFlow action, same-day SMS + HubSpot task to front desk for payment resolutionSystem / HumanAutoFlow + CampaignFlow + TwilioHybridVagaro membership.payment_failedAutoFlow + CampaignFlow

Key design decisions

Intervention at 30-day drift, not 90-day confirmed lapse. No discount language in the sequence — the audit found that Serene & Co.'s retention problem is follow-up absence, not price sensitivity. The sequence is relationship-first, and the escalation at Day 30 gives the location manager a warm handoff with full context rather than a cold call to a churned client.

What disappears from the current state

Monthly management meeting as the mechanism for identifying at-risk members. Manual outreach by location managers based on memory. The 60-day window where $62K in ARR was left uncontacted. Membership payment failures going unaddressed until next month's review.


Workflow 5 — Performance Reporting

Audit ref: §03 Workflow 3 · Currently 16 hrs/month manual assembly across 4 location managers
#Step (Future State)OwnerSystemTypeTrigger / LogicEnFlow Module
1InsightFlow connects Vagaro, HubSpot, and Meta Ads APIs — live data available from Sprint 1 go-liveSystemInsightFlowAutomatedAPI connections live — continuous pullInsightFlow
2Executive Overview dashboard updates every 15 minutes — revenue by location, booking volume, new vs. returning, membership status all visible in real timeSystemInsightFlowAutomated15-minute API refresh intervalInsightFlow
3Every Monday 7:00 AM — AutoFlow fires reporting trigger; InsightFlow generates 5-bullet performance digest comparing last 7 days to prior 4-week averageSystemAutoFlow + InsightFlowAutomatedScheduled: Monday 7:00 AMAutoFlow + InsightFlow
4Digest delivered via email and SMS to ownership (3 recipients) — no assembly, no manual data pullsSystemInsightFlow + HubSpot Email + TwilioAutomatedTriggered by AutoFlow weekly digest ruleInsightFlow + CampaignFlow
5Threshold alert: if any location's weekly revenue drops &gt;15% below prior 4-week average — immediate SMS + email alert to ownershipSystemInsightFlow + Twilio + HubSpotAutomatedRevenue threshold breach — real-timeInsightFlow + AutoFlow
6Location manager review — dashboard available 24/7 on any device; no export, no spreadsheet, no compilation requiredHumanInsightFlow dashboardHuman (optional)On demandInsightFlow

Key design decisions

InsightFlow goes live in Sprint 1 — before any automations are built. Ownership gets performance visibility immediately and builds a baseline for measuring ROI throughout the build. The weekly digest compares to a rolling 4-week average rather than a fixed target to account for seasonal variation across the Tampa Bay market.

What disappears from the current state

16 hours per month of management time on CSV exports, Google Sheets assembly, and email delivery. No-visibility windows between monthly reporting cycles. Manual screenshot sharing of Meta Ads data. Ownership waiting until the first of the month to know last month's performance.


Workflow 6 — Lapsed Client Reactivation

New workflow — currently handled by ad hoc monthly Mailchimp blast to full list
#Step (Future State)OwnerSystemTypeTrigger / LogicEnFlow Module
1ScoreFlow detects 90 days since last Vagaro appointment for a non-member client — Client Health Score drops to "Lapsed" bandSystemScoreFlow + VagaroAutomatedHealth Score &lt;30 threshold (90-day gap)ScoreFlow
2AutoFlow enrolls client in Lapsed Reactivation sequence — distinct from Membership Retention sequence (non-members only)SystemAutoFlow + CampaignFlowAutomatedScoreFlow threshold breachAutoFlow
3Touch 1 (Day 1): Email — warm, personal. Reference to last service and esthetician by name. No discount. Simple "we'd love to see you again."SystemCampaignFlow + HubSpot EmailAutomatedSequence day 1CampaignFlow
4Touch 2 (Day 10): SMS — brief booking link with last service pre-selected as default.SystemCampaignFlow + TwilioAutomatedDay 10, no bookingCampaignFlow
5Touch 3 (Day 25): Email — seasonal or service-specific content relevant to their history (e.g., "Botox is due" for a client 3 months post last appointment).SystemCampaignFlow + HubSpot EmailAutomatedDay 25, no bookingCampaignFlow
6Client books at any point in sequence — sequence closes; HubSpot pipeline re-enters "Booked" stage; ScoreFlow resets health score on next appointment.completed eventSystemAutoFlow + HubSpot + ScoreFlowAutomatedVagaro appointment.created eventAutoFlow + Pipelines + ScoreFlow

Key design decisions

Separate from the Membership Retention workflow — lapsed non-members have different economics and a different relationship with the brand. Service-specific content in Touch 3 requires pulling last service type from Vagaro history and mapping to a content variant. Three content variants built: injectables, skin treatments, and body services.

What disappears from the current state

Monthly undifferentiated Mailchimp blast to full list — same message to everyone regardless of visit history, lapse duration, or service type. No individual-level detection of when a client has gone quiet. No service-relevant content in reactivation outreach.

Section 05

Data Model


Enflow Systems maintains a single, normalized data model across all modules — HubSpot as the CRM layer, Vagaro as the booking and transaction system, and EnFlow OS as the behavioral and automation layer. All three systems operate on a shared view of six core entities: Account, Location, Contact, Appointment, Membership, and Interaction. Multi-tenant isolation is enforced at the database level through Account scoping on every query. Event sourcing captures every state change for audit compliance. Referential integrity is maintained through API-level constraints and webhook-driven consistency checks.

Global Entities

EntityPurposeKey PropertiesOwned By
AccountRoot organization unit. All data is scoped by Account ID. Supports multi-location brands.id, name, industry, timezone, status (active/paused), created_at, updated_atHubSpot
LocationPhysical or virtual service site. Owns appointments, staff, and inventory. Mapping to Vagaro location ID is 1:1.id, account_id, name, address, phone, timezone, vagaro_location_id, status, created_atVagaro (source) + HubSpot (sync)
ContactIndividual — client, prospect, or staff. Unified view across Vagaro and HubSpot. Source of truth: HubSpot.id, account_id, email, phone, name, source (channel), status (prospect/client/inactive), is_member, consent_sms, consent_email, last_interaction, created_at, updated_atHubSpot (primary) + Vagaro (appointments only)
RolePermission group. Admin, Manager, Esthetician, Front Desk, Reviewer (for InsightFlow). Scoped per Account.id, account_id, name, permissions (array), created_atHubSpot User Management
UserStaff member with login. Maps to Contact. One Contact can have zero or one User record.id, account_id, contact_id, email (unique per account), role_id, sso_provider, last_login, status (active/deactivated), created_atHubSpot (via SSO) or EnFlow OS auth service

Operational Entities

EntityPurposeKey PropertiesOwner
AppointmentService booking. Created in Vagaro. Copied to HubSpot for pipeline context. Fires triggers for AutoFlow and CampaignFlow.id, account_id, location_id, contact_id, service_type, start_time, end_time, status (scheduled/completed/cancelled/noshow), staff_id, notes, vagaro_appointment_idVagaro (source) → HubSpot (sync)
LeadPre-booking prospect inquiry. Created via intake form or agent. Mapped to HubSpot pipeline. Not yet an Appointment.id, account_id, location_id, contact_id, source (instagram/google/web), service_interest, budget, inquiry_time, status (new/qualified/booked/lost), assigned_user_idHubSpot CRM
MembershipRecurring subscription or package. Defined in Vagaro. Synced to HubSpot for ScoreFlow health modeling.id, account_id, contact_id, type, billing_cycle, status (active/paused/cancelled), next_billing_date, amount, created_at, updated_atVagaro (source) → HubSpot (sync)
WorkflowRunInstance of an AutoFlow or CampaignFlow workflow. Created on trigger, progresses through stages until completion.id, account_id, workflow_id, contact_id, triggered_by (webhook event type), status (active/completed/failed), started_at, completed_at, error_logAutoFlow / CampaignFlow
WorkflowNodeIndividual step within a WorkflowRun. Executes a named action (send SMS, update HubSpot, call webhook).id, workflow_run_id, node_type (sms/email/webhook/conditional), action, status (pending/executed/failed), executed_at, error_messageAutoFlow / CampaignFlow
ClientMessageInbound or outbound message. SMS, email, or chat. Single unified record regardless of channel.id, account_id, contact_id, direction (inbound/outbound), channel (sms/email/chat), body, status (sent/delivered/failed/read), timestamp, associated_workflow_run_idTwilio / HubSpot / Chat provider
AuditEventImmutable log of every data mutation. Compliance record. For HIPAA / data retention.id, account_id, timestamp, user_id, entity_type, entity_id, action (create/update/delete), before_state (JSON), after_state (JSON), ip_address, user_agentEnFlow OS audit service
FileDocument or attachment — intake form PDFs, consent records, correspondence. Versioned.id, account_id, contact_id, filename, mime_type, size_bytes, storage_url, uploaded_by, purpose (medical_history/consent/correspondence), expires_at, created_atDocument Storage module
ScoreFlowScoreComputed health metric for a Contact. Updated continuously based on Vagaro and HubSpot events.id, account_id, contact_id, score (0–100), band (active/at_risk/lapsed), factors (visit_frequency, recency, membership_status), last_updated, next_recalcScoreFlow

Relationship Map & Cross-Module Dependencies

Contact → Appointment: One contact has many appointments (across locations). New appointment triggers AutoFlow pipeline entry and CampaignFlow sequence conditional on lead status.

Contact → Membership: One contact can hold zero or many memberships (multi-service, multi-location). Membership status feeds ScoreFlow health scoring. Payment failure on membership.payment_failed webhook triggers AutoFlow payment-recovery sequence.

Lead → Appointment: Lead progresses to Appointment when booked. HubSpot pipeline stage advances: "Qualified" → "Booked". No lead is converted to a contact until first appointment is confirmed.

WorkflowRun → ClientMessage: One workflow run produces many messages (SMS, email). Each message is a ClientMessage record linked to the WorkflowRun. Failed message triggers error escalation within the workflow.

Contact → ScoreFlowScore:One contact has one active ScoreFlowScore. Recomputed every 6 hours or on any appointment.completed event. Score changes trigger AutoFlow thresholds (e.g., health_score <60 → enter retention sequence).

Contact → AuditEvent: All Contact mutations — status changes, membership updates, data corrections — logged to AuditEvent. Audit trail is immutable and archived separately from operational data.


Multi-Tenant Isolation & Data Boundaries

Every table includes an account_id column. All queries filter by account_id at the application layer. Database-level row-level security (RLS) enforces account isolation — a query without account_id scoping returns no results. Cross-account data access is denied by default.

Location scoping: All user-level queries also filter by location_id (except Admin/Owner roles). A front desk user at Tampa sees only Tampa appointments, contacts, and lead assignments. Location managers see their location + read-only reporting on other locations.

Sensitive data segregation: PHI (medical history, contraindications) is stored only in JotForm Health, not in HubSpot or Vagaro. HubSpot and Vagaro contain only non-PHI fields (name, phone, service type, appointment timestamp). File records store only the storage URL and metadata; no medical data is embedded in the File object itself.


Event Sourcing & Audit Trail

Every state change is immutable. AuditEvent records capture: timestamp, user_id, action (create/update/delete), before_state (full JSON), and after_state (full JSON). This enables complete audit compliance, point-in-time data recovery, and dispute resolution.

Webhook events from Vagaro (appointment.completed, membership.payment_failed, etc.) are themselves audit events. They are logged, timestamped, and retained for 7 years minimum. Failed webhook deliveries are retried 3 times with exponential backoff; all retry attempts are logged.

Contact status changes (prospect → client → inactive) are tracked with reason and timestamp. If a contact is inactivated, their associated leads and workflows are flagged, not deleted.


EnFlow OS Module Alignment

EnFlow ModulePrimary Entity ConsumedData Flow / Integration PointOutput / Mutation
AutoFlowLead, Appointment, Contact, MembershipVagaro appointment events trigger AutoFlow workflows. HubSpot Contact fields (source, status) determine routing logic.WorkflowRun records; ClientMessage (SMS/email); HubSpot Contact stage updates
CampaignFlowContact, Appointment, Lead, ClientMessage (for opt-out checks)AutoFlow enrolls Contact in CampaignFlow sequences. Sequence delivery uses ClientMessage table to track every send.ClientMessage records (SMS, email); opt-out tracking; click/delivery events
ScoreFlowContact, Appointment, MembershipContinuous ingestion from Vagaro (appointment history) and HubSpot (lifecycle stage). Appointment.completed triggers score recalculation.ScoreFlowScore; score_band triggers (e.g., health_score &lt;60 → enroll in AutoFlow retention sequence)
InsightFlowAppointment, Lead, ClientMessage, WorkflowRun (for performance metrics)Read-only access to all operational entities. 15-minute API pull from Vagaro, HubSpot, Meta Ads. No mutations.InsightFlow dashboard; weekly digest reports; threshold alerts to ownership
Integrations HubContact, Appointment, ClientMessage (for channel mapping)Maps external channels (Instagram, Google Business) to internal Contact records. Inbound messages routed to intake agent, then to HubSpot.Contact creation; ClientMessage inbound records; webhook routing to AutoFlow
Section 06

Integration Map


Enflow Systems operates as a data orchestration layer, connecting Vagaro (system of record for appointments), HubSpot (operational CRM), and external channels (Instagram, Google, SMS, email) into a unified automation backbone. Six integration vectors carry data: Vagaro webhooks fire AutoFlow triggers; HubSpot contacts and properties feed scoring; communication channels route through Twilio and HubSpot email; InsightFlow pulls reporting data from all sources; and webhooks from external systems (payment failures, form submissions) drive event-driven logic. Every integration has explicit sync rules, retry logic, and fallback behavior.

Core Integrations

SystemPrimary RoleSync Direction & FrequencyAuthenticationError Handling & Fallback
VagaroBooking system of record. Single source of truth for appointments, clients, members, and transactions.Webhooks (real-time): appointment.created, appointment.completed, appointment.cancelled, appointment.noshow, client.created, membership.payment_failedAPI Key (OAuth not supported by Vagaro). Credentials stored in EnFlow OS secrets manager. Rotated annually.Webhook delivery failure: 3 retry attempts with exponential backoff (5s, 25s, 125s). Failed event logged to AuditEvent. Manual reconciliation dashboard available to ops team.
HubSpotOperational CRM. Owns contact records, pipeline stages, and automation trigger engine. AutoFlow and CampaignFlow orchestrated through HubSpot.Bidirectional: Vagaro → HubSpot (contact, appointment, membership data) syncs on appointment events. HubSpot → Vagaro (booking confirmation) syncs on pipeline stage change. Frequency: event-driven + 30-minute batch reconciliation.OAuth 2.0. Service account token stored in secrets manager. Scope: contacts, deals, email, workflows.HubSpot API errors (rate limit, 5xx): exponential backoff to max 2 minutes, then page ops team. Contact sync failures queue in a dead-letter topic for manual review.
TwilioSMS delivery and inbound message routing. All outbound SMS from CampaignFlow and AutoFlow routes through Twilio. Inbound SMS replies route back to HubSpot conversation inbox.Outbound: event-driven (send SMS on AutoFlow/CampaignFlow action). Inbound: webhook real-time on message arrival.API Key. Service account credentials in secrets manager. Separate credentials per location (4 numbers, 4 credential sets).Send failure: immediate retry within Twilio. If Twilio unavailable for &gt;10 mins, page on-call. Inbound webhook failure: Twilio retries 3 times. Dead messages logged for manual investigation.
JotForm HealthHIPAA-compliant intake form storage. Medical history and contraindications stored here only — not in HubSpot or Vagaro.One-way: JotForm → HubSpot and Vagaro (non-PHI fields only). Triggered on form submission. PHI stays in JotForm.API Key. Form submission webhook authentication via signed header verification.Webhook delivery failure: 3 retries with backoff. If non-PHI sync fails, HubSpot contact is created (without medical data) and escalated to front desk for manual form collection. No blocking failure.
Meta (Instagram + Ads)Inbound inquiry channel (DMs). Lead ads for direct lead routing. Ad platform for spend and attribution reporting.Inbound: Instagram Messaging API (real-time). Lead ads: Meta Lead Ads native sync to HubSpot (real-time). Ad spend: InsightFlow pulls Meta Marketing API daily.OAuth 2.0 (Instagram Business Account). Meta Marketing API token. Tokens scoped to specific Ad Account. Rotated semi-annually.Messaging API unavailable: intake agent falls back to SMS-only mode (no Instagram DM capability). Lead ads sync failure: leads manually pull from Meta Ads interface; InsightFlow flags discrepancy. Ad spend reporting delay up to 24 hours acceptable.
Google BusinessInbound inquiry channel (Google Business Messages). Secondary to Instagram; same intake agent handles both.Inbound: Google Business Messages API (real-time messages routed to intake agent).Service account (Google Cloud). OAuth for GBM API. Credentials scoped to Business Profile management.API outage: inquiry messages queue in Google; next API reconnect retrieves queued messages within 15 minutes. No loss of inquiries.

Data Flow Diagram (Textual)

Inbound Inquiry Flow:

Instagram DM / Google Message → Integrations Hub → AI Intake Agent
→ HubSpot Contact (create/update) → AutoFlow trigger (Lead Intake)
→ HubSpot Pipeline Stage: "New Inquiry" → Bot response to user

Appointment Booking Flow:

Vagaro appointment.created webhook → AutoFlow (trigger)
→ HubSpot Contact: advance to "Booked" stage
→ HubSpot: enroll in CampaignFlow (pre-appointment sequence)
→ ScoreFlow: add to health score calculation

Appointment Completion Flow:

Vagaro appointment.completed webhook → AutoFlow trigger
→ ScoreFlow: recalculate Client Health Score
→ HubSpot: enroll in CampaignFlow (post-visit sequence)
→ If Health Score <60: enroll in retention sequence (separate trigger)

Reporting & Dashboarding Flow:

Vagaro, HubSpot, Meta Ads APIs (read-only) ← InsightFlow (pull every 15 mins)
→ InsightFlow dashboard (real-time) + weekly digest (Monday 7am)
→ Threshold alerts to ownership (SMS + email) if revenue ↓ >15%

Payment Failure Flow:

Vagaro membership.payment_failed webhook → AutoFlow trigger
→ CampaignFlow: SMS to member + email with retry instructions
→ HubSpot Task assigned to location front desk (escalation)
→ Slack alert to #esthetician-alerts


Sync Rules & Reconciliation

Data TypeSource → DestinationSync TriggerConflict ResolutionReconciliation
ContactVagaro → HubSpotclient.created, appointment.created (new client)HubSpot wins if contact already exists (contact deduplication by email)30-min batch: compare record counts per location
AppointmentVagaro → HubSpotappointment.created, appointment.completed, appointment.cancelled webhookN/A (append-only; no overwrites)Daily: compare appointment count by date range
MembershipVagaro → HubSpotclient.created, membership.created webhook eventHubSpot wins if membership already exists (dedup by Vagaro ID)Weekly: audit membership status discrepancies
Non-PHI form dataJotForm → HubSpot + VagaroJotForm form submissionHubSpot wins (phone, email). Vagaro custom fields populated from HubSpot.Manual: intake form review if field mismatch detected
SMS delivery statusTwilio → HubSpotTwilio status callback webhook (delivered, failed, bounced)N/A (append-only)None required; immutable event log

Webhook Architecture & Security

Inbound webhooks from Vagaro, Twilio, JotForm, and Meta are received at a single gateway endpoint. Each webhook is authenticated via signed header verification (HMAC-SHA256). Webhook payloads are logged (without sensitive data) before processing. Processing is asynchronous — webhooks are immediately acknowledged (HTTP 200) and queued for processing.

Outbound webhooks to HubSpot, Twilio, and Slack are authenticated via API keys stored in EnFlow OS secrets manager. All outbound calls use TLS 1.3. Request timeouts set to 10 seconds; failed requests are queued for retry.

Webhook retry logic: Failed webhooks are retried up to 3 times with exponential backoff (5 seconds, 25 seconds, 125 seconds). After 3 failures, the event is logged to AuditEvent and flagged in the ops dashboard for manual investigation. No webhook is silently dropped.

Idempotency: All webhook handlers are idempotent. Receiving the same webhook twice produces the same result. This is enforced via idempotency keys (webhook ID + timestamp) stored in a short-lived cache. Duplicate webhooks within 1 minute are silently ignored.


API Gateway & Rate Limiting

All external API calls are routed through an API gateway layer. Rate limits are enforced per endpoint:

EndpointRate LimitThrottle BehaviorBilling Impact
Vagaro API (contact read, appointment query)100 req/min per accountQueue and retry with backoffNo overage; queued requests processed at next window
HubSpot API (contact update, deal creation)200 req/min per accountQueue and retryEach API call billable; queued calls processed normally
Twilio SMS send50 msg/sec per accountBuffer; send at max rateEach SMS billable regardless of queueing
Meta Lead Ads sync10 req/sec per accountQueue with backoffNo impact (read-only)
Section 07

EnFlow OS Configuration


Enflow Systems plugs into EnFlow OS through a registration interface that exposes Enflow's entities (Contact, Appointment, Membership, ScoreFlowScore) as first-class objects within the OS. The OS sees Enflow Systems as a data provider and an action executor — the system ingests Enflow data for behavioral scoring and automation, and Enflow executes the resulting workflows (send SMS, update CRM, escalate to human). This section documents module registration, trigger/condition/action specs, and cross-module event propagation.

Module Registration & Manifest

Enflow Systems registers itself to EnFlow OS via a manifest file deployed at module initialization:

name: "enflow-systems"

version: "1.0"

exports:

entities:

- contact (read/write)

- appointment (read/write)

- membership (read/write)

- scoreflow_score (read)

triggers:

- contact.created

- appointment.completed

- membership.payment_failed

actions:

- send_sms

- send_email

- update_contact

- create_task

dependencies:

- AutoFlow v2.0+

- CampaignFlow v1.5+

- ScoreFlow v3.0+

Trigger Registry & Emission Specs

Trigger NameSource EventPayload (Context)Consuming Modules
contact.createdNew inquiry via intake form or agentcontact_id, name, phone, email, source_channel, location_id, timestampAutoFlow (lead qualification), CampaignFlow (welcome sequence), ScoreFlow (baseline health score)
contact.updatedHubSpot contact field change (pipeline stage, SMS consent, etc.)contact_id, changed_fields (JSON), before_state, after_state, timestampScoreFlow (score recalculation if visit history updated), AutoFlow (conditional routing on status change)
appointment.completedVagaro appointment.completed webhookappointment_id, contact_id, service_type, location_id, completed_at, duration_minutes, staff_idScoreFlow (health score update), CampaignFlow (post-visit sequence enrollment), AutoFlow (booking confirmation routing)
appointment.noshowVagaro appointment marked no-showappointment_id, contact_id, scheduled_time, location_id, timestampScoreFlow (negative factor in health score), AutoFlow (escalation to location manager)
membership.payment_failedVagaro membership billing failuremembership_id, contact_id, amount, failure_reason, retry_at, timestampAutoFlow (same-day SMS + task escalation), CampaignFlow (payment recovery sequence)
scoreflow.score_updatedScoreFlow recalculation completescontact_id, old_score, new_score, old_band, new_band, factors (JSON), timestampAutoFlow (threshold-based sequence enrollment; e.g., health_score &lt;60 → retention sequence)
message.inboundInbound SMS reply or chat from contactcontact_id, channel (sms/chat), message_body, timestamp, provider_message_idAutoFlow (intent detection, escalation routing), CampaignFlow (sequence termination on rebook response)

Condition & Action Registry

Conditions are predicates evaluated within AutoFlow and CampaignFlow workflows. Conditions can reference Contact properties, Appointment data, ScoreFlowScore, or membership status.

Condition NamePredicateData SourceUsage Example
contact.is_new_clientTRUE if contact.visit_count == 0HubSpot Contact + Vagaro historyIF is_new_client → Send intake form (JotForm) instead of rebook prompt
contact.has_sms_consentTRUE if contact.consent_sms == true AND consent_date validHubSpot Contact consent propertyIF NOT has_sms_consent → Send email instead of SMS
scoreflow.health_bandEquals: "active", "at_risk", or "lapsed"ScoreFlow score bandIF health_band == "at_risk" → Enroll in retention sequence
appointment.service_type_matchesAppointment.service_type IN (list)Vagaro appointmentIF service_type IN ["Botox", "Filler"] → Send injectables-specific prep instructions
membership.is_activeTRUE if membership.status == "active" AND next_billing_date &gt; todayVagaro membershipIF NOT is_active → Route to lapsed reactivation sequence (not member retention)

Actions are executable operations invoked by workflows. Every action is atomic — it succeeds or fails completely. Failed actions trigger retry logic or escalation.

ActionOutput / Side EffectRetry BehaviorLogging / AuditEscalation
send_smsSMS message delivered via Twilio. ClientMessage record created. Delivery status tracked.3 retries, exp. backoff. Max 2 minutes.AuditEvent: action, contact_id, message_id, status, timestampAfter 3 failures: log to ops dashboard + page on-call if &gt;50 msgs failed in 10 mins
send_emailEmail delivered via HubSpot Email. ClientMessage record created.HubSpot handles retry (24-hour window). Enflow queues on HubSpot API error.AuditEvent: action, contact_id, email_id, HubSpot workflow ID, statusHubSpot unsubscribe → remove contact from future email sequences
update_contactHubSpot Contact record updated (property value change). Before/after states logged.Immediate retry on API error, then exponential backoff.AuditEvent: contact_id, property_name, before_value, after_value, modified_by, timestampIf contact does not exist: create new contact first, then apply update
create_taskHubSpot Task created, assigned to user_id, with description and due date.3 retries. Max 5 minutes.AuditEvent: action, contact_id, task_id, assigned_to, due_dateTask creation failure: send Slack alert to #ownership-alerts with full workflow context
enroll_workflowContact enrolled in AutoFlow or CampaignFlow workflow. WorkflowRun record created.Idempotent: if contact already enrolled, no-op (return existing WorkflowRun).AuditEvent: action, contact_id, workflow_id, workflow_run_id, timestampNone; enrollment is append-only. Failed enrollments logged for ops review.
send_slack_notificationMessage posted to specified Slack channel. Used for internal alerts only (not client-facing).3 retries. Max 30 seconds. If failed, logged but no escalation.AuditEvent: action, channel, message summary, statusNone; Slack is informational only. Failures do not block workflows.

Cross-Module Event Propagation

Events flow bidirectionally between modules. No module is isolated.

From ModuleEvent TypeTo Module(s)Action / Reaction
Integrations Hubcontact.created (inbound inquiry)AutoFlow, ScoreFlowAutoFlow: enroll in lead-intake workflow. ScoreFlow: initialize Client Health Score.
AutoFlowworkflow.enrolledCampaignFlowCampaignFlow: if workflow type is campaign, automatically enroll contact in corresponding sequence.
ScoreFlowscore_updated (health_score &lt;60)AutoFlowAutoFlow: trigger retention enrollment if not already enrolled. Check contact status to avoid duplicate sequences.
CampaignFlowmessage.inbound (customer reply)AutoFlowAutoFlow: if inbound message contains booking link click or affirmative intent, terminate sequence and advance pipeline stage.
AutoFlowaction.failed (e.g., send_sms failed 3x)InsightFlowInsightFlow: log failure in observability. If threshold exceeded (10+ failures/min), alert ops team.
Vagaromembership.payment_failed webhookAutoFlow, ScoreFlowAutoFlow: create task + send notification. ScoreFlow: downgrade health score (penalty factor).

Observability, Logging & Audit Integration

Enflow Systems inherits EnFlow OS logging and audit infrastructure. Every action, trigger, and state change is captured in the unified AuditEvent table. No local logs; all observability goes through EnFlow OS audit service.

Structured logging: Every log entry includes: timestamp, user_id (if human action), action_type, resource_id, before_state, after_state, metadata (JSON). Logs are immutable and retained for 7 years minimum (HIPAA compliance).

Observability dashboards: InsightFlow provides real-time visibility into workflow execution, message delivery rates, error counts by type, and latency percentiles. SLOs are defined:

MetricTarget SLOAlert ThresholdOwner / Escalation
Inbound message response time (agent)p95 &lt;5 sec&gt;10 sec for 5+ msgsOn-call eng
AutoFlow workflow execution success rate99.9%< 99.5%On-call eng
SMS delivery rate99%< 98%Twilio support + ops
HubSpot contact sync latencyp95 &lt;30 sec&gt;60 secEngineering
InsightFlow dashboard responsivenessp95 &lt;2 sec&gt;5 secOn-call eng

Future Extensibility & Module Integration Points

Enflow Systems is designed for expansion into adjacent EnFlow OS modules without architectural changes.

Inventory Management (future module)

Integration point: Appointment.service_type → inventory deduction on appointment.completed. New trigger: inventory.depleted.

Constraint: Must maintain referential integrity with appointment.service_id.

Payment Processing (Stripe integration)

Integration point: Membership.payment_failed already routes to AutoFlow. Stripe webhook on charge.failed → same trigger.

Constraint: PCI compliance requires Stripe tokenization; no card data stored in HubSpot.

Advanced Analytics (custom AI model)

Integration point: ScoreFlow model extensible via new condition types. Custom ML model can read Contact and Appointment history.

Constraint: Model must return a single score (0–100) compatible with existing AutoFlow threshold conditions.

QuickBooks integration (future phase)

Integration point: Appointment revenue syncs to QB invoice on appointment.completed. Membership recurring revenue mapped to QB customer record.

Constraint: QB API limits: 100 req/min. Batch sync every 15 minutes to stay within limits.

Section 08

AI Agents


Enflow Systems deploys four AI agents, each optimized for a specific domain within the customer lifecycle. All agents run on Claude 3.5 Sonnet with prompt caching enabled for cost efficiency and latency. Agents operate within strict guardrails — they can inform, suggest, and escalate, but cannot execute financial transactions, prescribe medical treatments, or access PHI data. Escalation to human staff is automatic when agent confidence falls below a threshold or when interaction falls outside trained domains.

Agent Catalog

Agent NamePrimary FunctionInput SourcesOutput / Actions
Intake AgentHandle inbound inquiries across Instagram, Google Business, and web forms. Qualify leads, surface available appointment slots, and route to appropriate service category.Inbound message (text/chat), HubSpot Contact record (if returning client), Vagaro location availability, service menuResponse message (brand-aligned greeting + info delivery), HubSpot Lead creation, Vagaro booking link injection, Slack escalation (if needed)
Scheduling AgentAssist with appointment rescheduling and cancellation. Understand client constraints (availability, service type preference) and suggest optimal windows.Client message, Vagaro appointment history, current location calendar, service duration dataRescheduling confirmation, cancellation acknowledgment, HubSpot activity log entry, Slack notification to location manager (for high-value cancellations)
Compliance AgentMonitor intake form submissions and client communication for compliance flags (contraindications, consent validity, PHI leakage). Quarantine flagged records for human review.JotForm submission (non-PHI fields only), inbound client messages, intake agent conversation logsFlag or clear-to-proceed signal, Slack alert to compliance team (if flag detected), AuditEvent log entry
Insight AgentAnalyze client conversation history and booking patterns to surface high-value upsell moments and churn signals. Recommend interventions.Client message history (ClientMessage table), HubSpot Contact data, Vagaro appointment history, ScoreFlow scoreUpsell recommendation card (for staff), churn flag (to ScoreFlow), suggested message template for manual staff send

Agent Memory & Retrieval Architecture

Intake Agent memory: Long-term memory stored in HubSpot Contact record (service history, preferences, location affinity, price sensitivity signals). Conversation context window: 10 messages or 15 minutes of active chat, whichever is longer. Memory is cleared between sessions unless client re-opens within 24 hours.

Scheduling Agent memory: Client availability patterns and historical rescheduling preferences (e.g., "always books afternoons on Thursdays"). Retrieved from Vagaro appointment history via vector similarity search on time slots. No persistent memory between conversations; data is always fresh from source systems.

Compliance Agent memory: No persistent memory. Stateless evaluation of each submission against hardcoded compliance rules (consent date validity, contraindication flagging, PHI field detection). Rules are versioned and deployed centrally; agents do not learn or evolve rules.

Insight Agent memory: Historical context retrieved from ClientMessage and Appointment tables. No learning across clients; insights are deterministic outputs of the conversation analysis pipeline, not ML-driven predictions.


Guardrails & Safety Boundaries

BoundaryRuleViolation BehaviorAudit Log
Medical adviceAgent cannot prescribe, diagnose, or recommend medical treatment. Service selection and product info only.If client asks for medical advice, agent responds: "Please consult with your esthetician," then escalates to staff via Slack.AuditEvent: agent_guardrail_triggered, boundary_type="medical_advice", contact_id, escalation_user_id
Financial transactionsAgent cannot accept payment, issue refunds, or process discounts. Booking and inquiry only.If client requests discount or payment adjustment, agent directs to front desk: "I'll connect you with our team," then creates HubSpot task.AuditEvent: agent_guardrail_triggered, boundary_type="financial", contact_id, created_task_id
PHI accessAgent cannot access or reference medical history stored in JotForm. Non-PHI fields only.If agent is trained context includes PHI, context is stripped at runtime. PHI queries fail silently with "Data unavailable" response.AuditEvent: phi_access_attempt_blocked, agent_id, contact_id, attempted_field
Confidence thresholdIf agent confidence &lt;60% on next action, escalate to human.Agent stops responding to client, delivers: "Let me get our team to help," and creates Slack alert with full conversation for staff.AuditEvent: agent_escalation, reason="low_confidence", confidence_score, escalation_user_id
Out-of-scope inquiryAgent trained only on: intake, scheduling, rebook prompts, event details. Outside scope: HR, legal, compliance reports.Agent responds: "That's outside my area — let me get the right person," escalates to owner email + Slack.AuditEvent: agent_escalation, reason="out_of_scope", inquiry_category, escalation_recipient

Agent Interaction Model & Workflow Integration

Agents operate within AutoFlow workflows as decision nodes. A message arrives → AutoFlow routes to appropriate agent → agent returns response + metadata (confidence, action flags, escalation status) → AutoFlow determines next step (send response, enroll in CampaignFlow, create task, escalate).

Intake Agent workflow: Inbound message → AutoFlow trigger → Intake Agent (response + lead qualification) → IF booking link clicked: advance HubSpot pipeline + enroll CampaignFlow → IF escalation flagged: create Slack alert + HubSpot task.

Insight Agent integration with ScoreFlow: On every appointment.completed, Insight Agent analyzes the client's full message history and appointment pattern. If upsell moment detected (e.g., client previously inquired about add-on services), recommendation is logged to InsightFlow dashboard for staff visibility. If churn signal detected (long message gaps, cancellation pattern), churn flag is sent to ScoreFlow for health score adjustment.


Observability & Audit Requirements

Every agent interaction is logged to AuditEvent with: agent_id, contact_id, conversation_id, input_message, output_response, confidence_score, guardrail_triggers (if any), escalation_status, timestamp. No agent output leaves the system without an audit trail.

Agent metrics are published to InsightFlow: response latency (p50/p95), confidence score distribution, escalation rate by reason, message classification accuracy (for intake agent qualification). SLO for agent response time: p95 <5 seconds.

Section 09

Pipelines


Enflow Systems operates four pipeline categories: Event pipelines (webhook → trigger → action), Data pipelines (periodic Vagaro, HubSpot, Meta API pulls), Scoring pipelines (ScoreFlow health score calculations), and Sync pipelines (bidirectional Contact/Appointment sync). Each pipeline is versioned, observable, and implements explicit retry and dead-letter queue logic. Pipeline execution is idempotent — the same event processed twice produces the same result.

Pipeline Types & Execution Model

Pipeline TypeTriggerProcessing ModelOutputSLO
EventWebhook (appointment.completed, client.created, etc.)Synchronous. Processed immediately on receipt. Max 10 sec processing time per event.WorkflowRun record created. AutoFlow triggers fired. HubSpot/Vagaro mutations queued.p95 &lt;2 sec (acknowledge) + p95 &lt;5 sec (execution)
DataScheduled: every 15 minutes (Vagaro, HubSpot, Meta). Every 1 hour (full reconciliation).Asynchronous batch. Fetch delta since last pull. Process and reconcile. Atomic per source.Updated Contact, Appointment, Lead, AuditEvent records. Sync conflict log.p95 &lt;30 sec per pull (not including network latency)
ScoringOn appointment.completed. Also: daily batch recalc at 2:00 AM UTC.Transactional. Read full Contact history (appointments, memberships, messages). Calculate score. Update ScoreFlowScore.ScoreFlowScore record. If score band changes, emit scoreflow.score_updated trigger.p95 &lt;1 sec per contact
SyncOn Vagaro appointment.completed. Bidirectional every 30 minutes (full reconciliation).Pull from source, apply transformations, check for conflicts, write to destination. Log all conflicts.HubSpot Contact/Appointment updated or created. Vagaro client fields synced from HubSpot (non-appointment fields).p95 &lt;15 sec per sync record

Retry, Backoff & Dead-Letter Queue Strategy

Event pipelines (sync execution): If processing fails, immediate retry (max 3 times) with exponential backoff: 1 sec, 5 sec, 25 sec. After 3 failures, event is moved to DLQ and logged to AuditEvent. DLQ events are reviewed manually within 24 hours. High-priority events (appointment.completed, payment failures) trigger a Slack alert when DLQ'd.

Data pipelines (async, batch): If a data pull fails (API error, timeout), the batch is marked failed and the next scheduled pull is triggered immediately. Failed pulls do not block subsequent pulls. Reconciliation jobs detect missing data from failed pulls and flag discrepancies.

Scoring pipelines:If score calculation fails for a single contact, the contact is flagged and the score recalc is deferred to the next batch. The Contact record is not left in an inconsistent state. A daily audit checks for stale scores (not updated in >24 hours) and triggers manual review.

Sync pipelines:If a sync fails (conflict detected, target API unavailable), the record is logged with before/after state and moved to a conflict queue. Conflicts are resolved in order of priority (payment_failed > appointment > contact) and retried every 5 minutes up to 288 times (24 hours).


Pipeline Versioning & Rollback

Every pipeline has a version identifier. Pipeline deployments are atomic — the old version runs until all in-flight requests complete, then the new version takes over. Rollback is automatic if new version error rate exceeds 5% within the first 10 minutes.

Breaking changes to pipeline data formats are prohibited. Data schema changes are additive only (new fields with defaults). Legacy field removal requires a 2-sprint deprecation notice.

Pipeline versions are logged in AuditEvent: pipeline_version_changed, old_version, new_version, deployment_timestamp, deployed_by_user_id.


Pipeline Observability & Monitoring

MetricCollectionAlert ThresholdEscalation
Event pipeline latency (p95)Per webhook type&gt;5 secSlack #ops-alerts + page on-call
Data pipeline success ratePer source (Vagaro, HubSpot, Meta)< 95%Slack + email to eng team
Sync conflict ratePer data type (Contact, Appointment, Membership)&gt;5 conflicts/hourPage on-call + create manual review ticket
DLQ queue depthPer pipeline&gt;10 eventsSlack alert, manual review required
Scoring pipeline stale scoresDaily audit&gt;2% of contactsSlack alert + trigger full recalc batch
Section 10

Automation Specifications


Enflow Systems implements a explicit trigger → condition → action execution model. Every workflow is deterministic and auditable. Actions are idempotent — running the same action twice produces the same result. Long-running workflows (multi-touch sequences) maintain state in the database. Human escalation is automatic when conditions cannot be resolved by logic.

Trigger → Condition → Action Execution Lifecycle

1. TRIGGER FIRES

Webhook or scheduled event → EnFlow event service → route to pipeline

2. CONTEXT LOAD

Fetch Contact, Appointment, Membership, ScoreFlowScore, recent messages

3. CONDITION EVALUATION

Evaluate all conditions: IF is_new_client AND has_sms_consent → proceed. Fail fast on first FALSE.

4. CONDITION FAILURE

If any condition FALSE: workflow halts, no action executed, reason logged to AuditEvent

5. ACTION EXECUTION

All conditions TRUE → execute action (send_sms, send_email, create_task, enroll_workflow, etc.)

6. ACTION RESULT

SUCCESS: WorkflowNode marked complete. FAILURE: retry handler invoked.

7. RETRY / ESCALATION

If failed: exponential backoff (3 retries). If all retries fail: escalate to human OR move to DLQ.

8. WORKFLOW COMPLETION

WorkflowRun marked complete with final status (success/failed/escalated). Audit trail immutable.

Idempotency & Deduplication

Every action includes an idempotency key: workflow_run_id + node_index + attempt_number. If the same action is executed twice (webhook retry, manual retry), the second execution is detected and skipped. The first result is returned instead.

Idempotency keys are stored in a cache with 24-hour TTL. After 24 hours, the key expires and the action is re-executable (acceptable for non-critical operations; critical operations enforce longer TTLs or manual approval).


Escalation Logic & Human-in-the-Loop Checkpoints

Escalation TriggerConditionActionAssignment
Agent confidence lowIntake Agent confidence &lt;60%Stop responding to client. Create HubSpot task with full conversation.Location manager (based on contact location)
Medical escalationClient asks for medical advice or reports contraindicationRoute to esthetician via Slack + HubSpot task. Esthetician responds directly.Assigned esthetician (from appointment record)
Payment failureMembership payment fails 2x in 7 daysCreate task for location manager. SMS to client with payment retry link.Location front desk
High churn riskScoreFlow health score &lt;30 (lapsed)Create task for location manager. Recommended talking points provided in task.Location manager (high-value client override: owner)
Workflow failureAction fails 3x (DLQ)Log to AuditEvent. Create task for ops team. Slack #ops-alerts.On-call engineer

Long-Running Workflow State Management

Workflows that span multiple days (CampaignFlow sequences, retention sequences) are stored as WorkflowRun records with explicit state. Each day, a batch job checks for pending WorkflowRun.next_action_scheduled_at values and fires the next step.

State transitions are atomic: check current state → validate preconditions → update state → emit trigger. No partial state updates. If an error occurs during state update, the entire transaction rolls back.

Workflow state snapshots are captured at every transition and stored in AuditEvent for complete historical audit trail. This enables manual workflow recovery and debugging.

Section 11

Dashboards & Reporting


InsightFlow provides four primary dashboards: Executive (ownership view of all 4 locations), Operations (location-level performance and anomalies), Agent (AI agent execution metrics and guardrail triggers), and Compliance (audit logs, data access, escalations). All dashboards update every 15 minutes. Custom reporting is available via the InsightFlow API for building ad-hoc queries.

Dashboard Catalog

DashboardPrimary AudienceCore MetricsData Sources
Executive OverviewOwnership, monthly + real-time reviewRevenue (by location, by service), new bookings, membership count, churn rate (weekly), aggregate agent response time, top upsell opportunityVagaro API (15m), HubSpot (15m), Meta Ads API (daily), ScoreFlow
Operations HubLocation managers, daily monitoringAppointments booked today, no-shows, prep form completion rate, payment failures (with contact name), top-performing esthetician (bookings), queue depth (pending tasks)Vagaro API (live), HubSpot (live), JotForm (live), AuditEvent
Agent PerformanceProduct team, weekly reviewIntake agent response rate, avg latency, escalation rate by reason, message classification accuracy, guardrail triggers (by type), confidence score distributionAutoFlow metrics, AuditEvent (agent_escalation, agent_guardrail_triggered), InsightFlow agent logs
Compliance & SecurityCompliance officer, real-time + weekly auditData access logs (by user), failed authentication attempts, PHI access attempts (blocked), workflow failures (by type), escalations (by category), user activity heatmapAuditEvent (all), auth service logs, InsightFlow observability stack
Pipeline HealthEngineering team, daily + on-demandEvent pipeline latency (p50/p95), data pipeline success rate, DLQ queue depth, sync conflicts (by type), scoring stale rate, error rate by pipeline versionPipeline observability (Prometheus), AuditEvent (pipeline version changes), DLQ logs

Custom Reporting & Widget Framework

InsightFlow exposes a REST API for ad-hoc queries. All data is queried through this API — no direct database access. Query timeouts: 30 seconds max. Large queries (>1M rows) must be scheduled as background jobs.

Widgets are reusable dashboard components (line chart, bar chart, KPI card, table) with configurable data source (GROQ query or predefined metric). Widgets refresh independently: some every 5 minutes (operations), others every 1 hour (compliance audit). Widget caching reduces API load and improves dashboard responsiveness.

Dashboard permissions are role-based: Admin sees all data; Location Manager sees their location only; Esthetician sees no dashboards; Reviewer (InsightFlow-only role) sees Compliance & Executive dashboards only.

Section 12

Compliance & Security


Enflow Systems is designed for HIPAA and SOC2 alignment. All data is encrypted in transit (TLS 1.3) and at rest (AES-256). Access control is role-based with explicit least-privilege scoping. Audit logs are immutable and retained for 7 years. Incident response procedures are documented and tested quarterly.

Data Classification & Protection

Data ClassificationExamplesStorageAccess ControlEncryption
PHI (Protected Health Information)Medical history, contraindications, allergies, treatment notesJotForm Health only (HIPAA BAA)Assigned esthetician only (+ compliance officer)At rest (AES-256) + in transit (TLS 1.3)
PII (Personally Identifiable Information)Name, email, phone, address, date of birthHubSpot, Vagaro, JotForm (non-PHI fields)Staff with role access to locationAt rest (AES-256) + in transit (TLS 1.3)
Sensitive Business DataPayment methods (tokenized), SMS consent status, revenue by serviceHubSpot, Vagaro (tokenized in Stripe)Ownership, location managersAt rest (AES-256) + in transit (TLS 1.3)
Audit LogsAuditEvent: who accessed what, when, whyCentral audit service (immutable)Compliance officer, legal team (upon request)At rest (AES-256) + append-only

Access Control Model

All user authentication is SSO (SAML 2.0 or OIDC). No passwords. Password reset is not applicable. User accounts are deactivated (never deleted) on staff departure.

Role-based access control (RBAC) enforces permissions:

RoleData VisibilityActions AllowedDashboard AccessPHI Access
AdminAll locations, all contacts, all dataUser mgmt, role assignment, system config, data exportsAll dashboardsAll PHI (with audit trail)
Location ManagerTheir location only (contact, appointment, task filters)Assign tasks, respond to client escalations, view reportingOperations Hub, Local metricsLocation PHI only (filtered at query)
EstheticianTheir assigned clients + appointmentsMark appointment complete, respond to client messages (in HubSpot inbox)NoneOnly their assigned client PHI
Front DeskLocation (appointments, contact names, payment status)Create contact, update phone/address, process payment failure responseNoneNone (encrypted access via task assignments)
Compliance OfficerAudit logs, escalations, data access historyAudit log review, escalation review, data retention queriesCompliance & Security dashboardVia audit logs only (no direct PHI access)

Data Retention & Deletion

Operational data (Contact, Appointment, Membership): Retained indefinitely unless client requests deletion (CCPA "right to be forgotten"). Deletion is a logical soft delete (marked deleted, not removed from database). Audit trail of the deletion is preserved.

PHI (JotForm): Retained for 7 years post-service delivery to comply with medical record retention laws. After 7 years, automatically deleted from JotForm. Retention date is calculated from last appointment date.

Audit logs (AuditEvent): Immutable and retained for 7 years minimum. Archive to cold storage after 2 years (still searchable, slower retrieval).

SMS consent: Maintained indefinitely. TCPA opt-out is honored immediately — any SMS to an opt-out contact is rejected at send time with a compliance error logged.


Incident Response Plan

Detection: Automated alerts fire on: unauthorized data access (AuditEvent anomaly), DLQ queue depth exceeding threshold, multiple failed authentication attempts from one IP, unexpected data export (bulk contact queries).

Containment (0–30 min): On-call engineer confirms incident. If data breach suspected: disable affected user accounts immediately, revoke API keys, page compliance officer and legal.

Investigation (30 min – 24 hours): Query AuditEvent for full access history. Identify: what data accessed, by whom, when, from where. Determine if PHI was involved.

Notification (24–72 hours): If PHI breached: notify all affected clients within 72 hours per HIPAA Breach Notification Rule. Document all notifications in AuditEvent and retain for 6 years.

Recovery & Learning (1 week): Post-mortem meeting. Identify root cause. Implement fix. Update incident response procedures if applicable.

Section 13

Observability & SLOs


Enflow Systems emits metrics, logs, and traces to a centralized observability stack. All components report to a single InsightFlow instance. SLOs are defined for every subsystem with explicit error budgets. Alerting is threshold-based for predictable anomalies and anomaly-based for unexpected behavior patterns.

Observability Stack

Signal TypeCollection MethodStorageRetentionQuery Latency
Metrics (counters, gauges, histograms)Prometheus scrape (every 30 sec) + push-based (time-series DB)Prometheus (hot) + Long-term storage (cold)15 days hot, 1 year coldReal-time (< 1 min)
Logs (structured JSON)App → syslog sink → log aggregatorElasticsearch / Loki30 days (hot), 7 years audit logs (archive)Real-time (< 5 sec)
Traces (request spans)OpenTelemetry SDK (automatic instrumentation)Jaeger / Tempo7 daysReal-time (< 30 sec)
Audit logs (immutable)Application → dedicated audit serviceAppend-only database7 years minimumEventual (< 1 sec)

SLO Catalog & Error Budgets

SLOs define acceptable reliability for each service. Error budget is the complement: if SLO is 99%, error budget is 1% (allowable failures). Every incident consumes error budget. Error budget exhaustion triggers "change freeze" — no new deployments until budget refreshes (monthly).

ServiceSLOError Budget / MonthMeasurement WindowConsequence (if breached)
Intake Agent response99.5%3.6 hours downtimep95 latency &lt;5 secClients wait &gt;5 sec for intake response. Escalate to front desk. Page on-call.
Event Pipeline (webhooks)99.9%43 minutes downtimep95 latency &lt;2 sec. Delivery success &gt; 99.9%.Appointments not triggering automations. DLQ queue alerts. Page on-call.
SMS Delivery99.0%7.2 hours downtimeSuccessful SMS send % (Twilio API available + contact opted in)CampaignFlow messages fail to send. Manual follow-up required. Page ops.
HubSpot Sync99.5%3.6 hours downtimeData syncs complete within 30 sec. Contact records updated &lt;2 min.Stale data in HubSpot. Duplicate contacts possible. Page on-call.
InsightFlow Dashboard99.0%7.2 hours downtimeDashboard load &lt;2 sec. Data freshness &lt;15 min.Ownership cannot view real-time metrics. Fallback to email digest only.
ScoreFlow recalculation99.0%7.2 hours downtimeScores calculated within 1 min of appointment event. Stale score audit &lt;2%.Retention sequences not triggered. At-risk clients not identified. Manual review.

Alerting Rules & Escalation

AlertConditionSeverityEscalationCooldown
Agent latency spikep95 latency &gt; 5 sec for 2+ minWarningSlack #ops-alerts15 min
Event pipeline DLQ depth&gt;10 events in DLQCriticalSlack #ops-alerts + page on-call5 min
SMS send failure rate&gt;5% failure in 15 min windowCriticalSlack + email (Twilio status) + page on-call10 min
HubSpot sync lag&gt;2 min since last successful syncWarningSlack, email to eng team10 min
PHI access anomalyNon-esthetician access to PHI, or bulk export attemptCriticalSlack #security + email compliance officer + page on-call1 min (no cooldown — each incident escalated)
Unauthorized data accessFailed auth attempt &gt; 5x from same IP in 10 minCriticalEmail security team, page on-call5 min
Section 14

Deployment Architecture


Enflow Systems runs on a managed cloud platform (AWS or equivalent) across three environments: Development (for feature work), Staging (for integration testing), and Production (live tenant data). Deployments use blue-green strategy for zero-downtime updates. Infrastructure is defined as code (Terraform). Secrets are managed through a centralized vault (AWS Secrets Manager or HashiCorp Vault).

Environment Configuration

EnvironmentPurposeComputeDatabaseData Retention & Access
DevelopmentFeature development, branch testing, integration workSingle container, auto-scaling 1–2 instancesShared Postgres (rebuilt daily from prod backup anonymized)All engineers (full access), limited scope data (randomized phone/email)
StagingPre-production integration testing, QA, compliance validationMulti-container (prod replica), auto-scaling 2–5 instancesProd backup (24h old, anonymized), refreshed nightlyAll engineers + QA team. API rate limits same as prod.
ProductionLive tenant data, real customer integrationsMulti-container (geo-distributed), auto-scaling 5–20+ instancesDedicated managed Postgres (replicated, daily backups to cold storage)On-call engineer (emergency only), ops team (read-only for dashboards)

CI/CD Pipeline

1. PUSH TO BRANCH

Developer pushes to feature branch. GitHub webhook triggers CI.

2. BUILD & TEST

Build Docker image. Run unit tests, integration tests, type check. SonarQube security scan.

FAIL: block merge. PASS: proceed to staging deploy.

3. DEPLOY TO STAGING

Blue-green deploy: new version spins up alongside old. Run smoke tests against new version. If pass: swap traffic.

4. PULL REQUEST REVIEW

Merge approval requires: 2x code review, security clearance (automated), compliance check (automated).

5. MERGE TO MAIN

Feature merged. CI automatically builds and deploys to staging again.

6. PRODUCTION DEPLOYMENT (MANUAL)

On-call engineer approves production deploy. Blue-green: new version deploys to 10% of instances. SLO monitoring for 5 min. If healthy: gradually increase to 100%. If error rate spike: auto-rollback.

Scaling Rules & Auto-Recovery

Horizontal scaling:CPU > 70% for 2 min → add 1 instance. CPU <40% for 5 min → remove 1 instance. Memory > 80% → page on-call (potential memory leak).

Auto-recovery: If a container crashes, Kubernetes automatically restarts it. If restart fails 3x within 5 min, container is marked unhealthy and removed from load balancer. Page on-call after 3 consecutive failures.

Database failover:Prod Postgres runs in HA mode (primary + replica). On primary failure, replica automatically promotes (RTO <1 min). Automated failback when primary recovers.


Secrets Management

All secrets (API keys, database passwords, encryption keys) are stored in a centralized vault, never in code or config. Secrets are injected at runtime into container environment variables. Secrets are rotated automatically: API keys every 90 days, database passwords every 180 days.

Access to secrets is logged in AuditEvent. Accessing a production secret requires on-call engineer approval (even for automation). Unapproved access attempts trigger a security alert.

Section 15

Operational Playbooks


Operational playbooks are step-by-step procedures for common scenarios: onboarding new tenants, responding to incidents, migrating data, and recovering from failures. Every playbook is executable by on-call staff without engineering escalation, when possible.

Playbook Catalog

Playbook 1: Onboard New Tenant

#StepOwnerVerification / Rollback
1Create Account record in HubSpot. Set account_id (UUID), name, timezone. Link to Vagaro location IDs.Ops adminHubSpot Account created. Confirm account_id visible in InsightFlow.
2Provision Twilio account for location. Create local phone number (1 per location). Configure webhook to Enflow webhook gateway.Ops + Eng (Twilio)Test send SMS. Confirm delivery success in InsightFlow.
3Create JotForm Health intake form for location. Map fields to HubSpot Contact schema. Deploy webhook to Enflow.Ops + ProductTest form submission. Confirm non-PHI fields sync to HubSpot.
4Provision HubSpot Vagaro API credentials. Test connection: pull test appointment, confirm in HubSpot. Deploy webhook listener.Ops + EngCreate test appointment in Vagaro. Confirm HubSpot activity log updated &lt;30 sec.
5Activate Intake Agent for location. Deploy with location name, service menu, esthetician list as context. Test with mock inquiry.Eng + ProductMock Instagram inquiry → agent responds. Qualify as intended. Create test HubSpot lead.
6Enable CampaignFlow sequences for location. Deploy pre-appointment, post-appointment, and retention sequences. Set stage triggers in HubSpot.Ops + ProductCreate test appointment. Confirm pre-appointment SMS sent at -48 hours (mock time).
7Activate ScoreFlow for location. Deploy health score model. Initialize scores for all existing contacts in Vagaro.Eng + DataRun scoreflow.score_updated trigger on test contact. Confirm ScoreFlowScore record created.
8Connect Meta Ads and Google Business. Deploy intake agent to Instagram and Google Business Messages APIs.Ops + EngSend test message from Instagram DM. Confirm agent responds. Check HubSpot lead created.
9Create InsightFlow dashboards for location. Copy Executive and Operations dashboards. Filter by account_id.Ops + AnalyticsLoad Operations dashboard. Confirm location data visible. Run reporting query.
10Invite location staff users. Create User records. Assign roles (Manager, Esthetician, Front Desk). Send SSO invitation.OpsStaff log in. Confirm location data visible. Location Manager can view all dashboards. Esthetician cannot access dashboards.

Rollback: If any step fails, revert Account record and contact support.


Playbook 2: Respond to Event Pipeline Failure (DLQ Depth > 10)

#StepTimelineSuccess Criteria
1On-call engineer paged. Check InsightFlow observability. Identify which events are in DLQ (webhook type, error message).0–5 minRoot cause identified: API timeout? Rate limit? Processing error?
2If rate limit: pause incoming webhook processing. Wait for quota reset. Retry events from DLQ.5–10 minDLQ depth &lt;5 or stable.
3If processing error: check deployment. Was a recent change introduced? Rollback if suspected.10–20 minEvent pipeline latency normalized to &lt;2 sec. DLQ queue drains.
4If API outage (HubSpot, Vagaro): page vendor support. Establish queue of events. Plan batch retry once API recovers.20+ minVendor confirms recovery. Retry all DLQ events. Confirm success.
5Post-incident: review DLQ events. Were any events lost (&gt;1 hour in DLQ)? Did any data mutations fail to propagate? Manual reconciliation if needed.1 hour post-recoveryAll events processed successfully or manually resolved. AuditEvent log complete.

Playbook 3: Recover from Agent Escalation Surge (>20% of intakes escalating)

SymptomDiagnosisRecovery
InsightFlow shows agent escalation rate spike (was 5%, now 25%)Review escalation reasons. Are they confidence failures, guardrail triggers, or out-of-scope inquiries?Check recent deployments. Revert if agent behavior changed. Retrain agent context if knowledge base stale.
Location managers report: "Intake agent not qualifying leads correctly."Intake Agent confidence threshold may be too high. Or: service menu in HubSpot out of sync with Vagaro.Update Intake Agent context with latest service menu. Lower confidence threshold to 55% (temporary). Monitor for false positives.
Front desk overwhelmed with escalated inquiries.Intake Agent working as designed. Escalation is correct behavior when confidence low.No system change. Recommend: hire second front desk staff for peak hours. Add escalation routing to secondary manager.
Section 16

Extensibility & Future Modules


Enflow Systems is architected for expansion into adjacent capabilities without architectural refactoring. New agents, pipelines, and modules are registered through the EnFlow OS manifest, inherit the same observability/audit infrastructure, and integrate via standardized trigger/condition/action model. Future modules can extend the platform without touching core code.

Extensibility Model

New Agent Development: Agents inherit a base class (Agent interface) that enforces: input/output schema, confidence scoring, guardrail checks, escalation logic. New agent is registered in OS manifest. At runtime, agent receives context (Contact, Appointment, message history) and returns response + metadata. No changes to core AutoFlow required.

New Pipeline Development: Pipelines inherit a base class (Pipeline interface) that enforces: trigger definition, processing model (sync/async), retry logic, observability hooks. Pipeline emits metrics and logs automatically. Dead-letter queue handling is built-in.

New Module Development: Modules expose entities (Contact, Appointment, etc.) and register triggers/conditions/actions. Entity schemas are versioned. Cross-module communication is via triggers (publish-subscribe) — no direct API calls between modules.


Future Module Catalog (Roadmap)

ModulePrimary FunctionTrigger Integration PointsNew Agent(s) NeededPriority
Inventory ManagementTrack service supplies (injectables, serums, etc.). Deduct on appointment completion. Alert on low stock.appointment.completed → deduct inventory. inventory.low_stock → escalate.Inventory Agent (supply reorder decisions)Phase 04
Payment Processing (Stripe)Capture payments, manage subscriptions, handle refunds. Webhook-driven reconciliation.membership.payment_failed → retry via Stripe API. charge.succeeded → log revenue to InsightFlow.None (automated)Phase 03
Esthetician Scheduling & AvailabilityManage esthetician calendars per location. Prevent double-booking. Optimize schedule gaps.appointment.created → check esthetician availability. schedule_conflict → escalate.Scheduling Optimization Agent (recommend best time slots)Phase 04
Advanced Analytics & ForecastingPredict revenue trends, service demand, client lifetime value. Recommend pricing changes.appointment.completed → feed into ML pipeline. scoreflow.score_updated → update LTV model.Forecast Agent (present trend insights to ownership)Phase 05
QuickBooks SyncSync revenue and expenses to QB. Map service types to QB items. Automate monthly reconciliation.appointment.completed → create QB invoice. payment_processed → create QB deposit.None (automated)Phase 04
Custom Integrations MarketplaceAllow tenants to plug in integrations (Mailchimp, Facebook Ads, custom CRM, etc.).All existing triggers available to plugins. Plugins define input/output schema.None (plugins are agents/pipelines)Phase 05+
Section 17

Build Plan & Milestones


Phase 03 Implementation runs 12 weeks (3 sprints of 4 weeks each). Every sprint delivers measurable ROI. Sprint 1 focuses on foundational integrations and reporting (InsightFlow live Day 1). Sprint 2 adds automation and AI agents. Sprint 3 completes the full system. Risk mitigation and dependency management are explicit in the timeline.

Phase 03 Build Schedule

SprintDurationMajor DeliverablesGo-Live MetricDependencies / Risks
Sprint 1Weeks 1–4Vagaro ↔ HubSpot API sync (appointments, contacts). InsightFlow dashboard (live Day 1). Twilio provisioning (4 numbers). JotForm intake form build.Ownership has real-time revenue visibility across 4 locations. Zero manual reporting spreadsheet assembly.Vagaro API delays. Twilio onboarding delays. → Mitigation: API credentials pre-provisioned before Sprint 1 kickoff.
Sprint 2Weeks 5–8AutoFlow integration layer. Intake Agent deployment + Instagram/Google Business connections. CampaignFlow setup (pre-appt + post-appt sequences). ScoreFlow health score model. Payment failure automation.First intake agent message → HubSpot lead in <60 sec. First appointment completion → post-visit SMS within 30 min. No manual intake admin work.Agent hallucination or over-escalation. → Mitigation: extensive testing against mock inquiries. Confidence threshold tuning. Weekly review cycle with product.
Sprint 3Weeks 9–12Full retention sequence (ScoreFlow threshold → 5-touch sequence). Lapsed client reactivation (separate module). Reporting digest automation (Monday 7am). User training + onboarding docs. Cut-over from legacy systems.All four locations running automations simultaneously. At-risk members contacted before 30-day threshold. 100% of intake via agent (zero manual front desk intake). Ownership receives digest every Monday at 7am without assembly.Staff resistance to new processes. Legacy system migration incomplete. → Mitigation: extensive hands-on training Week 10. Parallel run (old + new) for Week 11. Cut-over on specific date (Monday, Week 12).

30 / 60 / 90 Day Breakdown

Day 30 (End of Sprint 1):InsightFlow live and ownership using daily. Vagaro ↔ HubSpot sync stable. $42K annual intake labor savings validated (response time <60 sec). Measurement: agent latency p95 <5 sec, HubSpot data freshness <2 min.

Day 60 (End of Sprint 2):Intake Agent fully operational across Instagram, Google, web. All appointments generating post-visit SMS automatically. ScoreFlow identifying at-risk members. Retention sequence live at one location (pilot, full rollout Week 10). Measurement: intake agent qualification accuracy > 85%, post-visit SMS delivery > 99%, at-risk member detection latency <1 hour.

Day 90 (End of Sprint 3 + Stabilization):All workflows automated across all four locations. Zero manual intake admin. Zero manual reporting assembly. ROI measured: $181K in annual labor cost savings realized ($42K intake + $38K retention + $61K churn prevention + $18K HubSpot utilization + $22K reporting). System stable for 7+ days with <1% error rate across all pipelines.


Resourcing Assumptions

RoleCountResponsibilityNotes
Backend Engineer (Full Stack)1 FTECore platform: pipelines, webhooks, data models, database schema, API integrations.Seniority: mid+ (5+ years). Must be comfortable with event-driven architecture and async processing.
AI / LLM Engineer1 FTEAgent development: Intake Agent, Insight Agent, Compliance Agent. Prompt optimization, guardrail design, fine-tuning.Seniority: mid+ (3+ years LLM work). Claude 3.5 Sonnet experience preferred.
QA / Testing0.5 FTETest plan design, integration testing, UAT coordination, bug triage.Shared resource. Focus: integration test automation, Vagaro API scenarios.
Product Manager0.5 FTESprint planning, feature prioritization, user acceptance testing, stakeholder comms.Shared resource. Weekly sync with Serene & Co. ownership.
Ops / DevOps0.5 FTEInfrastructure provisioning, CI/CD pipeline setup, secrets management, monitoring setup.Shared resource. Pre-Sprint 1: Twilio, JotForm, Vagaro credentials. Sprint 1+: on-call rotation.
Professional Services / Training1 FTE (Weeks 10–12)Staff training, user documentation, cut-over planning, post-launch support.Ramped up Week 10. 2 weeks hands-on training at each location.

Risk Matrix & Mitigation

RiskProbabilityImpactMitigationTrigger / Owner
Vagaro API insufficient webhooks or rate limitsMedium (30%)High (2-week delay)Pre-integrate Sprint 0. Test webhook delivery at scale. Fallback to polling if webhooks fail.Week 2 integration testing. Owner: Backend Engineer.
Agent over-escalates or hallucinatesHigh (60%)Medium (front desk overwhelmed)Extensive mock testing. Confidence threshold tuning. Weekly agent performance review. Human-in-the-loop for first week.Week 5 launch. Owner: AI Engineer + Product.
Staff resistant to automation (Serene & Co. adoption)Medium (40%)High (rollout delay, reduced ROI)Early champion identification. Hands-on training Week 10. Run parallel (old + new) Week 11. Clear communication on time savings.Week 8 stakeholder interview. Owner: Product Manager.
Data migration from legacy Mailchimp incompleteLow (15%)Medium (campaign continuity gap)Pre-migration validation. Dual-write during Sprint 2. Full validation before Mailchimp decommission.Week 5 migration start. Owner: Backend Engineer.
HubSpot or Twilio service degradationLow (10%)Critical (product outage)Circuit breaker pattern. Graceful degradation (SMS → email fallback). SLA agreements pre-signed.Automated alerts. Owner: On-call engineer.

Success Criteria & Go-Live Checklist

System readiness:

✓ All four locations data syncing from Vagaro → HubSpot in <2 min

✓ Intake Agent responding to test inquiries with >85% qualification accuracy

✓ AutoFlow workflows executing with <5% error rate

✓ SMS delivery rate >99%

✓ ScoreFlow recalculating within 1 min of appointment event

✓ InsightFlow dashboards live and staffed

Organizational readiness:

✓ Staff trained on new workflows (4 location training completed)

✓ TCPA consent re-confirmation campaign complete (78% → 95% consent rate)

✓ Legacy Mailchimp decommissioned

✓ Customer comms issued (new intake process, SMS expectations)

✓ On-call rotation established (7-day support post-launch)

Post-launch (Day 1–7):On-call engineer monitoring. Daily standups with Serene & Co. ownership. Any critical bugs patched within 4 hours. Success: zero customer-impacting incidents, >95% automation completion rate, ownership satisfied with reporting.