Automation
Architecture
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
Version
v1.0 — Final
Approved by
Serene & Co. — May 16, 2026
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
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.
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.
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.
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.
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.
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 Finding | Function | Annual Labor Cost | Architecture Response | Section Reference |
|---|---|---|---|---|---|
| 1 | Lead 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 revenue | AI intake agent + AutoFlow pipeline entry | §08 Agent 1 · §07 Pipelines · §09 Auto-01 |
| 2 | Post-visit follow-up absent at 3 of 4 locations. Sarasota manual process produces 31% higher rebooking rate. | Retention | $38,000/yr labor | CampaignFlow 3-touch post-visit sequence triggered by Vagaro completion event | §07 CampaignFlow · §09 Auto-03 |
| 3 | Membership retention is reactive — at-risk clients identified monthly in meetings, too late to prevent churn. | Retention | $61,000/yr at-risk ARR | ScoreFlow Client Health Score + 5-touch reactivation sequence at 30-day threshold | §07 ScoreFlow · §08 Agent 3 |
| 4 | HubSpot 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 cost | Full HubSpot configuration: pipeline stages, contact schema, ScoreFlow, Vagaro API sync | §05 Data Model · §06 Integration Map · §07 Pipelines |
| 5 | Monthly reporting consumes 16 hours of management time across four locations with no real-time visibility between cycles. | Reporting | $22,000/yr labor | InsightFlow real-time dashboard + automated Monday digest replacing manual process entirely | §07 InsightFlow · §10 Dashboard Specs · §08 Agent 5 |
| 6 | Digital intake forms absent at two locations — paper forms transcribed manually into Vagaro by front desk staff. | Admin | $9,500/yr labor | Automated digital intake form via SMS on new-client booking confirmation | §09 Auto-06 · §08 Agent 4 |
| 7 | Meta Ads spend of $3,200/month produces leads that land in Instagram inbox with no routing, tracking, or attribution. | Marketing | Est. $28,000/yr in unattributed or lost ad spend | Meta Ads → HubSpot lead routing integration; intake agent covers Instagram DM channel | §06 Integration Map · §07 Pipelines |
| 8 | Appointment reminders are Vagaro generic only — no prep instructions, no upsell touchpoint, no add-on confirmation. | Ops / Revenue | $12,000/yr in unrealized upsell revenue | CampaignFlow pre-appointment 2-touch sequence: prep + upsell nudge at 48 hrs and 2 hrs | §07 CampaignFlow · §09 Auto-04 |
P1 Automation Opportunities Carried Forward
| Opportunity | Priority | Labor Offset / Yr | EnFlow Module | Architecture Treatment |
|---|---|---|---|---|
| AI intake agent — Instagram DM, Google, web form | P1 | $42,000 | AutoFlow + AI Agent | Fully specified in §08 Agent 1. Build sprint: Wk 7–9. |
| Post-visit follow-up sequence (3-touch, all 4 locations) | P1 | $38,000 | CampaignFlow + AutoFlow | Sequence map in §07 CampaignFlow. Trigger spec in §09 Auto-03. |
| Membership churn prediction + reactivation sequence | P1 | $61,000 | ScoreFlow + CampaignFlow | Scoring model in §07 ScoreFlow. Reactivation sequence in §07 CampaignFlow. |
| Vagaro → HubSpot bidirectional API sync | P1 | $18,000 | Pipelines + AutoFlow | Integration spec in §06. Webhook catalog documented. Sprint: Wk 4–5. |
| InsightFlow real-time dashboard (4 locations) | P1 | $22,000 | InsightFlow | KPI 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.
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
| Tool | Platform | Architectural Role | Integration Method | API Available | Action |
|---|---|---|---|---|---|
| HubSpot | Sales Hub Starter → upgrade to Professional | Primary 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 — full | Keep + Reconfigure Upgrade to Professional tier. Configure pipeline stages, contact schema, ScoreFlow properties, and AutoFlow workflows. |
Scheduling & Booking
| Tool | Platform | Architectural Role | Integration Method | Trigger Available | Action |
|---|---|---|---|---|---|
| Vagaro | Business (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 events | Keep + 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 / Channel | Platform | Architectural Role | Integration Method | Seq. Capable | Action |
|---|---|---|---|---|---|
| Twilio (new) | Twilio — to be provisioned | Primary 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. | Yes | New — Provision Provision 4 local numbers (one per location). Configure TCPA opt-out handling. Sprint 2 integration. |
| HubSpot Email | HubSpot (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. | Yes | Keep + Connect Mailchimp decommissioned at CampaignFlow go-live. Contact list migrated to HubSpot. |
| Mailchimp | Essentials | No architectural role. Being replaced by HubSpot email + CampaignFlow. Static list model is incompatible with behavioral sequencing requirements. | N/A — decommissioning | No | Replace Decommission at Sprint 3 go-live. Active subscriber list migrated to HubSpot. Cancel subscription post-migration. |
| iMessage (informal) | iPhone — staff personal | No architectural role. Being replaced by Twilio SMS via CampaignFlow. Staff personal messaging creates compliance gaps and no record trail. | N/A | No | Replace Deprecated at CampaignFlow go-live. Staff communication moves to HubSpot conversation inbox. |
Marketing & Paid Acquisition
| Tool / Channel | Platform | Architectural Role | Lead Routing Method | CRM Connection | Action |
|---|---|---|---|---|---|
| Meta Ads | Meta Business Suite | Paid 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. | Pending | Keep + Connect Add Meta Lead Ads form to active campaigns. Connect Meta → HubSpot. Sprint 2 integration. Admin access required. |
| Instagram (organic) | Highest-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. | Pending | Keep + Connect All 4 Instagram accounts connected to intake agent. Meta Business Suite admin access required. Sprint 3. | |
| Google Business | Secondary 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. | Pending | Keep + Connect Connect all 4 Google Business profiles to intake agent. Google Business API access required. Sprint 3. |
Analytics, Reporting & Data Sources
| Tool / Source | Type | KPIs It Produces | Connection Method | Dashboard Target | Action |
|---|---|---|---|---|---|
| Vagaro Reports | Native reporting / API | Revenue 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 dashboards | Keep + Connect API read access scoped to reporting endpoints. No write permissions required. Sprint 1 connection. |
| HubSpot | CRM / pipeline | Pipeline conversion rates, inquiry-to-booking rate, sequence performance, lead source attribution, ScoreFlow distribution. | HubSpot Reports API. InsightFlow native connector. | InsightFlow — Pipeline & Campaign dashboards | Keep + Connect HubSpot reporting permissions granted to InsightFlow service account. Sprint 1. |
| Meta Ads | Ad platform | Ad spend, CPM, CPC, lead form submissions, cost per confirmed booking (attributed). | Meta Marketing API. InsightFlow pulls daily. | InsightFlow — Executive Overview | Keep + Connect Meta Marketing API access via Business Suite. Sprint 2 connection. |
| Google Sheets | Manual spreadsheet | No architectural role. Was used for manual reporting assembly. Replaced entirely by InsightFlow. | N/A — decommissioning | None | Replace Deprecated at InsightFlow go-live (Sprint 1). Archived for reference. |
Internal Operations & Notifications
| Tool | Platform | Architectural Role | Integration Method | Data In / Out | Action |
|---|---|---|---|---|---|
| Slack | Slack (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 AutoFlow | New — Provision Provision workspace + 4 location channels. AutoFlow integration configured in Sprint 2. No client-facing use. |
| JotForm Health | JotForm (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. |
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) | Owner | System | Type | Trigger / Logic | EnFlow Module |
|---|---|---|---|---|---|---|
| 1 | Inquiry arrives via Instagram DM, Google Business message, or website form | System | Instagram / Google / Web | Automated | Platform message event | AutoFlow |
| 2 | AutoFlow routes inquiry to AI intake agent; HubSpot contact created with source tag and location assignment | System | AutoFlow + HubSpot | Automated | Any inbound inquiry event | AutoFlow + Pipelines |
| 3 | Intake agent responds within 60 seconds — brand-aligned greeting, service inquiry, FAQ resolution | AI Agent | Intake Agent (Claude) | Automated | AutoFlow trigger on contact creation | AutoFlow + AI Agent |
| 4 | Agent qualifies lead: service interest confirmed, location preference identified, timing established | AI Agent | Intake Agent + HubSpot | Automated | Conversation context + LLM logic | AutoFlow + Pipelines |
| 5 | Agent delivers Vagaro booking link pre-filled with location, service, and next available window | System | Intake Agent + Vagaro API | Automated | Qualification criteria met | AutoFlow |
| 6 | Lead books — Vagaro appointment.created webhook fires; HubSpot pipeline advances to "Booked"; CampaignFlow pre-appointment sequence enrolled | System | Vagaro → HubSpot | Automated | Vagaro appointment.created | AutoFlow + Pipelines + CampaignFlow |
| 7 | Edge case — complex objection or request outside agent scope: agent escalates with full conversation summary to front desk via HubSpot + Slack | Human | Front Desk + HubSpot + Slack | Human | Agent confidence threshold not met | AutoFlow |
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) | Owner | System | Type | Trigger / Logic | EnFlow Module |
|---|---|---|---|---|---|---|
| 1 | Appointment confirmed in Vagaro — appointment.created event fires AutoFlow trigger | System | Vagaro → AutoFlow | Automated | Vagaro appointment.created | AutoFlow |
| 2 | New client? AutoFlow sends JotForm Health intake form link via SMS — form must be completed before appointment | System | AutoFlow + Twilio | Automated | IF contact.is_new_client = true | AutoFlow + CampaignFlow |
| 3 | 48-hour pre-appointment SMS: personalized prep instructions based on service type (Botox — no blood thinners, avoid alcohol; HydraFacial — arrive makeup-free; etc.) + add-on suggestion | System | CampaignFlow + Twilio | Automated | 48 hrs before appointment time (Vagaro event timestamp) | CampaignFlow |
| 4 | 2-hour pre-appointment SMS: appointment confirmation + parking / arrival note for specific location | System | CampaignFlow + Twilio | Automated | 2 hrs before appointment time | CampaignFlow |
| 5 | New client intake form completed — JotForm webhook fires; non-PHI fields update HubSpot and Vagaro; contraindication flags send Slack alert to assigned esthetician | System | JotForm + HubSpot + Slack | Automated | JotForm form submission event | AutoFlow |
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) | Owner | System | Type | Trigger / Logic | EnFlow Module |
|---|---|---|---|---|---|---|
| 1 | Appointment marked complete in Vagaro — appointment.completed webhook fires | System | Vagaro → AutoFlow | Automated | Vagaro appointment.completed | AutoFlow |
| 2 | AutoFlow determines: first-visit or returning client? Routes to appropriate CampaignFlow sequence variant | System | AutoFlow + HubSpot | Automated | IF contact.visit_count = 1 → Sequence A; else → Sequence B | AutoFlow |
| 3 | Touch 1 (Day 1, 24 hrs): Personalized thank-you SMS with esthetician name and service performed | System | CampaignFlow + Twilio | Automated | 24 hrs after appointment.completed timestamp | CampaignFlow |
| 4 | Touch 2 (Day 3, 72 hrs): Rebook prompt with service-specific suggested return window (Botox: 90 days, HydraFacial: 30 days, Filler: 6 months) | System | CampaignFlow + Twilio | Automated | 72 hrs after appointment.completed | CampaignFlow |
| 5 | Touch 3 (Day 7): Google review request via SMS with direct link. First-visit clients receive longer-form email version. | System | CampaignFlow + Twilio + HubSpot Email | Automated | Day 7 after appointment.completed | CampaignFlow |
| 6 | Rebook link clicked — sequence closes; Vagaro booking link delivered; HubSpot pipeline stage updated | System | AutoFlow + Vagaro + HubSpot | Automated | Booking link click event (HubSpot tracking) | AutoFlow + Pipelines |
| 7 | Review link clicked — sequence closes; response logged in HubSpot; no further automation on this touch | System | AutoFlow + HubSpot | Automated | Review link click event | AutoFlow |
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) | Owner | System | Type | Trigger / Logic | EnFlow Module |
|---|---|---|---|---|---|---|
| 1 | ScoreFlow continuously monitors each member's Client Health Score — visit frequency vs. personal 90-day baseline updated on every Vagaro appointment event | System | ScoreFlow + Vagaro API | Automated | Continuous / updated on each appointment event | ScoreFlow |
| 2 | Client Health Score drops below 60 (30-day visit gap approaching baseline): AutoFlow triggers enrollment in Membership Reactivation Sequence (Stage 1) | System | ScoreFlow → AutoFlow | Automated | Health Score <60 threshold breach | ScoreFlow + AutoFlow |
| 3 | Touch 1 (Day 1): Warm personal check-in SMS — no discount language, service suggestion based on visit history | System | CampaignFlow + Twilio | Automated | Sequence enrollment | CampaignFlow |
| 4 | Touch 2 (Day 7): Availability note + easy booking link for their most recently visited service | System | CampaignFlow + Twilio | Automated | Day 7, no rebook response | CampaignFlow |
| 5 | Touch 3 (Day 14): Email with treatment plan reminder and what they're due for based on last service date | System | CampaignFlow + HubSpot Email | Automated | Day 14, no response | CampaignFlow |
| 6 | Touch 4 (Day 21): SMS — brief, direct. One-click booking link only. | System | CampaignFlow + Twilio | Automated | Day 21, no response | CampaignFlow |
| 7 | Touch 5 (Day 30): Human escalation — HubSpot task assigned to location manager with full engagement history, last service date, and membership value | Human | AutoFlow + HubSpot + Slack | Human | Day 30, no response to any touch | AutoFlow |
| 8 | Membership payment failure — separate trigger: immediate AutoFlow action, same-day SMS + HubSpot task to front desk for payment resolution | System / Human | AutoFlow + CampaignFlow + Twilio | Hybrid | Vagaro membership.payment_failed | AutoFlow + 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) | Owner | System | Type | Trigger / Logic | EnFlow Module |
|---|---|---|---|---|---|---|
| 1 | InsightFlow connects Vagaro, HubSpot, and Meta Ads APIs — live data available from Sprint 1 go-live | System | InsightFlow | Automated | API connections live — continuous pull | InsightFlow |
| 2 | Executive Overview dashboard updates every 15 minutes — revenue by location, booking volume, new vs. returning, membership status all visible in real time | System | InsightFlow | Automated | 15-minute API refresh interval | InsightFlow |
| 3 | Every Monday 7:00 AM — AutoFlow fires reporting trigger; InsightFlow generates 5-bullet performance digest comparing last 7 days to prior 4-week average | System | AutoFlow + InsightFlow | Automated | Scheduled: Monday 7:00 AM | AutoFlow + InsightFlow |
| 4 | Digest delivered via email and SMS to ownership (3 recipients) — no assembly, no manual data pulls | System | InsightFlow + HubSpot Email + Twilio | Automated | Triggered by AutoFlow weekly digest rule | InsightFlow + CampaignFlow |
| 5 | Threshold alert: if any location's weekly revenue drops >15% below prior 4-week average — immediate SMS + email alert to ownership | System | InsightFlow + Twilio + HubSpot | Automated | Revenue threshold breach — real-time | InsightFlow + AutoFlow |
| 6 | Location manager review — dashboard available 24/7 on any device; no export, no spreadsheet, no compilation required | Human | InsightFlow dashboard | Human (optional) | On demand | InsightFlow |
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) | Owner | System | Type | Trigger / Logic | EnFlow Module |
|---|---|---|---|---|---|---|
| 1 | ScoreFlow detects 90 days since last Vagaro appointment for a non-member client — Client Health Score drops to "Lapsed" band | System | ScoreFlow + Vagaro | Automated | Health Score <30 threshold (90-day gap) | ScoreFlow |
| 2 | AutoFlow enrolls client in Lapsed Reactivation sequence — distinct from Membership Retention sequence (non-members only) | System | AutoFlow + CampaignFlow | Automated | ScoreFlow threshold breach | AutoFlow |
| 3 | Touch 1 (Day 1): Email — warm, personal. Reference to last service and esthetician by name. No discount. Simple "we'd love to see you again." | System | CampaignFlow + HubSpot Email | Automated | Sequence day 1 | CampaignFlow |
| 4 | Touch 2 (Day 10): SMS — brief booking link with last service pre-selected as default. | System | CampaignFlow + Twilio | Automated | Day 10, no booking | CampaignFlow |
| 5 | Touch 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). | System | CampaignFlow + HubSpot Email | Automated | Day 25, no booking | CampaignFlow |
| 6 | Client books at any point in sequence — sequence closes; HubSpot pipeline re-enters "Booked" stage; ScoreFlow resets health score on next appointment.completed event | System | AutoFlow + HubSpot + ScoreFlow | Automated | Vagaro appointment.created event | AutoFlow + 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.
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
| Entity | Purpose | Key Properties | Owned By |
|---|---|---|---|
| Account | Root organization unit. All data is scoped by Account ID. Supports multi-location brands. | id, name, industry, timezone, status (active/paused), created_at, updated_at | HubSpot |
| Location | Physical 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_at | Vagaro (source) + HubSpot (sync) |
| Contact | Individual — 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_at | HubSpot (primary) + Vagaro (appointments only) |
| Role | Permission group. Admin, Manager, Esthetician, Front Desk, Reviewer (for InsightFlow). Scoped per Account. | id, account_id, name, permissions (array), created_at | HubSpot User Management |
| User | Staff 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_at | HubSpot (via SSO) or EnFlow OS auth service |
Operational Entities
| Entity | Purpose | Key Properties | Owner |
|---|---|---|---|
| Appointment | Service 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_id | Vagaro (source) → HubSpot (sync) |
| Lead | Pre-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_id | HubSpot CRM |
| Membership | Recurring 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_at | Vagaro (source) → HubSpot (sync) |
| WorkflowRun | Instance 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_log | AutoFlow / CampaignFlow |
| WorkflowNode | Individual 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_message | AutoFlow / CampaignFlow |
| ClientMessage | Inbound 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_id | Twilio / HubSpot / Chat provider |
| AuditEvent | Immutable 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_agent | EnFlow OS audit service |
| File | Document 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_at | Document Storage module |
| ScoreFlowScore | Computed 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_recalc | ScoreFlow |
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 Module | Primary Entity Consumed | Data Flow / Integration Point | Output / Mutation |
|---|---|---|---|
| AutoFlow | Lead, Appointment, Contact, Membership | Vagaro appointment events trigger AutoFlow workflows. HubSpot Contact fields (source, status) determine routing logic. | WorkflowRun records; ClientMessage (SMS/email); HubSpot Contact stage updates |
| CampaignFlow | Contact, 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 |
| ScoreFlow | Contact, Appointment, Membership | Continuous ingestion from Vagaro (appointment history) and HubSpot (lifecycle stage). Appointment.completed triggers score recalculation. | ScoreFlowScore; score_band triggers (e.g., health_score <60 → enroll in AutoFlow retention sequence) |
| InsightFlow | Appointment, 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 Hub | Contact, 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 |
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
| System | Primary Role | Sync Direction & Frequency | Authentication | Error Handling & Fallback |
|---|---|---|---|---|
| Vagaro | Booking 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_failed | API 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. |
| HubSpot | Operational 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. |
| Twilio | SMS 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 >10 mins, page on-call. Inbound webhook failure: Twilio retries 3 times. Dead messages logged for manual investigation. |
| JotForm Health | HIPAA-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 Business | Inbound 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 Type | Source → Destination | Sync Trigger | Conflict Resolution | Reconciliation |
|---|---|---|---|---|
| Contact | Vagaro → HubSpot | client.created, appointment.created (new client) | HubSpot wins if contact already exists (contact deduplication by email) | 30-min batch: compare record counts per location |
| Appointment | Vagaro → HubSpot | appointment.created, appointment.completed, appointment.cancelled webhook | N/A (append-only; no overwrites) | Daily: compare appointment count by date range |
| Membership | Vagaro → HubSpot | client.created, membership.created webhook event | HubSpot wins if membership already exists (dedup by Vagaro ID) | Weekly: audit membership status discrepancies |
| Non-PHI form data | JotForm → HubSpot + Vagaro | JotForm form submission | HubSpot wins (phone, email). Vagaro custom fields populated from HubSpot. | Manual: intake form review if field mismatch detected |
| SMS delivery status | Twilio → HubSpot | Twilio 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:
| Endpoint | Rate Limit | Throttle Behavior | Billing Impact |
|---|---|---|---|
| Vagaro API (contact read, appointment query) | 100 req/min per account | Queue and retry with backoff | No overage; queued requests processed at next window |
| HubSpot API (contact update, deal creation) | 200 req/min per account | Queue and retry | Each API call billable; queued calls processed normally |
| Twilio SMS send | 50 msg/sec per account | Buffer; send at max rate | Each SMS billable regardless of queueing |
| Meta Lead Ads sync | 10 req/sec per account | Queue with backoff | No impact (read-only) |
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 Name | Source Event | Payload (Context) | Consuming Modules |
|---|---|---|---|
| contact.created | New inquiry via intake form or agent | contact_id, name, phone, email, source_channel, location_id, timestamp | AutoFlow (lead qualification), CampaignFlow (welcome sequence), ScoreFlow (baseline health score) |
| contact.updated | HubSpot contact field change (pipeline stage, SMS consent, etc.) | contact_id, changed_fields (JSON), before_state, after_state, timestamp | ScoreFlow (score recalculation if visit history updated), AutoFlow (conditional routing on status change) |
| appointment.completed | Vagaro appointment.completed webhook | appointment_id, contact_id, service_type, location_id, completed_at, duration_minutes, staff_id | ScoreFlow (health score update), CampaignFlow (post-visit sequence enrollment), AutoFlow (booking confirmation routing) |
| appointment.noshow | Vagaro appointment marked no-show | appointment_id, contact_id, scheduled_time, location_id, timestamp | ScoreFlow (negative factor in health score), AutoFlow (escalation to location manager) |
| membership.payment_failed | Vagaro membership billing failure | membership_id, contact_id, amount, failure_reason, retry_at, timestamp | AutoFlow (same-day SMS + task escalation), CampaignFlow (payment recovery sequence) |
| scoreflow.score_updated | ScoreFlow recalculation completes | contact_id, old_score, new_score, old_band, new_band, factors (JSON), timestamp | AutoFlow (threshold-based sequence enrollment; e.g., health_score <60 → retention sequence) |
| message.inbound | Inbound SMS reply or chat from contact | contact_id, channel (sms/chat), message_body, timestamp, provider_message_id | AutoFlow (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 Name | Predicate | Data Source | Usage Example |
|---|---|---|---|
| contact.is_new_client | TRUE if contact.visit_count == 0 | HubSpot Contact + Vagaro history | IF is_new_client → Send intake form (JotForm) instead of rebook prompt |
| contact.has_sms_consent | TRUE if contact.consent_sms == true AND consent_date valid | HubSpot Contact consent property | IF NOT has_sms_consent → Send email instead of SMS |
| scoreflow.health_band | Equals: "active", "at_risk", or "lapsed" | ScoreFlow score band | IF health_band == "at_risk" → Enroll in retention sequence |
| appointment.service_type_matches | Appointment.service_type IN (list) | Vagaro appointment | IF service_type IN ["Botox", "Filler"] → Send injectables-specific prep instructions |
| membership.is_active | TRUE if membership.status == "active" AND next_billing_date > today | Vagaro membership | IF 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.
| Action | Output / Side Effect | Retry Behavior | Logging / Audit | Escalation |
|---|---|---|---|---|
| send_sms | SMS message delivered via Twilio. ClientMessage record created. Delivery status tracked. | 3 retries, exp. backoff. Max 2 minutes. | AuditEvent: action, contact_id, message_id, status, timestamp | After 3 failures: log to ops dashboard + page on-call if >50 msgs failed in 10 mins |
| send_email | Email 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, status | HubSpot unsubscribe → remove contact from future email sequences |
| update_contact | HubSpot 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, timestamp | If contact does not exist: create new contact first, then apply update |
| create_task | HubSpot 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_date | Task creation failure: send Slack alert to #ownership-alerts with full workflow context |
| enroll_workflow | Contact 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, timestamp | None; enrollment is append-only. Failed enrollments logged for ops review. |
| send_slack_notification | Message 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, status | None; Slack is informational only. Failures do not block workflows. |
Cross-Module Event Propagation
Events flow bidirectionally between modules. No module is isolated.
| From Module | Event Type | To Module(s) | Action / Reaction |
|---|---|---|---|
| Integrations Hub | contact.created (inbound inquiry) | AutoFlow, ScoreFlow | AutoFlow: enroll in lead-intake workflow. ScoreFlow: initialize Client Health Score. |
| AutoFlow | workflow.enrolled | CampaignFlow | CampaignFlow: if workflow type is campaign, automatically enroll contact in corresponding sequence. |
| ScoreFlow | score_updated (health_score <60) | AutoFlow | AutoFlow: trigger retention enrollment if not already enrolled. Check contact status to avoid duplicate sequences. |
| CampaignFlow | message.inbound (customer reply) | AutoFlow | AutoFlow: if inbound message contains booking link click or affirmative intent, terminate sequence and advance pipeline stage. |
| AutoFlow | action.failed (e.g., send_sms failed 3x) | InsightFlow | InsightFlow: log failure in observability. If threshold exceeded (10+ failures/min), alert ops team. |
| Vagaro | membership.payment_failed webhook | AutoFlow, ScoreFlow | AutoFlow: 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:
| Metric | Target SLO | Alert Threshold | Owner / Escalation |
|---|---|---|---|
| Inbound message response time (agent) | p95 <5 sec | >10 sec for 5+ msgs | On-call eng |
| AutoFlow workflow execution success rate | 99.9% | < 99.5% | On-call eng |
| SMS delivery rate | 99% | < 98% | Twilio support + ops |
| HubSpot contact sync latency | p95 <30 sec | >60 sec | Engineering |
| InsightFlow dashboard responsiveness | p95 <2 sec | >5 sec | On-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.
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 Name | Primary Function | Input Sources | Output / Actions |
|---|---|---|---|
| Intake Agent | Handle 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 menu | Response message (brand-aligned greeting + info delivery), HubSpot Lead creation, Vagaro booking link injection, Slack escalation (if needed) |
| Scheduling Agent | Assist 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 data | Rescheduling confirmation, cancellation acknowledgment, HubSpot activity log entry, Slack notification to location manager (for high-value cancellations) |
| Compliance Agent | Monitor 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 logs | Flag or clear-to-proceed signal, Slack alert to compliance team (if flag detected), AuditEvent log entry |
| Insight Agent | Analyze 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 score | Upsell 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
| Boundary | Rule | Violation Behavior | Audit Log |
|---|---|---|---|
| Medical advice | Agent 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 transactions | Agent 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 access | Agent 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 threshold | If agent confidence <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 inquiry | Agent 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.
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 Type | Trigger | Processing Model | Output | SLO |
|---|---|---|---|---|
| Event | Webhook (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 <2 sec (acknowledge) + p95 <5 sec (execution) |
| Data | Scheduled: 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 <30 sec per pull (not including network latency) |
| Scoring | On 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 <1 sec per contact |
| Sync | On 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 <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
| Metric | Collection | Alert Threshold | Escalation |
|---|---|---|---|
| Event pipeline latency (p95) | Per webhook type | >5 sec | Slack #ops-alerts + page on-call |
| Data pipeline success rate | Per source (Vagaro, HubSpot, Meta) | < 95% | Slack + email to eng team |
| Sync conflict rate | Per data type (Contact, Appointment, Membership) | >5 conflicts/hour | Page on-call + create manual review ticket |
| DLQ queue depth | Per pipeline | >10 events | Slack alert, manual review required |
| Scoring pipeline stale scores | Daily audit | >2% of contacts | Slack alert + trigger full recalc batch |
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 Trigger | Condition | Action | Assignment |
|---|---|---|---|
| Agent confidence low | Intake Agent confidence <60% | Stop responding to client. Create HubSpot task with full conversation. | Location manager (based on contact location) |
| Medical escalation | Client asks for medical advice or reports contraindication | Route to esthetician via Slack + HubSpot task. Esthetician responds directly. | Assigned esthetician (from appointment record) |
| Payment failure | Membership payment fails 2x in 7 days | Create task for location manager. SMS to client with payment retry link. | Location front desk |
| High churn risk | ScoreFlow health score <30 (lapsed) | Create task for location manager. Recommended talking points provided in task. | Location manager (high-value client override: owner) |
| Workflow failure | Action 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.
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
| Dashboard | Primary Audience | Core Metrics | Data Sources |
|---|---|---|---|
| Executive Overview | Ownership, monthly + real-time review | Revenue (by location, by service), new bookings, membership count, churn rate (weekly), aggregate agent response time, top upsell opportunity | Vagaro API (15m), HubSpot (15m), Meta Ads API (daily), ScoreFlow |
| Operations Hub | Location managers, daily monitoring | Appointments 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 Performance | Product team, weekly review | Intake agent response rate, avg latency, escalation rate by reason, message classification accuracy, guardrail triggers (by type), confidence score distribution | AutoFlow metrics, AuditEvent (agent_escalation, agent_guardrail_triggered), InsightFlow agent logs |
| Compliance & Security | Compliance officer, real-time + weekly audit | Data access logs (by user), failed authentication attempts, PHI access attempts (blocked), workflow failures (by type), escalations (by category), user activity heatmap | AuditEvent (all), auth service logs, InsightFlow observability stack |
| Pipeline Health | Engineering team, daily + on-demand | Event pipeline latency (p50/p95), data pipeline success rate, DLQ queue depth, sync conflicts (by type), scoring stale rate, error rate by pipeline version | Pipeline 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.
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 Classification | Examples | Storage | Access Control | Encryption |
|---|---|---|---|---|
| PHI (Protected Health Information) | Medical history, contraindications, allergies, treatment notes | JotForm 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 birth | HubSpot, Vagaro, JotForm (non-PHI fields) | Staff with role access to location | At rest (AES-256) + in transit (TLS 1.3) |
| Sensitive Business Data | Payment methods (tokenized), SMS consent status, revenue by service | HubSpot, Vagaro (tokenized in Stripe) | Ownership, location managers | At rest (AES-256) + in transit (TLS 1.3) |
| Audit Logs | AuditEvent: who accessed what, when, why | Central 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:
| Role | Data Visibility | Actions Allowed | Dashboard Access | PHI Access |
|---|---|---|---|---|
| Admin | All locations, all contacts, all data | User mgmt, role assignment, system config, data exports | All dashboards | All PHI (with audit trail) |
| Location Manager | Their location only (contact, appointment, task filters) | Assign tasks, respond to client escalations, view reporting | Operations Hub, Local metrics | Location PHI only (filtered at query) |
| Esthetician | Their assigned clients + appointments | Mark appointment complete, respond to client messages (in HubSpot inbox) | None | Only their assigned client PHI |
| Front Desk | Location (appointments, contact names, payment status) | Create contact, update phone/address, process payment failure response | None | None (encrypted access via task assignments) |
| Compliance Officer | Audit logs, escalations, data access history | Audit log review, escalation review, data retention queries | Compliance & Security dashboard | Via 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.
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 Type | Collection Method | Storage | Retention | Query 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 cold | Real-time (< 1 min) |
| Logs (structured JSON) | App → syslog sink → log aggregator | Elasticsearch / Loki | 30 days (hot), 7 years audit logs (archive) | Real-time (< 5 sec) |
| Traces (request spans) | OpenTelemetry SDK (automatic instrumentation) | Jaeger / Tempo | 7 days | Real-time (< 30 sec) |
| Audit logs (immutable) | Application → dedicated audit service | Append-only database | 7 years minimum | Eventual (< 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).
| Service | SLO | Error Budget / Month | Measurement Window | Consequence (if breached) |
|---|---|---|---|---|
| Intake Agent response | 99.5% | 3.6 hours downtime | p95 latency <5 sec | Clients wait >5 sec for intake response. Escalate to front desk. Page on-call. |
| Event Pipeline (webhooks) | 99.9% | 43 minutes downtime | p95 latency <2 sec. Delivery success > 99.9%. | Appointments not triggering automations. DLQ queue alerts. Page on-call. |
| SMS Delivery | 99.0% | 7.2 hours downtime | Successful SMS send % (Twilio API available + contact opted in) | CampaignFlow messages fail to send. Manual follow-up required. Page ops. |
| HubSpot Sync | 99.5% | 3.6 hours downtime | Data syncs complete within 30 sec. Contact records updated <2 min. | Stale data in HubSpot. Duplicate contacts possible. Page on-call. |
| InsightFlow Dashboard | 99.0% | 7.2 hours downtime | Dashboard load <2 sec. Data freshness <15 min. | Ownership cannot view real-time metrics. Fallback to email digest only. |
| ScoreFlow recalculation | 99.0% | 7.2 hours downtime | Scores calculated within 1 min of appointment event. Stale score audit <2%. | Retention sequences not triggered. At-risk clients not identified. Manual review. |
Alerting Rules & Escalation
| Alert | Condition | Severity | Escalation | Cooldown |
|---|---|---|---|---|
| Agent latency spike | p95 latency > 5 sec for 2+ min | Warning | Slack #ops-alerts | 15 min |
| Event pipeline DLQ depth | >10 events in DLQ | Critical | Slack #ops-alerts + page on-call | 5 min |
| SMS send failure rate | >5% failure in 15 min window | Critical | Slack + email (Twilio status) + page on-call | 10 min |
| HubSpot sync lag | >2 min since last successful sync | Warning | Slack, email to eng team | 10 min |
| PHI access anomaly | Non-esthetician access to PHI, or bulk export attempt | Critical | Slack #security + email compliance officer + page on-call | 1 min (no cooldown — each incident escalated) |
| Unauthorized data access | Failed auth attempt > 5x from same IP in 10 min | Critical | Email security team, page on-call | 5 min |
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
| Environment | Purpose | Compute | Database | Data Retention & Access |
|---|---|---|---|---|
| Development | Feature development, branch testing, integration work | Single container, auto-scaling 1–2 instances | Shared Postgres (rebuilt daily from prod backup anonymized) | All engineers (full access), limited scope data (randomized phone/email) |
| Staging | Pre-production integration testing, QA, compliance validation | Multi-container (prod replica), auto-scaling 2–5 instances | Prod backup (24h old, anonymized), refreshed nightly | All engineers + QA team. API rate limits same as prod. |
| Production | Live tenant data, real customer integrations | Multi-container (geo-distributed), auto-scaling 5–20+ instances | Dedicated 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.
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
| # | Step | Owner | Verification / Rollback |
|---|---|---|---|
| 1 | Create Account record in HubSpot. Set account_id (UUID), name, timezone. Link to Vagaro location IDs. | Ops admin | HubSpot Account created. Confirm account_id visible in InsightFlow. |
| 2 | Provision 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. |
| 3 | Create JotForm Health intake form for location. Map fields to HubSpot Contact schema. Deploy webhook to Enflow. | Ops + Product | Test form submission. Confirm non-PHI fields sync to HubSpot. |
| 4 | Provision HubSpot Vagaro API credentials. Test connection: pull test appointment, confirm in HubSpot. Deploy webhook listener. | Ops + Eng | Create test appointment in Vagaro. Confirm HubSpot activity log updated <30 sec. |
| 5 | Activate Intake Agent for location. Deploy with location name, service menu, esthetician list as context. Test with mock inquiry. | Eng + Product | Mock Instagram inquiry → agent responds. Qualify as intended. Create test HubSpot lead. |
| 6 | Enable CampaignFlow sequences for location. Deploy pre-appointment, post-appointment, and retention sequences. Set stage triggers in HubSpot. | Ops + Product | Create test appointment. Confirm pre-appointment SMS sent at -48 hours (mock time). |
| 7 | Activate ScoreFlow for location. Deploy health score model. Initialize scores for all existing contacts in Vagaro. | Eng + Data | Run scoreflow.score_updated trigger on test contact. Confirm ScoreFlowScore record created. |
| 8 | Connect Meta Ads and Google Business. Deploy intake agent to Instagram and Google Business Messages APIs. | Ops + Eng | Send test message from Instagram DM. Confirm agent responds. Check HubSpot lead created. |
| 9 | Create InsightFlow dashboards for location. Copy Executive and Operations dashboards. Filter by account_id. | Ops + Analytics | Load Operations dashboard. Confirm location data visible. Run reporting query. |
| 10 | Invite location staff users. Create User records. Assign roles (Manager, Esthetician, Front Desk). Send SSO invitation. | Ops | Staff 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)
| # | Step | Timeline | Success Criteria |
|---|---|---|---|
| 1 | On-call engineer paged. Check InsightFlow observability. Identify which events are in DLQ (webhook type, error message). | 0–5 min | Root cause identified: API timeout? Rate limit? Processing error? |
| 2 | If rate limit: pause incoming webhook processing. Wait for quota reset. Retry events from DLQ. | 5–10 min | DLQ depth <5 or stable. |
| 3 | If processing error: check deployment. Was a recent change introduced? Rollback if suspected. | 10–20 min | Event pipeline latency normalized to <2 sec. DLQ queue drains. |
| 4 | If API outage (HubSpot, Vagaro): page vendor support. Establish queue of events. Plan batch retry once API recovers. | 20+ min | Vendor confirms recovery. Retry all DLQ events. Confirm success. |
| 5 | Post-incident: review DLQ events. Were any events lost (>1 hour in DLQ)? Did any data mutations fail to propagate? Manual reconciliation if needed. | 1 hour post-recovery | All events processed successfully or manually resolved. AuditEvent log complete. |
Playbook 3: Recover from Agent Escalation Surge (>20% of intakes escalating)
| Symptom | Diagnosis | Recovery |
|---|---|---|
| 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. |
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)
| Module | Primary Function | Trigger Integration Points | New Agent(s) Needed | Priority |
|---|---|---|---|---|
| Inventory Management | Track 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 & Availability | Manage 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 & Forecasting | Predict 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 Sync | Sync 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 Marketplace | Allow 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+ |
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
| Sprint | Duration | Major Deliverables | Go-Live Metric | Dependencies / Risks |
|---|---|---|---|---|
| Sprint 1 | Weeks 1–4 | Vagaro ↔ 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 2 | Weeks 5–8 | AutoFlow 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 3 | Weeks 9–12 | Full 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
| Role | Count | Responsibility | Notes |
|---|---|---|---|
| Backend Engineer (Full Stack) | 1 FTE | Core 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 Engineer | 1 FTE | Agent 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 / Testing | 0.5 FTE | Test plan design, integration testing, UAT coordination, bug triage. | Shared resource. Focus: integration test automation, Vagaro API scenarios. |
| Product Manager | 0.5 FTE | Sprint planning, feature prioritization, user acceptance testing, stakeholder comms. | Shared resource. Weekly sync with Serene & Co. ownership. |
| Ops / DevOps | 0.5 FTE | Infrastructure 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 / Training | 1 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
| Risk | Probability | Impact | Mitigation | Trigger / Owner |
|---|---|---|---|---|
| Vagaro API insufficient webhooks or rate limits | Medium (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 hallucinates | High (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 incomplete | Low (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 degradation | Low (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.