You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

369 lines
11 KiB
Markdown

# Know Foolery - Claude Code Project Guide
## Project Overview
Know Foolery is a cross-platform quiz game with a Go microservices backend and React/React Native frontend using Gluestack UI. This document provides guidance for future Claude Code sessions.
## Project Structure
```
knowfoolery/
├── docs/ # Project documentation
│ ├── architecture.md # System architecture
│ ├── api-specs.md # API specifications
│ └── deployment.md # Deployment guides
├── backend/ # Go microservices
│ ├── services/ # Individual microservices
│ │ ├── game-service/ # Game logic and session management
│ │ ├── question-service/ # Question CRUD operations
│ │ ├── user-service/ # User management
│ │ ├── leaderboard-service/ # Score and ranking logic
│ │ ├── session-service/ # Session and timer management
│ │ ├── admin-service/ # Admin panel backend
│ │ └── gateway-service/ # API gateway
│ ├── shared/ # Shared Go packages
│ │ ├── auth/ # JWT middleware and Zitadel integration
│ │ ├── database/ # Ent database client
│ │ ├── observability/ # Metrics and tracing
│ │ └── security/ # Security utilities
│ └── scripts/ # Build and deployment scripts
├── frontend/ # Cross-platform frontend
│ ├── packages/ # Shared packages
│ │ ├── ui-components/ # Gluestack UI components
│ │ ├── shared-logic/ # Business logic
│ │ └── shared-types/ # TypeScript types
│ ├── web/ # React web application
│ ├── mobile/ # React Native mobile app
│ └── desktop/ # Electron desktop app (future)
├── infrastructure/ # Infrastructure as code
│ ├── docker/ # Docker configurations
│ ├── kubernetes/ # K8s manifests
│ └── monitoring/ # Observability configs
├── tests/ # Testing utilities
│ ├── e2e/ # End-to-end tests
│ ├── load/ # Performance tests
│ └── security/ # Security tests
├── requirements.md # Project requirements
└── README.md # Setup and development guide
```
## Technology Stack
### Backend (Go)
- **Framework**: Fiber for HTTP routing
- **Database ORM**: Ent with PostgreSQL
- **Authentication**: Zitadel OAuth 2.0/OIDC
- **Observability**: Prometheus metrics, OpenTelemetry tracing
- **Communication**: gRPC for inter-service communication
- **Testing**: Go testing + testcontainers
- **Security**: Comprehensive input validation, JWT middleware
### Frontend (TypeScript)
- **Web**: React 18 with TypeScript
- **Mobile**: React Native with TypeScript
- **UI Framework**: Gluestack UI with NativeWind/Tailwind CSS
- **State Management**: React Context + useReducer
- **Testing**: Jest + React Testing Library + Playwright
### Database & Infrastructure
- **Primary Database**: PostgreSQL with Ent ORM
- **Cache**: Redis for sessions and performance
- **Authentication**: Self-hosted Zitadel
- **Deployment**: Docker + Kubernetes
- **Monitoring**: Prometheus + Grafana + Jaeger
## Key Architectural Decisions
### 1. Database Strategy
- **Development**: SQLite for fast local development
- **Testing**: PostgreSQL with testcontainers
- **Production**: PostgreSQL with high availability
- **ORM**: Ent (Facebook) for type-safe database operations
- **No Repository Pattern**: Direct Ent usage except for external APIs
### 2. Authentication Strategy
- **Local Development**: Mock JWT service
- **Production**: Self-hosted Zitadel
- **Repository Pattern**: Only for external integrations (Zitadel)
- **Security**: MFA required for admin accounts
### 3. Cross-Platform UI Strategy
- **Design System**: Gluestack UI for consistent components
- **Styling**: NativeWind/Tailwind CSS for utility-first styling
- **Code Sharing**: Same components work on web and mobile
- **Performance**: Native performance on mobile, optimized for web
## Development Guidelines
### Code Organization
```go
// Backend service structure
services/
├── game-service/
├── cmd/main.go # Service entry point
├── internal/
├── handlers/ # HTTP handlers
├── services/ # Business logic
└── models/ # Ent models
├── api/ # API definitions
└── tests/ # Service tests
```
```typescript
// Frontend component structure
packages/ui-components/
├── src/
├── GameCard/
├── GameCard.tsx # Main component
├── GameCard.test.tsx # Tests
└── index.ts # Exports
└── index.ts # Package exports
```
### Naming Conventions
- **Go**: PascalCase for exported, camelCase for unexported
- **TypeScript**: PascalCase for components, camelCase for functions
- **Files**: kebab-case for directories, PascalCase for components
- **Database**: snake_case for tables and columns
### Testing Standards
- **Unit Tests**: Required for all business logic
- **Integration Tests**: Required for database operations
- **E2E Tests**: Required for critical user journeys
- **Security Tests**: Required for all input validation
- **Performance Tests**: Required for high-load scenarios
## Security Requirements
### Critical Security Measures (Implemented Early)
1. **Input Validation**: All user inputs sanitized and validated
2. **SQL Injection Prevention**: Ent parameterized queries only
3. **XSS Protection**: HTML escaping and CSP headers
4. **Authentication**: JWT validation with secure middleware
5. **Rate Limiting**: Per-user and global rate limits
6. **HTTPS**: TLS encryption for all communications
7. **CORS**: Strict cross-origin policies
### Game Integrity
- **Server-Side Validation**: All game logic on backend
- **Score Verification**: Server calculates all scores
- **Session Security**: Tamper-proof session management
- **Anti-Cheating**: Multiple validation layers
## Common Commands
### Backend Development
```bash
# Start all services locally
docker-compose up -d
# Run specific service
cd ~/Projects/go/src/knowfoolery/backend/services/game-service
go run cmd/main.go
# Run tests with coverage
go test -v -cover ./...
# Generate Ent code
cd ~/Projects/go/src/knowfoolery/database/ent
go run -mod=mod entgo.io/ent/cmd/ent describe ./schema
# Update database schema description from Ent code
cd ~/Projects/go/src/knowfoolery/database/ent
go run -mod=mod entgo.io/ent/cmd/ent describe ./schema > ./schema/schema.md
```
### Frontend Development
```bash
# Install dependencies
npm install
# Start web development
cd ~/Projects/go/src/knowfoolery/frontend/web
npm run dev
# Start mobile development
cd ~/Projects/go/src/knowfoolery/frontend/mobile
npm run ios # or npm run android
# Run tests
npm test
# Build for production
npm run build
```
### Database Operations
```bash
# Run migrations
go run ~/Projects/go/src/knowfoolery/backend/scripts/migrate.go
# Reset database (development only)
go run ~/Projects/go/src/knowfoolery/backend/scripts/reset-db.go
# Seed test data
go run ~/Projects/go/src/knowfoolery/backend/scripts/seed.go
```
## Environment Configuration
### Development (.env.dev)
```bash
# Database
DATABASE_URL=sqlite://./dev.db
REDIS_URL=redis://localhost:6379
# Authentication
JWT_SECRET=dev-secret-key
ZITADEL_URL=http://localhost:8080
# Observability
PROMETHEUS_PORT=9090
JAEGER_ENDPOINT=http://localhost:14268
```
### Production (.env.prod)
```bash
# Database
DATABASE_URL=postgres://user:pass@db:5432/knowfoolery
REDIS_URL=redis://redis:6379
# Authentication
JWT_SECRET=${JWT_SECRET}
ZITADEL_URL=${ZITADEL_URL}
# Observability
PROMETHEUS_PORT=9090
JAEGER_ENDPOINT=${JAEGER_ENDPOINT}
```
## Development Workflow
### 1. Feature Development
1. Create feature branch from main
2. Implement domain model changes
3. Add comprehensive tests for domain model
3. Implement database and ORM changes
3. Add comprehensive tests for domain model
2. Implement backend service changes
3. Add comprehensive tests
4. Implement frontend components
5. Test cross-platform compatibility
6. Update documentation
7. Create pull request
### 2. Testing Checklist
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Security tests pass
- [ ] E2E tests pass
- [ ] Cross-platform UI tests pass
- [ ] Performance tests pass
### 3. Deployment Process
1. Merge to main branch
2. Automated CI/CD pipeline
3. Deploy to staging environment
4. Run smoke tests
5. Deploy to production
6. Monitor metrics and alerts
## Troubleshooting
### Common Issues
#### Database Connection Errors
```bash
# Check database status
docker-compose ps
# Reset database connection
docker-compose restart postgres
# Check logs
docker-compose logs postgres
```
#### Authentication Issues
```bash
# Verify JWT token
curl -H "Authorization: Bearer $TOKEN" localhost:8080/api/health
# Check Zitadel status
curl localhost:8080/.well-known/openid_configuration
```
#### Frontend Build Issues
```bash
# Clear node modules
rm -rf node_modules package-lock.json
npm install
# Clear build cache
npm run clean
npm run build
```
## Performance Optimization
### Backend Optimization
- Use Ent query optimization
- Implement Redis caching
- Profile with pprof
- Monitor with Prometheus
### Frontend Optimization
- Bundle size analysis
- React Native performance profiling
- Gluestack UI optimization
- Image and asset optimization
## Security Checklist
### Before Each Release
- [ ] Security dependencies updated
- [ ] Vulnerability scan passed
- [ ] Penetration testing completed
- [ ] Security headers configured
- [ ] Input validation tested
- [ ] Authentication flows verified
- [ ] Rate limiting tested
- [ ] Audit logs reviewed
## Monitoring and Alerts
### Key Metrics to Watch
- **Response Times**: API endpoint performance
- **Error Rates**: Application stability
- **Authentication**: Success/failure rates
- **Game Metrics**: Session duration, completion rates
- **Security Events**: Failed logins, rate limit hits
### Alert Conditions
- API response time > 500ms
- Error rate > 1%
- Authentication failure rate > 5%
- Database connection issues
- Security events detected
## Future Development Notes
### Mobile App Considerations
- Platform-specific optimizations needed
- App store submission requirements
- Push notification integration
- Offline capability planning
### Desktop App Considerations
- Electron performance optimization
- Native OS integration
- Auto-update mechanism
- Platform-specific packaging
### Scalability Planning
- Horizontal scaling strategies
- Database sharding considerations
- CDN integration for global reach
- Microservice boundaries refinement
This guide should be updated as the project evolves and new decisions are made.