A production-grade ChatGPT-class assistant with health intelligence. Features St. Raphael (health companion), autonomous task execution, and daily progress tracking. Built with React, TypeScript, Tailwind CSS, and Supabase.
- Node.js 18+ and npm
- Supabase account (https://supabase.com)
- OpenAI API key (https://platform.openai.com/api-keys)
# 1. Install dependencies
npm install
# 2. Copy environment template
cp .env.example .env
# 3. Add your Supabase credentials to .env
# Get these from: https://supabase.com/dashboard/project/YOUR_PROJECT/settings/api
VITE_SUPABASE_URL=https://YOUR_PROJECT.supabase.co
VITE_SUPABASE_ANON_KEY=your-anon-key-here
# 4. Start development server
npm run devThe application will be available at http://localhost:5000
CRITICAL: Edge Functions require additional setup. See EDGE_FUNCTIONS_SETUP.md for complete instructions.
Quick version:
# 1. Set OpenAI API key in Supabase Dashboard → Functions → Secrets
# Name: OPENAI_API_KEY
# Value: sk-your-actual-key-here
# 2. Link your project
supabase login
supabase link --project-ref YOUR_PROJECT_REF
# 3. Deploy functions
supabase functions deploy raphael-chat
supabase functions deploy task-create
supabase functions deploy daily-progress
# 4. Test deployment
USER_JWT='your-jwt-here' ./scripts/smoke-test.shUnified Task System (engram_ai_tasks):
- Single source of truth for all health and personal tasks
- St. Raphael operates through engrams schema
- Full audit trail with execution logs
- Status tracking: pending → in_progress → done/failed
St. Raphael Health Companion:
- ChatGPT-class conversational AI
- Health information and emotional support
- Never diagnoses or prescribes (safety-first design)
- Automatic daily progress tracking
- Emergency escalation patterns
Edge Functions (Production-Grade):
raphael-chat: AI chat with safety guardrailstask-create: Create health/personal tasksdaily-progress: Track user engagement- Structured error responses (code/message/hint)
- JWT forwarding with RLS enforcement
Health Monitoring:
- Medication tracking with adherence rates
- Appointment scheduling and reminders
- Health goal setting and progress
- Emergency contact management
- Health Connectors with OAuth integration (see below)
Health Connectors:
- OAuth-based integration with health data providers
- Aggregators: Terra (multi-device), Human API, Validic, Metriport
- Wearables: Fitbit, Oura Ring, WHOOP, Garmin, Withings, Polar
- Glucose/CGM: Dexcom, Abbott Libre (via aggregators)
- Clinical/EHR: SMART on FHIR (Epic, Oracle Health/Cerner)
- Webhook ingestion with signature verification
- Background sync with idempotent processing
- Normalized metrics storage (steps, heart rate, sleep, glucose, etc.)
- See Health Connectors Setup for configuration
- ✅ Row Level Security (RLS) on all 30+ tables
- ✅ All policies use
(select auth.uid())for performance - ✅ JWT authentication enforced in Edge Functions
- ✅ OpenAI API keys stored in Supabase Secrets (never in code)
- ✅ Function security with
search_pathhardening - ✅ PHI protection (no logging of sensitive health data)
- ✅ CORS headers configured
- ✅ Rate limiting available
See SECURITY.md for complete threat model and mitigations.
- iPhone-optimized (320-430px, safe areas, no horizontal scroll)
- Responsive design for all devices
- Dark theme with accessible contrast
- Loading states and error handling
- Production-ready interface
- Smooth animations and transitions
- Frontend: React 18 + TypeScript + Vite
- Styling: Tailwind CSS
- Icons: Lucide React
- Routing: React Router v6
- Backend: Supabase (PostgreSQL + Auth + Edge Functions)
- State Management: React Hooks + Context API
- Optional: Python FastAPI backend (for advanced ML features)
EverAfter uses a Supabase-First Architecture:
- All authentication via Supabase Auth
- All database operations via Supabase PostgreSQL
- All API endpoints via Supabase Edge Functions (8 serverless functions)
- Python FastAPI backend available but optional (only for advanced ML/NLP)
See ARCHITECTURE.md for detailed system design.
src/
├── components/ # React components
│ ├── CustomEngramsDashboard.tsx
│ ├── DailyQuestionCard.tsx
│ ├── EngramChat.tsx
│ ├── EngramTaskManager.tsx
│ ├── FamilyMembers.tsx
│ ├── ProtectedRoute.tsx
│ ├── RaphaelAgentMode.tsx
│ └── SaintsDashboard.tsx
├── contexts/ # React contexts
│ └── AuthContext.tsx
├── hooks/ # Custom React hooks
│ └── useAuth.tsx
├── lib/ # Third-party integrations
│ ├── supabase.ts
│ └── api-client.ts
├── pages/ # Page components
│ ├── Dashboard.tsx
│ ├── Login.tsx
│ ├── Signup.tsx
│ └── Pricing.tsx
├── App.tsx # Main application component
└── main.tsx # Application entry point
supabase/
├── migrations/ # Database schema migrations (17 files)
└── functions/ # Edge functions (8 serverless functions)
backend/ # Optional Python FastAPI backend
├── app/ # FastAPI application
└── requirements.txt # Python dependencies
The Supabase credentials are already configured in .env:
VITE_SUPABASE_URL=https://rfwghspbhuqdhyyipynt.supabase.co
VITE_SUPABASE_ANON_KEY=eyJhbG...The application uses 17+ Supabase tables including:
Core Tables:
profiles- User informationarchetypal_ais- Custom AI personalitiesdaily_question_pool- 365 questionsdaily_question_responses- User responsesuser_daily_progress- Progress tracking
Saints AI:
saints_subscriptions- Active Saints per usersaint_activities- Activity logs
Family & Social:
family_members- Family access controlfamily_personality_questions- Questions for familyfamily_member_invitations- Invitation system
Advanced Features:
agent_task_queue- Autonomous task systempersonality_dimensions- Multi-layer personality modelvector_embeddings- AI personality vectorssubscriptions- Stripe payment management
All tables have Row Level Security enabled with proper policies.
Pre-configured AI assistants:
- St. Raphael (FREE): Health management, appointments, prescriptions
- St. Michael (Premium): Security & privacy protection
- St. Martin (Premium): Charitable giving & community
- St. Agatha (Premium): Crisis support & resilience
Build your own AI personalities:
- Answer daily questions (365-day journey)
- AI learns your communication style, values, humor
- Activate when readiness reaches 80%
- Chat with your trained AI
- Invite family via email
- Send personality questions
- Collect external memories
- Build family member AI representations
# Development mode with hot reload
npm run dev
# Type checking
npx tsc --noEmit
# Linting
npm run lint
# Production build
npm run build
# Preview production build
npm run previewSee DEPLOYMENT_CHECKLIST.md for detailed deployment instructions.
npm install -g vercel
vercel --prodnpm install -g netlify-cli
netlify deploy --prodThe Health Connectors system allows Raphael to integrate with external health data providers through OAuth and webhooks.
- OAuth Flow: User initiates connection → Edge Function redirects to provider → Callback stores tokens
- Webhook Ingestion: Provider sends data → Signature verified → Metrics normalized → Stored in
health_metrics - Manual Sync: User triggers backfill → Edge Function fetches historical data → Stored with idempotency
provider_accounts: OAuth tokens and connection statushealth_metrics: Normalized health data (steps, heart rate, sleep, glucose, etc.)webhook_events: Webhook audit log with deduplication
- Terra: https://tryterra.co/ - Supports Fitbit, Garmin, Apple Health, Google Fit, Oura, WHOOP, and more
- Human API: https://humanapi.co/ - Wellness + Medical records
- Validic: https://validic.com/ - Broad device catalog with streaming
- Metriport: https://metriport.com/ - Open-source, FHIR-native
- Fitbit: https://dev.fitbit.com/ - Steps, heart rate, sleep
- Oura Ring: https://cloud.ouraring.com/docs/ - Sleep, HRV, readiness
- WHOOP: https://developer.whoop.com/ - Strain, recovery (coming soon)
- Garmin: https://developer.garmin.com/ - Fitness, VO2 max (coming soon)
- Withings: https://developer.withings.com/ - Weight, BP (coming soon)
- Polar: https://www.polar.com/accesslink-api/ - Training load (coming soon)
- Dexcom: https://developer.dexcom.com/ - Real-time glucose via OAuth
- Abbott Libre: Via aggregator partners (no public API)
- SMART on FHIR: https://docs.smarthealthit.org/ - Epic, Oracle Health/Cerner, etc.
- Requires per-institution registration
Add to Supabase Dashboard → Functions → Secrets:
APP_BASE_URL=https://your-app.com
# Terra
TERRA_CLIENT_ID=your_terra_client_id
TERRA_CLIENT_SECRET=your_terra_secret
TERRA_WEBHOOK_SECRET=your_terra_webhook_secret
# Fitbit
FITBIT_CLIENT_ID=your_fitbit_client_id
FITBIT_CLIENT_SECRET=your_fitbit_secret
FITBIT_SUBSCRIBER_VERIFICATION_CODE=your_verification_code
# Oura
OURA_CLIENT_ID=your_oura_client_id
OURA_CLIENT_SECRET=your_oura_secret
# Dexcom
DEXCOM_CLIENT_ID=your_dexcom_client_id
DEXCOM_CLIENT_SECRET=your_dexcom_secretTerra:
- Sign up at https://dashboard.tryterra.co/
- Create new integration
- Set redirect URL:
https://your-app.com/api/connect-callback - Set webhook URL:
https://YOUR_PROJECT.supabase.co/functions/v1/webhook-terra
Fitbit:
- Register app at https://dev.fitbit.com/apps/new
- OAuth 2.0 Application Type: Server
- Redirect URL:
https://your-app.com/api/connect-callback - Webhook subscription URL:
https://YOUR_PROJECT.supabase.co/functions/v1/webhook-fitbit
Oura:
- Request API access at https://cloud.ouraring.com/oauth/applications
- Set redirect URI:
https://your-app.com/api/connect-callback
Dexcom:
- Register at https://developer.dexcom.com/
- Use sandbox for testing: https://sandbox-api.dexcom.com
- Set redirect URI:
https://your-app.com/api/connect-callback
# Deploy OAuth handlers
supabase functions deploy connect-start
supabase functions deploy connect-callback
# Deploy webhook handlers
supabase functions deploy webhook-terra
supabase functions deploy webhook-fitbit
supabase functions deploy webhook-oura
supabase functions deploy webhook-dexcom
# Deploy sync function
supabase functions deploy sync-health-nowFor providers that support webhooks, register the webhook URLs in their developer dashboards:
- Terra:
https://YOUR_PROJECT.supabase.co/functions/v1/webhook-terra - Fitbit:
https://YOUR_PROJECT.supabase.co/functions/v1/webhook-fitbit - Oura:
https://YOUR_PROJECT.supabase.co/functions/v1/webhook-oura - Dexcom:
https://YOUR_PROJECT.supabase.co/functions/v1/webhook-dexcom
- All OAuth tokens encrypted at rest in Supabase
- Webhook signatures verified on every request
- Idempotent processing prevents duplicate data
- Row Level Security enforces user data isolation
- No PHI/credentials logged
- Rate limiting on sync endpoints
- Apple HealthKit: Requires native iOS app companion
- Android Health Connect: Requires native Android app
- Strava: Workout data only; training/AI uses violate ToS
- Abbott Libre: Must use aggregator programs (no public API)
All providers map to standardized metrics:
steps(count)resting_hr(bpm)hrv(ms)sleep_efficiency(%)glucose(mg/dL)tir(% time in range for glucose)vo2_max(ml/kg/min)calories(kcal)
See Edge Function handlers for complete mapping tables.
CRITICAL SAFETY: This system provides informational data only. It does NOT diagnose, prescribe, or provide medical advice. All alerts use conservative clinical thresholds.
The Glucose & Metabolic Health system integrates continuous glucose monitors (CGM), lab results, and contextual events into a unified, normalized data store that powers Raphael's health insights.
- Dexcom G6/G7: OAuth + Webhooks + Poll (Sandbox & Production)
- Libre: Via aggregator partners (Terra, Validic, Metriport)
- Manual Upload: CSV/JSON from Dexcom/Libre exports
- SMART on FHIR: HbA1c (LOINC 4548-4), lipid panels
- Manual Entry: Support for any lab with structured format
- Meals (carb counting)
- Insulin dosing
- Exercise (intensity tracking)
- Illness/notes
glucose_readings: High-frequency CGM data (~5 min intervals)
- Normalized to mg/dL (original unit preserved)
- Sources: dexcom, libre-agg, terra, manual, fhir
- Includes trend (rising/falling) and quality indicators
- Unique constraint: (user_id, engram_id, ts, src)
lab_results: Laboratory test results
- LOINC codes for standardization
- HbA1c, lipids, metabolic panels
- FHIR integration ready
metabolic_events: User-logged context
- meal, insulin, exercise, illness, note
- Carb counting, insulin dosing, free-text notes
glucose_daily_agg: Pre-computed daily statistics
- Time-in-Range (TIR) 70-180 mg/dL
- Hypo/hyper event counts
- Mean, SD, GMI (Glucose Management Indicator)
- Computed by nightly cron job
connector_tokens: Secure OAuth token vault
- Encrypted at rest
- Refresh token support
- Expiration tracking
connector_consent_ledger: Compliance audit trail
- Grant/revoke/refresh events
- Scope tracking
- IP and user agent logging
# Dexcom CGM
DEXCOM_CLIENT_ID=your_dexcom_client_id
DEXCOM_CLIENT_SECRET=your_dexcom_secret
DEXCOM_REDIRECT_URL=https://your-app.com/api/cgm-callback
DEXCOM_ENVIRONMENT=sandbox # or 'production'
DEXCOM_WEBHOOK_SECRET=your_webhook_secret
# Aggregators (choose one to start)
TERRA_API_KEY=your_terra_key
TERRA_WEBHOOK_SECRET=your_terra_webhook_secret
# FHIR (for lab results)
FHIR_CLIENT_ID=your_fhir_client
FHIR_CLIENT_SECRET=your_fhir_secret
FHIR_REDIRECT_URL=https://your-app.com/api/fhir-callback
# General
APP_BASE_URL=https://your-app.comDexcom:
- Apply for Dexcom Developer account: https://developer.dexcom.com/
- Start with Sandbox environment for testing
- Production requires partnership agreement
- Redirect URI:
https://your-app.com/api/cgm-callback - Webhook URL:
https://YOUR_PROJECT.supabase.co/functions/v1/cgm-dexcom-webhook
Terra (for Libre + multi-device):
- Sign up: https://dashboard.tryterra.co/
- Get API key and webhook secret
- Configure webhook:
https://YOUR_PROJECT.supabase.co/functions/v1/cgm-agg-webhook
SMART on FHIR:
- Register with EHR provider (Epic, Cerner/Oracle Health, etc.)
- Request scopes:
patient/Observation.read,launch,offline_access - Redirect URI:
https://your-app.com/api/fhir-callback
# OAuth flows
supabase functions deploy cgm-dexcom-oauth
supabase functions deploy cgm-fhir-oauth
# Webhooks
supabase functions deploy cgm-dexcom-webhook
supabase functions deploy cgm-agg-webhook
# Manual upload
supabase functions deploy cgm-manual-upload
# Daily aggregation (schedule this)
supabase functions deploy glucose-aggregate-cronIn Supabase Dashboard → Database → Cron Jobs:
-- Run daily aggregation at 2 AM UTC
SELECT cron.schedule(
'glucose-daily-aggregation',
'0 2 * * *',
$$
SELECT net.http_post(
url := 'https://YOUR_PROJECT.supabase.co/functions/v1/glucose-aggregate-cron',
headers := '{"Content-Type": "application/json", "Authorization": "Bearer YOUR_SERVICE_ROLE_KEY"}'::jsonb
);
$$
);Urgent Low: <55 mg/dL → Immediate notification (bypasses quiet hours)
Low: <70 mg/dL sustained 20+ min → Notify user
High: >180 mg/dL sustained 60+ min → Notify user
Weekly TIR: <70% over 7 days → Insight + non-diagnostic suggestion
Connection Alerts:
- Webhook silence >6 hours
- Token expiration within 24 hours
- Signature verification failures
- OAuth Connection: User authorizes → Tokens stored in vault → Initial backfill queued
- Webhook Ingestion: Provider sends data → Signature verified → Normalized to mg/dL → Upserted into
glucose_readings - Daily Aggregation: Cron job computes TIR, mean, SD, GMI → Stores in
glucose_daily_agg - Alert Engine: Evaluates thresholds → Sends notifications via existing system
- Agent Access: Raphael queries via RLS-protected functions for context-aware responses
Primary Storage: mg/dL
Conversion: mmol/L × 18.0182 = mg/dL
Preservation: Original unit stored in unit field; raw payload in raw jsonb
- Encryption: OAuth tokens encrypted at rest in Supabase
- Signatures: All webhooks verify HMAC signatures
- Idempotency: Unique constraints prevent duplicate ingestion
- RLS: Users can only access their own data
- Audit: All consent actions logged with timestamp, IP, user agent
- PHI Protection: Device serials redacted from logs
- Export/Delete: User-initiated data export and deletion flows
Dexcom CSV (from Clarity export):
Timestamp,Glucose Value (mg/dL),Unit
2024-10-25 08:00:00,120,mg/dL
2024-10-25 08:05:00,125,mg/dLJSON Format:
{
"readings": [
{
"ts": "2024-10-25T08:00:00Z",
"value": 120,
"unit": "mg/dL"
}
],
"events": [
{
"ts": "2024-10-25T07:30:00Z",
"type": "meal",
"carbs_g": 45,
"text": "Breakfast - oatmeal"
}
]
}Raphael can access these functions (server-side only):
get_glucose_window({ start, end }): Fetch readings with statsget_last_hypo_event({ window }): Find recent hypoglycemic eventscompute_tir({ window }): Calculate time-in-rangeadd_meal_event({ ts, carbs_g, text }): Log mealsadd_insulin_event({ ts, insulin_units, text }): Log insulinset_glucose_alerts({ low, high, durationMin, quietHours }): Configure alerts
All functions respect RLS and validate ownership.
- TIR (Time-in-Range): % readings 70-180 mg/dL
- GMI (Glucose Management Indicator): Estimated HbA1c from mean glucose
- Formula: GMI = 3.31 + (0.02392 × mean_glucose)
- CV (Coefficient of Variation): SD / mean × 100
- Hypoglycemia: <70 mg/dL and <54 mg/dL bands
- Hyperglycemia: >180 mg/dL and >250 mg/dL bands
Smoke Test (scripts/smoke-glucose.sh):
#!/bin/bash
# Upload fixture CSV
curl -X POST \
-H "Authorization: Bearer $USER_JWT" \
-F "file=@fixtures/dexcom-sample.csv" \
$SUPABASE_URL/functions/v1/cgm-manual-upload
# Trigger aggregation
curl -X POST \
-H "Authorization: Bearer $SERVICE_ROLE_KEY" \
$SUPABASE_URL/functions/v1/glucose-aggregate-cron
# Verify data
psql $DATABASE_URL -c "SELECT COUNT(*) FROM glucose_readings;"
psql $DATABASE_URL -c "SELECT * FROM glucose_daily_agg ORDER BY day DESC LIMIT 5;"- Dexcom Production: Requires partnership agreement; use Sandbox for development
- Libre Direct: No public API; use aggregator partnerships (Terra, Validic)
- Rate Limits: Backfill operations respect provider rate limits with exponential backoff
- Data Retention: Follow provider ToS for data retention periods
- Dexcom API Docs: https://developer.dexcom.com/
- Terra Docs: https://docs.tryterra.co/
- SMART on FHIR: https://docs.smarthealthit.org/
- Clinical Guidelines: ADA Standards of Care (https://diabetesjournals.org/care/issue/47/Supplement_1)
- Setup Guide: SETUP.md
- Deployment: DEPLOYMENT_CHECKLIST.md
- Stripe Integration: STRIPE_SETUP.md
- Row Level Security (RLS) on all database tables
- Secure authentication via Supabase Auth
- Protected routes with auth guards
- Environment variables for sensitive data
- Automatic user initialization triggers
Code Quality:
- Removed all TypeScript linting errors
- Fixed React Hook dependencies
- Removed unused imports and variables
- Proper type definitions throughout
Authentication:
- Added ProtectedRoute component
- Auto-redirect for authenticated users
- Proper loading states
- Session management
Database:
- Verified all 17+ tables exist
- Confirmed RLS policies active
- Auto user initialization working
- Complete schema migrations
Build:
- Production build: 390KB JS (gzipped: 107KB)
- Optimized CSS: 28KB (gzipped: 5.6KB)
- Zero TypeScript errors
- Clean, maintainable code
All rights reserved.
Built with care for preserving memories and honoring legacies.