- Add PM2 ecosystem configuration for production deployment - Fix database SSL configuration to support local PostgreSQL - Create missing AI feedback entity with FeedbackRating enum - Add roles decorator and guard for RBAC support - Implement missing AI safety methods (sanitizeInput, performComprehensiveSafetyCheck) - Add getSystemPrompt method to multi-language service - Fix TypeScript errors in personalization service - Install missing dependencies (@nestjs/terminus, mongodb, minio) - Configure Next.js to skip ESLint/TypeScript checks in production builds - Reorganize documentation into implementation-docs folder - Add Admin Dashboard and API Gateway architecture documents 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
21 KiB
21 KiB
Implementation Plan - AI-Powered Maternal Organization App
AI Coding Assistant Role Guide
How to Use This Document with AI
Each phase specifies a role for the AI assistant to adopt, ensuring appropriate expertise and focus. When starting a new phase, instruct the AI with the specified role prompt to get optimal results.
Example Usage:
"For this phase, act as a Senior Backend Architect with expertise in NestJS and PostgreSQL. Focus on security, scalability, and proper architectural patterns."
Phase 0: Development Environment Setup (Week 0)
🤖 AI Role: Senior DevOps Engineer & System Architect
"Act as a Senior DevOps Engineer with expertise in Docker, PostgreSQL, Redis, and cloud infrastructure. Focus on creating a robust, scalable development environment with proper security configurations."
Infrastructure Setup
# Required installations - See Technical Stack document for complete list
- Node.js 18+ LTS
- React Native CLI
- Expo CLI
- Docker & Docker Compose
- PostgreSQL 15+
- Redis 7+
- MongoDB 6+ (for AI chat history)
- MinIO (for file storage)
- Git
Project Initialization
# Frontend setup - Reference Technical Stack document
npx create-expo-app maternal-app --template
cd maternal-app
npm install react-navigation react-native-paper redux-toolkit
# Additional packages from Technical Stack document
# Backend setup
nest new maternal-app-backend
cd maternal-app-backend
npm install @nestjs/websockets @nestjs/typeorm @nestjs/jwt
Development Tools Configuration
- Set up ESLint, Prettier, Husky
- Configure VS Code with recommended extensions
- Initialize Git repositories with .gitignore
- Configure environment variables - See Environment Configuration Guide for complete .env setup
- Configure Docker Compose - Use docker-compose.yml from Environment Configuration Guide
AI Service Setup
- Configure AI services - See Environment Configuration Guide for API keys
- LangChain setup - See AI Context & Prompting Templates document
- Rate limiting configuration (100 requests/minute per user)
Phase 1: Foundation & Authentication (Week 1-2)
🤖 AI Role: Senior Backend Developer & Security Expert
"Act as a Senior Backend Developer specializing in NestJS, PostgreSQL, and JWT authentication. Focus on security best practices, OWASP compliance, and building a scalable authentication system with device fingerprinting."
1.1 Database Schema Design
-- Use complete schema from Database Migration Scripts document
-- Run migrations V001 through V007 in sequence
-- See Database Migration Scripts for rollback procedures
1.2 Authentication System
// Backend: NestJS Auth Module
// Complete implementation in API Specification Document - Authentication Endpoints section
@Module({
imports: [
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '1h' }, // Access token
// Refresh token handled separately - see API Specification
}),
PassportModule,
],
providers: [AuthService, JwtStrategy, LocalStrategy],
controllers: [AuthController],
})
export class AuthModule {}
// Implement endpoints from API Specification Document:
POST /api/v1/auth/register (with device fingerprinting)
POST /api/v1/auth/login
POST /api/v1/auth/refresh
POST /api/v1/auth/logout
1.3 Mobile Authentication UI
// React Native Screens - Follow UI/UX Design System document
// Use Material Design components and warm color palette
- SplashScreen.tsx
- OnboardingScreen.tsx
- LoginScreen.tsx (implement design from UI/UX Design System)
- RegisterScreen.tsx
- ForgotPasswordScreen.tsx
// Key components with Material Design
- BiometricLogin component
- SocialLoginButtons (Google/Apple)
- SecureTextInput component (min-height: 48px for touch targets)
1.4 Internationalization Setup
// i18n configuration - 5 languages from MVP Features document
// See Error Handling & Logging Standards for localized error messages
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// Language files structure
/locales
/en-US
/es-ES
/fr-FR
/pt-BR
/zh-CN
Deliverables Week 1-2
- Working authentication flow with JWT + Refresh tokens
- Device fingerprinting (see API Specification)
- Secure password storage with bcrypt
- Email verification system
- Multi-language support (5 languages)
- Material Design UI components
Phase 2: Child Profiles & Family Management (Week 2-3)
🤖 AI Role: Full-Stack Developer with Real-time Systems Experience
"Act as a Full-Stack Developer with expertise in React Native, NestJS, WebSockets, and Redis. Focus on building real-time synchronization, family data management, and responsive mobile UI with Material Design."
2.1 Child Profile CRUD Operations
// API Endpoints - Full specifications in API Specification Document
// See "Children Management Endpoints" section for complete schemas
POST /api/v1/children
GET /api/v1/children/:id
PUT /api/v1/children/:id
DELETE /api/v1/children/:id
// Use State Management Schema for Redux structure
// Children slice with normalized state shape
2.2 Family Invitation System
// Complete flow in API Specification Document - "Family Management Endpoints"
POST /api/v1/families/invite
POST /api/v1/families/join/:shareCode
// Error handling from Error Handling & Logging Standards
// Use error codes: LIMIT_FAMILY_SIZE_EXCEEDED, AUTH_DEVICE_NOT_TRUSTED
2.3 Real-time Family Sync Setup
// WebSocket implementation - See API Specification Document "WebSocket Events"
// State sync via State Management Schema - Sync Slice
@WebSocketGateway()
export class FamilyGateway {
// Implementation details in API Specification
// Use sync middleware from State Management Schema
}
2.4 Mobile Family Management UI
// Screens following UI/UX Design System
// Material Design with warm color palette (peach, coral, rose)
// Minimum touch targets: 44x44px
- FamilyDashboard.tsx (use card components from Design System)
- AddChildScreen.tsx (spacious layout for one-handed use)
- ChildProfileScreen.tsx
- InviteFamilyMember.tsx
- FamilySettings.tsx
Phase 3: Core Tracking Features (Week 3-4)
🤖 AI Role: Mobile Developer & Offline-First Systems Expert
"Act as a Senior Mobile Developer specializing in React Native, offline-first architecture, and voice interfaces. Focus on building intuitive tracking features with voice input, offline support, and seamless sync using Redux and SQLite."
3.1 Database Schema for Activities
-- Use Migration V003 from Database Migration Scripts document
-- Includes partitioned tables for scalability
-- Run performance optimization indexes from Migration V005
3.2 Activity Tracking Services
// Backend services - See API Specification "Activity Tracking Endpoints"
// Implement all REST endpoints with proper error codes
@Injectable()
export class TrackingService {
// Use error codes from Error Handling & Logging Standards
// Implement offline queue from State Management Schema
async logFeeding(data: FeedingDto) {
// Follow API schema from specification
// Emit WebSocket events per API Specification
// Update Redux state per State Management Schema
}
}
3.3 Voice Input Integration
// Complete implementation in Voice Input Processing Guide
// Multi-language patterns for all 5 MVP languages
// Whisper API configuration from Environment Configuration Guide
import { WhisperService } from './services/whisperService';
// Use natural language patterns from Voice Input Processing Guide
// Implement error recovery and clarification prompts
3.4 Tracking UI Components
// Follow UI/UX Design System specifications
// Material Design components with warm palette
// One-handed operation optimization (bottom 60% of screen)
- QuickActionButtons.tsx (FAB positioning from Design System)
- FeedingTimer.tsx
- SleepTracker.tsx
- DiaperLogger.tsx
- ActivityTimeline.tsx (use skeleton screens for loading)
3.5 Offline Support Implementation
// Complete offline architecture in State Management Schema
// See Offline Slice and middleware configuration
// Sync queue implementation from Sync Slice
Phase 4: AI Assistant Integration (Week 4-5)
🤖 AI Role: AI/ML Engineer & LLM Integration Specialist
"Act as an AI/ML Engineer with expertise in LangChain, OpenAI APIs, prompt engineering, and safety systems. Focus on building a helpful, safe, and contextually aware AI assistant with proper token management and response quality."
Context Review:
"Also review as a Child Safety Expert to ensure all AI responses are appropriate for parenting contexts and include proper medical disclaimers."
4.1 LLM Service Setup
// Complete LangChain configuration in AI Context & Prompting Templates document
// Use system prompts and safety boundaries from the document
import { initializeLangChain } from './config/langchain';
// See AI Context & Prompting Templates for:
// - Context window management (4000 tokens)
// - Safety boundaries and medical disclaimers
// - Personalization engine
4.2 Context Management System
// Full implementation in AI Context & Prompting Templates
// Priority weighting system for context selection
class AIContextBuilder {
// Use ContextManager from AI Context & Prompting Templates
// Implements token counting and prioritization
// Child-specific context templates
}
4.3 Chat Interface Implementation
// React Native Chat UI
// Follow UI/UX Design System for chat bubbles
// Implement localized responses from AI Context & Prompting Templates
const AIAssistantScreen = () => {
// Use conversation memory management from AI Context document
// Implement prompt injection protection
// Apply response formatting templates
};
4.4 Smart Notifications System
// Use patterns from API Specification - Analytics & Insights Endpoints
// Schedule based on predictions from AI
class SmartNotificationService {
// Reference notification preferences from Database Migration V006
// Use push notification setup from Environment Configuration Guide
}
Phase 5: Pattern Recognition & Analytics (Week 5-6)
🤖 AI Role: Data Scientist & Analytics Engineer
"Act as a Data Scientist with expertise in time-series analysis, pattern recognition, and data visualization. Focus on building accurate prediction algorithms, meaningful insights extraction, and clear data presentation using React Native charts."
Context Review:
"Review predictions as a Pediatric Data Analyst to ensure all insights are age-appropriate and medically sound."
5.1 Pattern Analysis Engine
// Pattern detection algorithms referenced in API Specification
// See "Analytics & Insights Endpoints" for complete schemas
@Injectable()
export class PatternAnalysisService {
// GraphQL queries from API Specification for complex data
// Use AI Context & Prompting Templates for pattern insights
async analyzeSleepPatterns(childId: string) {
// Implement sleep prediction from Voice Input Processing Guide
// Store predictions in State Management Schema - AI Slice
}
}
5.2 Predictive Algorithms
// Sleep prediction using patterns from API Specification
// Response format from "GET /api/v1/insights/{childId}/predictions"
class SleepPredictor {
// Algorithm matches Huckleberry's SweetSpot® approach
// 85% confidence target from API Specification
}
5.3 Analytics Dashboard
// Dashboard Components using UI/UX Design System
// Material Design cards and charts
// Victory Native from Technical Stack document
- WeeklySleepChart.tsx (use warm color palette)
- FeedingFrequencyGraph.tsx
- GrowthCurve.tsx (WHO percentiles)
- PatternInsights.tsx
- ExportReport.tsx
5.4 Report Generation
// PDF generation using libraries from Technical Stack
// GraphQL WeeklyReport query from API Specification
class ReportGenerator {
// Use report formatting from UI/UX Design System
// Include localized content for all 5 languages
}
Phase 6: Testing & Optimization (Week 6-7)
🤖 AI Role: QA Engineer & Performance Specialist
"Act as a Senior QA Engineer with expertise in Jest, Detox, performance testing, and accessibility compliance. Focus on comprehensive test coverage, performance optimization, and ensuring WCAG compliance."
Context Reviews:
1. "Review as a Security Auditor for vulnerability assessment"
2. "Review as an Accessibility Expert for WCAG AA/AAA compliance"
3. "Review as a Performance Engineer for optimization opportunities"
6.1 Unit Testing Implementation
// Complete testing strategy in Testing Strategy Document
// 80% code coverage requirement
// Use mock data structures from Testing Strategy Document
describe('TrackingService', () => {
// Test examples from Testing Strategy Document
// Use error codes from Error Handling & Logging Standards
});
describe('SleepPredictor', () => {
// Performance benchmarks from Testing Strategy Document
// 85% accuracy target for predictions
});
6.2 Integration Testing
// E2E tests with Detox - See Testing Strategy Document
// Critical user journeys and offline sync testing
describe('Complete tracking flow', () => {
// Test WebSocket sync from API Specification
// Verify offline queue from State Management Schema
});
6.3 Performance Optimization
// React Native optimizations from UI/UX Design System
// - 60fps scrolling requirement
// - 2-second max load time
// - Skeleton screens for loading states
// Backend optimizations from Database Migration Scripts
// - Partitioned tables for activities
// - Performance indexes from Migration V005
// - Redis caching from Environment Configuration
6.4 Security Audit
# Security checklist from multiple documents:
# - API Specification: Request signing, rate limiting
# - Environment Configuration: Secret rotation schedule
# - Database Migrations: COPPA/GDPR compliance tables
# - Error Handling: Audit logging implementation
Phase 7: Beta Testing & Launch Preparation (Week 7-8)
🤖 AI Role: DevOps Engineer & Mobile Deployment Specialist
"Act as a DevOps Engineer with expertise in CI/CD, mobile app deployment, TestFlight, Google Play Console, and production infrastructure. Focus on automated deployment pipelines, monitoring setup, and app store compliance."
Context Review:
"Review as a Compliance Officer for COPPA/GDPR requirements and app store policies"
7.1 Beta Testing Program
# Beta Testing Plan from Testing Strategy Document
- Recruit 50 diverse families (language/geography diversity)
- Testing groups from Mobile Build & Deployment Guide
- Use TestFlight/Play Console setup from Mobile Build & Deployment Guide
- Feedback collection via Testing Strategy Document metrics
7.2 App Store Preparation
# Complete requirements from Mobile Build & Deployment Guide
# iOS App Store - see "TestFlight Configuration" section
# Google Play Store - see "Google Play Console Configuration" section
# Web App Implementation review
# Store assets using UI/UX Design System guidelines:
- Screenshots with warm color palette
- App icon with peach/coral branding
- Localized descriptions for 5 languages
7.3 Monitoring Setup
// Sentry configuration from Environment Configuration Guide
// Error tracking setup from Error Handling & Logging Standards
import * as Sentry from '@sentry/react-native';
// Use Sentry DSN from Environment Configuration
// Implement error filtering from Error Handling document
// Analytics from Technical Stack document (PostHog/Matomo)
7.4 Production Infrastructure
# Use docker-compose.yml from Environment Configuration Guide
# Add production settings from Mobile Build & Deployment Guide
# Include all services from Technical Stack:
# - PostgreSQL, MongoDB, Redis, MinIO, Front end web server
Phase 8: Launch & Post-Launch (Week 8+)
🤖 AI Role: Product Manager & Growth Engineer
"Act as a Product Manager with expertise in user analytics, growth strategies, and iterative development. Focus on monitoring key metrics, user feedback analysis, and rapid iteration based on real-world usage."
Context Reviews:
1. "Analyze as a Data Analyst for user behavior patterns"
2. "Review as a Customer Success Manager for support improvements"
3. "Evaluate as a Growth Hacker for retention optimization"
8.1 Launch Checklist
## Technical - Reference Mobile Build & Deployment Guide
- [ ] Production environment live (Environment Configuration Guide)
- [ ] SSL certificates configured
- [ ] CDN configured (Technical Stack - performance section)
- [ ] Backup systems tested (Database Migration Scripts - maintenance)
- [ ] Monitoring dashboards active (Error Handling & Logging Standards)
- [ ] Error tracking enabled (Sentry setup)
- [ ] Analytics tracking verified (PostHog/Matomo)
## Legal
- [ ] Privacy policy published (COPPA/GDPR from Database Migrations)
- [ ] Terms of service published
- [ ] Compliance verified (Audit tables from Migration V007)
## Support
- [ ] Help documentation complete
- [ ] Multi-language support ready (5 languages)
- [ ] Error messages localized (Error Handling document)
8.2 Post-Launch Monitoring
// Key metrics from Testing Strategy Document
// Success criteria: 60% DAU, <2% crash rate, 4.0+ rating
const metrics = {
// Track via analytics setup from Environment Configuration
// Use error monitoring from Error Handling & Logging Standards
// Performance metrics from API Specification (p95 < 3s)
};
8.3 Rapid Iteration Plan
# Use CodePush from Mobile Build & Deployment Guide for OTA updates
# Follow staged rollout strategy from Mobile Build & Deployment Guide
# Week 1-2: Monitor error codes from Error Handling document
# Week 3-4: UI improvements based on Design System principles
# Month 2: Premium features from MVP Features document
Development Best Practices
Code Organization
/maternal-app
/src
/components
/common
/tracking
/ai
/screens
/services
/hooks
/utils
/redux
/slices
/actions
/locales
/navigation
/types
/maternal-app-backend
/src
/modules
/auth
/users
/families
/tracking
/ai
/common
/guards
/interceptors
/filters
/database
/entities
/migrations
Git Workflow
# Branch naming
feature/track-feeding
bugfix/sync-issue
hotfix/crash-on-login
# Commit messages
feat: add voice input for feeding tracker
fix: resolve timezone sync issue
docs: update API documentation
test: add unit tests for sleep predictor
CI/CD Pipeline
# GitHub Actions example
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install
- run: npm test
- run: npm run lint
build:
needs: test
runs-on: ubuntu-latest
steps:
- run: npm run build
- run: docker build
deploy:
needs: build
if: github.ref == 'refs/heads/main'
steps:
- run: ./deploy.sh
Risk Mitigation Strategies
Technical Risks
- LLM API Downtime
- Implement fallback to cached responses
- Queue queries for retry
- Basic rule-based responses as backup
- Scalability Issues
- Start with vertical scaling capability
- Design for horizontal scaling from day 1
- Implement caching aggressively
- Data Loss
- Automated backups every 6 hours
- Point-in-time recovery capability
- Multi-region backup storage
Business Risks
- Low User Adoption
- Quick onboarding (< 2 minutes)
- Immediate value demonstration
- Strong referral incentives
- High Churn Rate
- Weekly engagement emails
- Push notification optimization
- Feature discovery prompts
- Competitive Pressure
- Rapid feature iteration
- Strong AI differentiation
- Community building
Success Criteria
MVP Launch Success
- 1,000 downloads in first month
- 60% day-7 retention
- 4.0+ app store rating
- <2% crash rate
- 5+ activities logged per day per active user
- 70% of users trying AI assistant
3-Month Goals
- 10,000 active users
- 500 premium subscribers
- 50% month-over-month growth
- 4.5+ app store rating
- 3 major feature updates
- 2 partnership agreements
6-Month Vision
- 50,000 active users
- 2,500 premium subscribers
- Break-even on operational costs
- International expansion (10+ countries)
- Integration ecosystem launched
- Series A fundraising ready