Skip to main content
Synced from the repo — do not edit here

Canonical source: docs/SUPPORT_BOT_SPEC.md. This page is generated by docs/scripts/sync-handbook.mjs. Edit the source file in the repo; changes appear here on the next build.

Basis Support Bot Specification

Status: Planning
Last Updated: 2026-02-07
Owner: Engineering Team

This document captures the architecture, design decisions, and implementation plan for the Basis staff support bot.


Overview

A support mode for the existing CopilotDrawer that helps staff with operational questions (configuration, troubleshooting, integrations) using RAG over documentation. When uncertain, the bot drafts a message for Slack escalation.

Goals

  1. Answer common staff questions about Basis configuration
  2. Reduce support burden with self-service documentation
  3. Learn from escalations to improve over time
  4. Design for future MCP integration (external agents)

Non-Goals

  • Not a replacement for clinical Copilot (that remains separate)
  • Not accessible to clients (staff-only)
  • No code/API discussions (operational focus only)

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ Basis Flow Web │
│ │
│ CopilotDrawer │
│ ├── Mode Toggle: Clinical | Support │
│ ├── Support-specific suggestions │
│ └── Escalation UI (when bot is uncertain) │
│ │
└─────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────┐
│ Firebase Functions │
│ │
│ clinical_agent_stream (modified) │
│ ├── mode='clinical' → existing agent (unchanged) │
│ └── mode='support' → support RAG chain │
│ │
│ functions_support.py (new) │
│ ├── query_support_rag() → reusable for MCP │
│ └── escalate_to_support() → Slack webhook │
│ │
└─────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────┐
│ Vertex AI Matching Engine │
│ │
│ Index: support_kb │
│ ├── docs/clinician-onboarding/*.md │
│ └── docs/integrations/*.md │
│ │
└─────────────────────────────────────────────────────────────────┘

Key Decisions

DecisionChoiceRationale
RAG approachVertex AI Matching EngineEnterprise-grade, scalable
Default modelGemini 2.0 FlashFast, cheap for support Q&A
Uncertainty detectionLow similarity score (<0.6)Automatic, tunable
Escalation channelExisting SLACK_WEBHOOK_URLAlready configured
Offline supportEmail support@basishealth.ioNo platform changes needed
MCP compatibilityBuilt-in from startresponse_format param

Correct UI Paths & Terminology

CRITICAL: These are verified from the codebase. Do not assume paths.

Sidebar ItemLocationContains
Marketplace/marketplaceServices, Products, Memberships (tabs)
Settings/settingsOrganization, Integrations, Permissions, etc.
Staff/staffStaff list, individual profiles with Availability
Clients/clientsClient list, individual profiles
Schedule/calendarCalendar view

Key Settings Paths

FeaturePathNotes
Clinic CodeSettings → Organization → Clinic CodeStaff share this with clients to join
Role EditingSettings → PermissionsChange staff roles, customize permissions
IntegrationsSettings → IntegrationsStripe, Zoom connections
LocationsSettings → Organization → LocationsAdd/edit clinic locations

Marketplace Structure

TabContains
ServicesService definitions (duration, buffers, remote toggle, group settings)
ProductsPhysical/digital products for sale
MembershipsMembership plans with benefits, booking rules, location access

Staff Availability

  • Location: Staff → [Staff Member] → Availability tab
  • V1 Blocks: Weekly recurring hours per location
  • V2 Rules: Flexible rules with start/end dates, interval weeks, unavailable blocks
  • Temporary Availability: Use V2 rules with specific date range

Staff Roles (Actual)

From hybrid/basisflow-web/lib/permissions.ts:

RoleKey Capabilities
AdminFull access to all features
ManagerScheduling, staff/client management, can refund, view reports (no revenue)
MedicalClinical staff - can book/cancel, view health data, add notes
CoachView-only schedule/clients, view health data, can add notes
Customer ServiceFront-of-house - scheduling, client/staff management, forms

Role Editing

Roles are changed via Settings → Permissions, not on individual staff profiles.


Documentation Structure

Files to Create

docs/docs/clinician-onboarding/
├── troubleshooting-booking.md # Booking/scheduling issues
├── troubleshooting-memberships.md # Membership configuration
├── troubleshooting-providers.md # Provider/staff setup
├── troubleshooting-clients.md # Client access issues
└── troubleshooting-data.md # Reports/data/sync issues

Content Sections per Issue Type

Each troubleshooting section should include:

  1. Symptoms - What the user sees/reports
  2. Common Causes - Numbered list of likely reasons
  3. Resolution Steps - Step-by-step with exact UI paths
  4. Escalate if - When to contact Basis support

Booking Issues (troubleshooting-booking.md)

  • No available times showing
  • Client can't see certain services
  • Booking blocked by limits (free booking, advance window)
  • Wrong provider showing (or missing)
  • Location access issues
  • Group session confusion (capacity, waitlist)
  • Cancellation policy questions

Membership Issues (troubleshooting-memberships.md)

  • Free booking limits (how they work, when they reset)
  • Booking windows (min/max advance time)
  • How to verify setup

Provider Issues (troubleshooting-providers.md)

  • Setting availability (weekly hours per location)
  • Temporary availability (V2 rules with date ranges)
  • Linking providers to services
  • Role permissions explained
  • Multi-location providers

Client Issues (troubleshooting-clients.md)

  • Invite not received (check spam, verify email)
  • Invite expired (how to resend - NOTE: Resend not yet implemented)
  • Clinic code usage (clients enter code in app to join)
  • Login issues (password reset, email verification)
  • Health data connection (Apple Health, Terra/wearables)

Data Issues (troubleshooting-data.md)

  • Metrics not showing (connection, sync delay, timezone)
  • Lab import (upload PDF, manual entry)
  • Data sync issues (Terra reconnection)

Backend Implementation

New File: functions_support.py

# Reusable support RAG function (MCP-ready)
def query_support_rag(
question: str,
response_format: str = "markdown", # "markdown" | "json"
context: dict | None = None,
) -> SupportResult:
"""
Query support knowledge base.

Returns:
SupportResult with answer, sources, similarity_score, uncertain flag
"""

# Slack escalation
@https_fn.on_call(secrets=[SLACK_WEBHOOK_URL_PARAM])
def escalate_to_support(req: https_fn.CallableRequest) -> dict:
"""Post support request to Slack with log linking."""

Modify: functions_ai_agent.py

Add mode parameter to AgentStreamRequest:

class AgentStreamRequest(BaseModel):
# ... existing fields ...
mode: str | None = None # 'clinical' | 'support'

Branch in clinical_agent_stream:

if data.mode == 'support':
from .functions_support import query_support_rag
result = query_support_rag(data.query, "markdown")
# Stream to RTDB, log to support_logs
else:
# Existing clinical agent flow
run_agent(...)

Logging & Learning Loop

Firestore Schema: support_logs

interface SupportLog {
// Client identification
client_type: 'staff' | 'mcp_agent'; // Future: MCP agents
clinic_id: string;
user_id: string;
user_email: string;

// Interaction
question: string;
response: string;
similarity_score: number;
sources_used: string[];

// Outcome
escalated: boolean;
escalated_at?: Timestamp;
resolution?: string;
should_add_to_docs: boolean;

// Metadata
created_at: Timestamp;
session_id?: string;
}

Firestore Schema: suggested_docs

interface SuggestedDoc {
from_log_id: string;
question: string;
resolution: string;

suggested_title: string;
suggested_content: string;
suggested_section: string;

status: 'pending' | 'approved' | 'rejected';
reviewed_by?: string;
reviewed_at?: Timestamp;

created_at: Timestamp;
}

Learning Flow

  1. All support interactions logged to support_logs
  2. Escalated questions marked with escalated: true
  3. Human resolution captured back to log
  4. Weekly analysis identifies patterns
  5. Bot suggests new doc entries
  6. Human reviews/approves
  7. Approved content re-indexed

Codebase Change Detection (Future)

Weekly cron job to detect changes that may need documentation:

  1. Run git diff --name-only HEAD~7
  2. Analyze changed files for:
    • New routes/pages
    • New settings fields
    • Permission changes
    • New components/modals
  3. Create suggested_docs entries with type: 'codebase_change'
  4. Alert via Slack

MCP Compatibility (Future)

The query_support_rag function is designed to be called from:

  1. Staff CopilotDrawer (now): response_format="markdown"
  2. MCP ask_support tool (future): response_format="json"

JSON response format:

{
"answer": "Step-by-step guidance...",
"sources": [{"title": "...", "section": "...", "path": "..."}],
"confidence": 0.87,
"escalate_suggested": false
}

Implementation Phases

Phase 1: Documentation

  • Create 5 troubleshooting docs
  • Validate content with product team

Phase 2: Infrastructure

  • Create support_logs Firestore collection
  • Add Firestore rules
  • Create Vertex AI Matching Engine index

Phase 3: Backend

  • Create functions_support.py
  • Add mode param to clinical_agent_stream
  • Implement logging

Phase 4: Frontend

  • Add mode toggle to CopilotDrawer
  • Implement escalation UI
  • Add support-specific suggestions

Phase 5: Learning Loop

  • Weekly analysis function
  • Suggestion generation
  • Admin review UI

Known Gaps / TODO

  • Resend Invite button not implemented in Basis Flow Web
  • No SMS invite option
  • Need to verify exact wording of error messages for troubleshooting docs
  • Need to confirm membership free booking limit reset timing (monthly? billing cycle?)
  • Temporary availability UI needs documentation

References

  • Navigation: hybrid/basisflow-web/app/(main)/layout.tsx (lines 273-288)
  • Permissions: hybrid/basisflow-web/lib/permissions.ts
  • Roles: basis-functions/functions/src/functions_clinic.py (lines 7255-7360)
  • Availability V2: hybrid/basisflow-web/lib/availability-resolver.ts
  • Marketplace: hybrid/basisflow-web/app/(main)/marketplace/page.tsx
  • Settings: hybrid/basisflow-web/app/(main)/settings/page.tsx