Skip to main content

Individual User Story

End-to-end journey for the Individual role (health consumer) in Syntropy Health. Covers onboarding through every sidebar feature, ambient AI, and external integrations (Slack, MCP, API).

1. Onboarding Flow

1.1 Discovery

StepWhat HappensRouteAuth
Visit landing pagePublic page with ShrineAI chat widget/None
Explore public pagesAbout, Connect, Startup, Partnership, Dietary Science, Privacy, Terms, Slides/about, /connect, etc.None
Browse product catalogPublic protocol/product listing/productsNone
View protocol detailProtocol info with “Adopt” CTA (prompts sign-in)/lounge/protocol/[id]None

1.2 Sign-Up & First Login

StepWhat HappensRouteImplementation
Click Sign InClerk-hosted sign-in component (email + Google SSO)/sign-inauth_page_wrapper
SSO callbackOAuth redirect processing/sign-in/sso-callbackSSOAuthState.handle_sso_callback
Auth syncClerk identity synced to auth state (no local User model)AuthState.sync_auth_state
Referral trackingref cookie → Clerk private_metadata.referral (new users only)AuthState.handle_referral_cookie
Onboarding checkIf user.onboarding_completed == False, show onboarding wizardAuthState.check_onboarding
Role redirectIndividual → /shrine/dashboardPageAuthState.redirect_by_role
Dashboard loadsHealthDM tabbed dashboard with stats, check-ins, protocols/shrine/dashboardCheckinState.on_load
Auth guard chain (every protected page):
clerk.on_load() → AuthState.sync_auth_state → PageAuthState.ensure_authenticated → [page on_load]

1.3 Demo Onboarding (First-Time Wizard)

New users who haven’t completed onboarding are presented a 3-step wizard modal:
StepWhat HappensImplementation
1. WelcomeRole confirmation (individual vs partner) + platform overviewModal step 1
2. Demo data opt-in”Try with demo data?” toggle — if yes, inject seed data into state vars (NOT into DB)AuthState.is_demo_mode = True
3. Feature tourHighlight sidebar items: HealthDM, Lounge, Chat widgetGuided tour overlay
CompleteSet user.onboarding_completed = True in DB + Clerk metadataAuthState.complete_onboarding()
Demo mode behavior:
  • State vars load from data/seed/ constants instead of DB
  • Clear visual indicator: “Demo Mode” badge in navbar
  • Real user data is never mixed with demo data
  • Exit demo: Clear demo state vars → user sees their real (empty) data
  • Re-enter demo: /shrine/help page has “Start onboarding tour” button

2. Sidebar Navigation

The sidebar has two switchable sections: The Shrine (personal health) and The Lounge (protocol adherence & feedback).

The Shrine Section

Sidebar LinkRouteWhat It Does
HealthDM/shrine/dashboardMain dashboard: stats, check-ins, protocols, food/supplement tracking
Message Center/shrine/notificationsHealth insights, DIET alerts, protocol reminders (with unread badge)
Health Profile/shrine/profileDietary prefs, supplements, goals, conditions, allergies, completeness %
Settings/shrine/settingsOrder integrations, notifications, data sharing, API tokens, subscription
Help/shrine/helpPlatform help, re-trigger onboarding tour, demo mode toggle

The Lounge Section

Sidebar LinkRouteWhat It Does
My Lounge/loungeSubscribed protocols grid, protocol selector, adherence timeline, notes feed
Catalog/lounge/catalogBrowse marketplace, subscribe/unsubscribe, compatibility scoring

Ambient ShrineChat Widget

ShrineAI is not a sidebar link — it’s a floating chat widget available on every authenticated page.
ElementBehavior
TriggerTeal floating button, bottom-right corner
CollapsedIcon only, subtle pulse when AI has a suggestion
ExpandedSlide-up chat panel with message input, voice button, streaming responses
MinimizedLast message preview bar (click to expand)
PersistenceSingle session — messages persist across page navigation via Reflex state
ContextInjected: last 3 message pairs from DB, current page context
Chat modes: LANDING (anonymous, on public pages), SHRINE (full auth, on protected pages) LLM fallback chain: OpenRouter free models → Cerebras Llama 3.3

Additional Protected Pages (not in sidebar)

RoutePage TitleAccess
/lounge/protocolsMy Protocols”View All” link from dashboard protocols section
/shrine/subscriptionSubscriptionPlan selection + Stripe checkout

Backward Compatibility Redirects

Old RouteNew RouteStatus
/shrine-checkin/shrine/dashboard301
/longevitian/shrine/dashboard301
/longevitian/shrine-chatremoved (chat widget)301 → /shrine/dashboard
/notifications/shrine/notifications301
/profile/shrine/profile301
/settings/shrine/settings301
/catalog/lounge/catalog301
/my-protocols/lounge/protocols301
/lounge/loungeunchanged

3. Feature Walkthrough

3.1 HealthDM Dashboard (/shrine/dashboard)

Tabbed interface:
TabContentStatus
Overview5 stat cards (total, this week, voice, text, phone) + check-in list + My ProtocolsBuilt
Food TrackerFood consumption trackingPlaceholder (“Coming soon”)
MedicationsMedication trackingPlaceholder (“Coming soon”)
ConditionsHealth conditionsPlaceholder (“Coming soon”)
SymptomsSymptom trackingPlaceholder (“Coming soon”)
Check-in flow:
  1. Click “New Check-in” → modal with topic pills + textarea
  2. Select input type (Text or Voice)
  3. Toggle health domains (medication, diet, symptoms…)
  4. Submit (min 3 chars) → create pending record
  5. AI processing: LLM extracts medications, foods, symptoms
  6. Health entries saved to DB (MedicationEntry, FoodLogEntry, SymptomEntry)
  7. View in this-week / past sections with pagination (5/page)
  8. Filter by status: All / Pending / Processed / Flagged
  9. Click to view details, edit, or delete
Phone check-in sync (CDC pipeline):
  • Background loop (30s interval) fetches Bland.ai call transcripts
  • Auto-ingests as phone check-ins with LLM processing
  • “Sync Now” button for manual refresh

3.2 Ambient ShrineChat Widget (All Pages)

  • Single-session chat with LangGraph agent (no multi-session management)
  • Floating panel, bottom-right — expands on click, minimizes to icon
  • Streaming token-by-token rendering
  • Voice input via browser audio recording → transcription
  • Context injection: last 3 message pairs from DB + current page context
  • Tool usage indicator during agent operations
  • Available on every authenticated page via build_layout() injection

3.3 Protocol Marketplace & Subscriptions

The Lounge catalog (/lounge/catalog) is a marketplace where users discover health protocols matched to their profile. Protocols are sourced from the Shopify Protocols seller app and enriched with compatibility scoring. Discovery flow:
StepWhat HappensRouteImplementation
Browse catalogGrid of protocol cards with compatibility scores, goal tags, and category badges/lounge/catalogCatalogState.initialize_catalog
View scoringEach card shows 0-100 compatibility score (emerald/amber/slate/red tiers)_enrich_protocol_with_scoring()
SubscribeClick “Subscribe” button on any catalog cardCatalogState.toggle_subscription
View subscriptions”My Subscriptions” section appears at top of Lounge dashboard/loungeLoungeState.user_subscriptions
UnsubscribeClick “Unsubscribe” on subscription card in Lounge dashboardLoungeState.unsubscribe_protocol
Marketplace scoring fields (from Shopify metafields):
FieldDescription
compatibility_score0-100 weighted composite (goal alignment 40%, gap filling 30%, community 10%, protocol quality 20%)
confidence_tierHIGH / MEDIUM / LOW / INSUFFICIENT based on profile completeness + community data
functional_goalsGoal tags: cognitive, sleep, gut_health, etc.
evidence_levelclinical, peer_reviewed, anecdotal, etc.
category_badgeNutraceutical category with color-coded badge
Subscription card (Lounge dashboard): Each subscribed protocol shows:
  • Adherence score circle (0-100 PDC with emerald/amber/rose tiers)
  • Current streak in days
  • Days active since subscription
  • Category badge + protocol image
  • Dosage, frequency, timing details
  • Unsubscribe action

3.4 Protocol Adoption & Adherence

  1. Browse /lounge/catalog → view protocol detail → click “Adopt”
  2. Set reminder time (HH:MM), toggle data sharing with partner
  3. Daily check-in modal: taken/skipped + optional note
  4. Dashboard “My Protocols” section shows progress, streak, adherence %
  5. /lounge/protocols for full list; /lounge for timeline view
  6. Pause/resume protocols, missed detection runs automatically

3.5 Health Profile (/shrine/profile)

7 sections: username, display name, bio, dietary preferences (toggle-based), supplement stack, health goals, conditions, allergies. Auto-calculated completeness %.

3.6 Settings (/shrine/settings)

6 collapsible sections:
  1. Order Integrations — 8 partners, all “Coming soon”
  2. Dietary Preference — toggle-based dietary selections
  3. Notifications — frequency + aggressiveness sliders
  4. Data Sharing & Privacy — per-protocol opt-in for partner visibility
  5. Payment & Subscription — Stripe checkout, plan management
  6. Admin Tokens — create named tokens, view active tokens, revoke, copy (see §3.8)

3.7 Notifications (/shrine/notifications)

4 types with 3-tier priority routing:
TypeColorPriorityDelivery
ALERTRedHigh (DIET severity)Immediate push + in-app + sound
SUGGESTIONAmberMediumIn-app + daily digest push
TIPSBlueLowIn-app only
PROTOCOL_REMINDERTealMediumIn-app + push at scheduled time
Collapsible sections, 10/page, mark as read, dismiss. Notification delivery channels:
  • In-app: Real-time via Reflex state (existing)
  • Web push: Service Worker + VAPID keys (requires browser permission)
  • Queue: Notifications flow through async queue (asyncio.Queue → NATS at scale)

3.8 Slack Integration (External)

CommandAuthWhat It Does
/syntropy-foodnewsNoneDuckDuckGo top 5 food safety news (ephemeral)
/shrine-checkin TOKEN:<token> textAdmin tokenCreates health check-in via process_with_llm()
/shrine-rate-diet TOKEN:<token>Admin token30-day diet fulfillment score
DM / @mention botNoneShrineAI LANDING mode conversation
Token format: TOKEN:<token> — admin token generated via Settings UI. Legacy sh_* keys still accepted (deprecated, compat layer logs warning).

3.9 Admin Token Management

Users manage admin tokens from /shrine/settings → Admin Tokens section:
ActionWhat Happens
Create tokenName + expiration (30/90/365 days or never) → generates token, shown once
List tokensTable: name, created date, expiration, status
Revoke tokenDeactivate immediately, non-reversible
Copy tokenOne-click copy to clipboard (only on initial creation)
Admin tokens are internal, full-access tokens for authenticating the user’s own integrations. They are not scoped — any valid token grants full access to the user’s data. Dual token system:
  • Clerk-issued tokens (new) — split-token SHA-256 pattern via reflex-clerk-api, with expiration support
  • Legacy sh_* keys (deprecated) — still accepted via validate_token_compat middleware with deprecation warning
Tokens authenticate access to:
  • REST API (/api/ext/*) — health data CRUD, check-in submission, protocol queries
  • MCP Server — same capabilities via Model Context Protocol for AI tool integration
  • Slack botTOKEN:<token> prefix in slash commands

3.10 MCP Integration (Developer)

MCP-compatible AI tools (Claude Desktop, etc.) can connect to Syntropy Health using an admin token:
MCP ToolMaps To
get_profileUser health profile
create_checkinLog a health check-in
list_protocolsAdopted protocols
get_adherenceProtocol adherence stats
search_catalogBrowse protocol catalog
get_notificationsRecent notifications
See docs/integrations/mcp.md for setup instructions.

4. Demo Run (Individual)

Prerequisites

make setup              # Install deps + start PostgreSQL + run migrations
make run seed           # Seed demo data (creates user + API key)

Start the Server

make run dev            # Start with real Clerk auth
# Or: make run dev-mock  (mocked LLM + transcription, no API keys needed — auth is still real Clerk)

Individual Demo Walkthrough

  1. Open http://localhost:3000/sign-in
  2. Sign in with your Clerk dev account (the email in ADMIN_USER_EMAILS in envs/base)
  3. Auth syncs to local DB → onboarding wizard appears (first time)
  4. Complete wizard: confirm role → enable demo data → tour highlights
  5. Redirects to /shrine/dashboard with demo data populated
  6. Explore The Shrine sidebar:
    • HealthDM — view demo check-ins, stats, browse tabs
    • Message Center — view demo DIET alerts and protocol reminders
    • Health Profile — see pre-filled dietary prefs, supplements, goals
    • Settings — notification preferences, data sharing, API tokens
    • Help — re-trigger onboarding, toggle demo mode
  7. Switch to The Lounge section in sidebar dropdown:
    • My Lounge — view demo protocol timeline + adherence
    • Catalog — browse and adopt a protocol
  8. Click the ShrineChat widget (bottom-right) to chat with AI assistant
  9. Exit demo mode from Help page or navbar badge → see real (empty) data

Slack Demo

After make run dev with ngrok:
# Food news (no auth needed)
/syntropy-foodnews

# Health check-in (requires admin token from Settings)
/shrine-checkin TOKEN:<your_token> feeling great after a green smoothie

# Diet score (requires admin token)
/shrine-rate-diet TOKEN:<your_token>
Create an admin token from /shrine/settings → Admin Tokens section.

5. Page Wrapper Reference

WrapperAuthNavbarSidebarChat WidgetUsed By
app_page_wrapperYesYesYesYesDashboard, catalog, settings, profile, notifications, lounge, protocols, subscription, help
auth_page_wrapperNoYesNoNoSign-in, SSO callback
standalone_page_wrapperNoYesNoNoLanding, about, products, protocol detail
partner_page_wrapperYes (partner)YesYesYesPartner portal, onboarding
Note: chat_page_wrapper is removed — ShrineChat is now a floating widget injected by build_layout() in all authenticated wrappers.

6. State Dependencies


7. Route Map Summary