Instruction file imported from shivanandham/pregnancy-assistant (
.cursor/rules/project_overview.mdc). Copyright stays with the author.
Luma Pregnancy Assistant - Project Overview
Project Vision
Luma is a comprehensive pregnancy tracking and AI assistant app designed to support expecting mothers throughout their pregnancy journey. The app combines traditional pregnancy tracking features with modern AI-powered assistance, providing personalized guidance, health monitoring, and educational content.
Architecture Overview
- Frontend: Flutter (Dart) cross-platform mobile app with Provider state management
- Backend: Node.js/Express REST API with Prisma ORM for database operations
- Database: PostgreSQL (self-hosted for production, local for development)
- AI Integration: Google Gemini 2.5 Flash for intelligent pregnancy assistance
- Authentication: Custom session token system with Firebase Auth for identity verification
- Deployment: Self-hosted on DigitalOcean with PM2 process management
- State Management: Provider pattern with 7 main providers (including AuthProvider)
- UI Framework: Material Design 3 with pregnancy-themed color palette
Core Features & Capabilities
1. Pregnancy Tracking System
- Week-by-week progress tracking with visual indicators and trimester identification
- Due date countdown with customizable cycle length support (22-44 days)
- Progress percentage calculation based on current week vs. 40-week pregnancy
- Timeline visualization with milestone tracking and important events
- Trimester-based color coding and visual feedback
2. AI-Powered Chatbot Assistant
- Context-aware responses based on current pregnancy week and user profile
- Pregnancy-specific knowledge base with medical disclaimers
- Diagnostic questioning system for symptom assessment and follow-up
- Chat session management with conversation history and searchability
- Knowledge extraction from conversations for future reference and learning
- Medical safety guidelines integrated into all AI responses
3. Comprehensive Health Tracking
- Symptom logging with severity levels (1-5), custom types, and notes
- Weight tracking with visual charts and trend analysis
- Appointment management with scheduling, reminders, and completion tracking
- Daily checklist system with auto-generated tasks based on pregnancy week
- Photo journal capability for weekly bump photos (planned feature)
4. User Profile & Personalization
- Personal information management (height, weight, age, medical history)
- Medical context integration (allergies, medications, lifestyle factors)
- Timezone support for accurate time tracking and reminders
- Preference storage for customized recommendations
- Medical history tracking for context-aware AI responses
- User authentication with Firebase Auth and Google Sign-In
- Secure logout functionality with confirmation dialogs
5. Knowledge Management System
- Pregnancy tips database categorized by week, trimester, and topic (cached per week)
- Milestone tracking with important events and developmental stages
- Weekly content generation for weeks without milestones (highlights, facts, things to do)
- Automatic fact extraction from AI conversations using Gemini
- Conversation chunking for search and retrieval capabilities
- Knowledge categorization (symptom, milestone, preference, medical, activity)
6. Content Generation & Caching System
- AI-Generated Tips: Personalized pregnancy tips per week using Gemini (cached for 7 days)
- AI-Generated Checklists: Daily personalized checklists based on pregnancy week and user profile (cached per day until midnight)
- AI-Generated Weekly Content: Week-specific highlights, facts, and actionable items when no milestones exist (cached per user per week)
- Caching Strategy: All AI-generated content is cached to reduce API calls and costs
- Expiration Logic: Tips (7 days), Checklists (end of day), Weekly Content (7 days or end of week)
Technical Architecture Details
Database Schema (Prisma)
- User: Firebase user integration with authentication data
- Session: Custom session token management (JWT tokens, refresh tokens, expiration, revocation)
- UserProfile: Demographics, medical history, preferences, timezone
- PregnancyData: Due date, LMP, cycle length, pregnancy timeline
- ChatSession/ChatMessage: AI conversation management with diagnostic support
- Symptom: Tracking entries with severity, type, and custom categories
- Appointment: Medical visits with scheduling and completion tracking
- WeightEntry: Weight tracking with timestamps and notes
- KnowledgeFact: Extracted knowledge from conversations with categorization
- ConversationChunk: Searchable conversation segments with keywords
- PregnancyTip: Weekly tips and advice with expiration dates (cached per week for 7 days)
- DailyChecklistItem: User-specific daily checklist items generated with AI (cached per day until midnight)
- WeeklyContent: Week-specific content with highlights, facts, and actionable items (cached per user per week for 7 days)
- ChecklistCompletion: Daily task completion tracking
API Architecture
- RESTful endpoints with consistent response patterns
- Express.js middleware for security, validation, and logging
- Prisma ORM for type-safe database operations
- Joi validation for input sanitization and error handling
- Rate limiting with different limits for chat vs. general API
- CORS configuration with environment-specific origins
- Custom Session Token Middleware: Validates JWT session tokens (not Firebase tokens)
- Session Service: Token generation, verification, refresh, and revocation
- Auth Endpoints:
/api/auth/login,/api/auth/refresh,/api/auth/logout,/api/auth/logout-all - User-specific data isolation with authentication context
AI Integration Architecture
- Google Gemini 2.5 Flash for natural language processing
- Context-aware prompting with pregnancy-specific guidelines
- Medical disclaimer integration in all AI responses
- Diagnostic questioning system for symptom assessment
- Knowledge extraction pipeline for conversation analysis
- Symptom detection from natural language input
- Content Generation: Tips, checklists, and weekly content generated with Gemini and cached appropriately
- Caching Layer: All AI-generated content cached in database to reduce API calls and ensure consistency
Development Guidelines & Standards
Code Organization
- Backend: TypeScript/JavaScript with Express.js and Prisma
- Frontend: Dart with Flutter and Provider state management
- Database: PostgreSQL with Prisma schema and migrations
- API: RESTful design with consistent error handling
- State Management: Provider pattern with separation of concerns
Database Migration Rules ⚠️ CRITICAL
ALL schema changes MUST go through Prisma migrations. Direct database modifications are STRICTLY PROHIBITED.
Workflow - Development (Local Laptop):
- Modify
prisma/schema.prisma - Generate and apply migration:
npx prisma migrate dev --name <descriptive-name>- This generates the migration file and applies it to your local database
- Carefully review generated migration SQL file
- Commit both
schema.prismaand migration files together
Workflow - Production (Droplet):
- Pull latest code with migrations
- Create database backup before applying
- Apply existing migrations:
npx prisma migrate deploy- This applies all pending migrations to the production database on droplet
- Verify migration status:
npx prisma migrate status
Rules:
- ✅ DO: Use migrations for ALL schema changes
- ✅ DO: Use descriptive migration names
- ✅ DO: Review generated migration SQL carefully before committing
- ✅ DO: Create database backups before major schema changes
- ✅ DO: Commit both
schema.prismaand migration files together - ❌ DON'T: Modify database directly via SQL
- ❌ DON'T: Edit migration files after committing
- ❌ DON'T: Skip or revert migrations
- ❌ DON'T: Use
prisma db push(always use migrations) - ❌ DON'T: Drop or recreate the database (data loss risk)
See backend/prisma/MIGRATION_RULES.md and .cursorrules for complete migration guidelines.
Pregnancy Calculation Standards
- Due date calculation: LMP + 280 days (adjustable for cycle length variations)
- Current week calculation: Days since LMP ÷ 7 (rounded down)
- Trimester determination: 1st (weeks 1-12), 2nd (weeks 13-26), 3rd (weeks 27-40+)
- Progress percentage: Current week ÷ 40 weeks
- Cycle length support: 22-44 days with automatic due date adjustment
AI Context Building
- Pregnancy week context for relevant advice and recommendations
- User profile integration for personalized responses
- Medical history consideration for safety and appropriateness
- Time-aware responses with current date/time and user timezone
- Conversation history for context continuity
- Knowledge base integration for consistent information
Security & Privacy Framework
Data Protection
- Custom Session Token System: Separates Firebase identity from session management
- Firebase Authentication: Used only for initial identity verification during login
- Session Tokens: JWT-based custom session tokens for API authentication (30-day expiration)
- Refresh Tokens: Long-lived tokens (90-day expiration) for obtaining new session tokens
- Immediate Revocation: Session revocation via database check on each request
- One Session Per User: New login automatically revokes all existing sessions
- Token Rotation: New refresh tokens issued on each refresh for enhanced security
- Session Cleanup: Automated cron job removes expired and revoked sessions
- JWT token validation for all API endpoints using session tokens
- User-specific data isolation with authentication context
- Backend-only API key access for AI services
- Input validation with comprehensive sanitization
- Rate limiting to prevent abuse and ensure service availability
Medical Safety
- Medical disclaimers in all AI responses
- Healthcare provider consultation reminders for medical concerns
- Evidence-based information with source attribution
- Symptom severity assessment with appropriate escalation guidance
- Emergency situation recognition with immediate medical advice
Privacy Considerations
- Multi-user support with secure user data isolation
- Firebase Auth integration for identity verification only
- Session token management with local storage and automatic expiration
- Device info tracking for security auditing (optional)
- User-specific data storage with proper access controls
- No personal data sharing with third parties
- Medical information protection with appropriate handling
- Conversation privacy with user-specific storage
Environment & Configuration
Development Environment
- Local development: http://192.168.0.8:3000 (local network access)
- Database: Local PostgreSQL with Prisma migrations
- AI: Google Gemini API with development key
- Authentication: Firebase Auth with development configuration
- Session Tokens: JWT_SECRET, JWT_EXPIRES_IN, JWT_REFRESH_EXPIRES_IN environment variables
- Hot reload: Nodemon for backend, Flutter hot reload for frontend
Production Environment
- Backend hosting: Self-hosted on DigitalOcean with PM2 process management
- Database: Self-hosted PostgreSQL on DigitalOcean
- API endpoint: Custom domain with SSL certificate
- AI: Google Gemini API with production key
- Authentication: Firebase Auth with production configuration
- Session Tokens: Production JWT_SECRET, JWT_EXPIRES_IN, JWT_REFRESH_EXPIRES_IN configuration
- Monitoring: PM2 process monitoring and health checks
- Session Cleanup: Automated daily cron job for expired session cleanup
Common Development Commands
- Backend:
npm run dev(development),npm run deploy:db(database deployment) - Flutter:
flutter pub get,flutter run,flutter build apk - Database:
npm run db:studio(Prisma Studio),npm run test:db(connection test) - Migrations:
npx prisma migrate dev --name <name>(create and apply),npx prisma migrate deploy(apply existing),npx prisma migrate status(check)
Business Logic & User Experience
Pregnancy Journey Support
- Onboarding flow for initial pregnancy data setup
- Progressive disclosure of features based on pregnancy stage
- Personalized content based on current week and user profile
- Milestone celebrations for important pregnancy events
- Preparation guidance for upcoming stages and events
Health Monitoring Integration
- Symptom pattern recognition for trend analysis
- Weight tracking with healthy range guidance
- Appointment coordination with reminder systems
- Medication tracking and vitamin reminders (planned)
- Exercise recommendations with pregnancy-safe activities (planned)
AI Assistant Capabilities
- Natural language understanding for pregnancy-related queries
- Contextual responses based on current pregnancy stage
- Diagnostic questioning for symptom assessment
- Educational content delivery with appropriate disclaimers
- Emotional support with encouraging and supportive language
Performance & Scalability Considerations
Frontend Optimization
- Provider-based state management for efficient widget rebuilding
- Lazy loading for large datasets and images
- Caching strategies for frequently accessed data
- Offline capability with local storage and sync
- Memory management for long-running app sessions
- Session Token Management: Custom session tokens stored in SharedPreferences
- AuthenticatedHttpClient: Automatic token injection and 401 error handling
- Reactive Token Refresh: Token refresh on expiration or 401 errors (not proactive)
- Authentication state management with automatic token refresh and logout on revocation
- HomeProvider Loading States: Separate loading states for tips, milestones, and checklist with proper error handling
- Empty State Handling: Properly handle empty states (no pregnancy data, no milestones) by setting loading=false
- Error handling with user-friendly messages and retry mechanisms
- Weekly Content Display: Home screen "This Week" section displays milestones when available, or AI-generated weekly content when no milestones exist
Backend Performance
- Database indexing on frequently queried fields
- API response caching for static content
- Rate limiting to prevent abuse and ensure availability
- Error handling with graceful degradation
- Monitoring with health checks and performance metrics
- User-specific data queries with authentication context
- PM2 process management for production stability
AI Service Optimization
- Context optimization for efficient prompt engineering
- Response caching for common queries
- Content Caching: Tips (7 days), Checklists (daily), Weekly Content (per week) - reduces API calls significantly
- Error handling with fallback responses
- Rate limiting for AI API calls
- Cost optimization with efficient token usage and aggressive caching
- Generation Strategy: Check cache before generating, only generate when content is missing or expired
When working on this project, always prioritize user safety, medical accuracy, and pregnancy-specific considerations. Maintain appropriate medical disclaimers and encourage professional healthcare consultation for medical concerns.