# Normogen Project Rules for AI Agents

## Project Overview
- **Name**: Normogen (Balanced Life in Mapudungun)
- **Type**: Monorepo (Rust backend + React frontend)
- **Goal**: Open-source health data platform
- **Current Phase**: 2.8 (Drug Interactions & Advanced Features)

## Technology Stack

### Backend
- **Language**: Rust 1.93
- **Framework**: Axum 0.7 (async web framework)
- **Database**: MongoDB 7.0
- **Auth**: JWT (15min access, 30day refresh tokens)
- **Security**: PBKDF2 password hashing (100K iterations), rate limiting

### Frontend
- **Framework**: React 19.2.4 + TypeScript 4.9.5
- **UI**: Material-UI (MUI) 7.3.9
- **State**: Zustand 5.0.11
- **HTTP**: Axios 1.13.6

## File Structure Rules

### Backend (`backend/src/`)
- **handlers/** - API route handlers (one file per feature)
- **models/** - Data models with Repository pattern
- **middleware/** - JWT auth, rate limiting, security headers
- **services/** - Business logic (OpenFDA, interactions)
- **config/** - Environment configuration
- **auth/** - JWT service implementation
- **security/** - Audit logging, session management, account lockout
- **db/** - MongoDB implementation

### Frontend (`web/normogen-web/src/`)
- **pages/** - Route components (LoginPage, RegisterPage, etc.)
- **components/** - Reusable components (ProtectedRoute, etc.)
- **services/** - API service layer (axios instance)
- **store/** - Zustand state stores
- **types/** - TypeScript type definitions

## Code Style Rules

### Rust (Backend)
1. **Always** run `cargo fmt` before committing
2. **Always** run `cargo clippy` and fix warnings
3. Use `Result<_, ApiError>` for error handling
4. Use `?` operator for error propagation
5. Document public APIs with rustdoc (`///`)
6. Use async/await for database operations
7. Use repository pattern for database access

### TypeScript (Frontend)
1. Use functional components with hooks
2. Prefer TypeScript interfaces over types
3. Use Material-UI components
4. Use Zustand for state management (not Redux)
5. Use axios for HTTP requests (configured in services/api.ts)
6. Use React Router DOM for routing

## Authentication Rules

### Protected Routes
1. **Always** require JWT for protected endpoints
2. Use `middleware::jwt_auth_middleware` in main.rs
3. Extract user_id from validated JWT claims
4. Return 401 Unauthorized for invalid/expired tokens

### Token Management
1. Access tokens: 15 minute expiry
2. Refresh tokens: 30 day expiry
3. Rotate refresh tokens on refresh
4. Invalidate tokens on password change/logout

## API Design Rules

### Route Naming
- Use kebab-case: `/api/health-stats`
- Use plural nouns for collections: `/api/medications`
- Use specific actions: `/api/medications/:id/log`
- Group by resource: `/api/users/me/settings`

### HTTP Methods
- GET: Read resources
- POST: Create resources or trigger actions
- PUT: Update entire resource
- DELETE: Delete resource

### Response Format
```json
{
  "id": "string",
  "created_at": 1234567890,
  "updated_at": 1234567890
}
```
- Use `timestamp_millis()` for DateTime serialization
- Never expose passwords or sensitive data
- Include error messages in 4xx/5xx responses

## Database Rules

### Collections
- Use lowercase, plural collection names: `users`, `medications`
- Index frequently queried fields
- Use MongoDB ObjectId for primary keys

### Models
- Use `mongodb::bson::DateTime` for dates (not chrono)
- Implement Repository trait pattern
- Use `serde` for serialization/deserialization

## Testing Rules

### Backend Tests
1. **Always** write tests for new features
2. Test both success and error paths
3. Mock external dependencies (OpenFDA API)
4. Use descriptive test names
5. Run `cargo test` before committing

### Frontend Tests
1. Test user interactions
2. Test API service calls (mock axios)
3. Test state management
4. Run `npm test` before committing

### Integration Tests
1. Test API endpoints end-to-end
2. Use scripts in `docs/testing/`
3. Test authentication flow
4. Test permission checks

## Security Rules

### Passwords
1. **Never** log passwords
2. **Never** return passwords in API responses
3. Use PBKDF2 with 100K iterations
4. Implement zero-knowledge recovery phrases

### Rate Limiting
1. Apply to all routes
2. Use `middleware::general_rate_limit_middleware`
3. Implement account lockout (5 attempts, 15min base, max 24hr)

### Data Validation
1. Validate all inputs using `validator` crate
2. Sanitize user input
3. Use MongoDB's BSON type system

## Commit Rules

### Commit Message Format
```
<type>(<scope>): <description>

[optional body]
```

### Types
- `feat` - New feature
- `fix` - Bug fix
- `docs` - Documentation changes
- `test` - Test changes
- `refactor` - Code refactoring
- `chore` - Maintenance tasks

### Examples
- `feat(backend): implement drug interaction checking`
- `fix(medication): resolve adherence calculation bug`
- `docs(readme): update quick start guide`
- `test(auth): add refresh token rotation tests`

## Documentation Rules

1. **Always** update relevant docs in `docs/implementation/` for new features
2. Update STATUS.md when completing phases
3. Add comments for complex logic
4. Keep AI_AGENT_GUIDE.md updated with architectural changes

## Common Patterns

### Adding API Endpoint
```rust
// 1. Add model to backend/src/models/
// 2. Add repository methods
// 3. Add handler to backend/src/handlers/
// 4. Register route in backend/src/main.rs
// 5. Add tests
// 6. Update docs
```

### Adding Frontend Page
```typescript
// 1. Add types to web/normogen-web/src/types/api.ts
// 2. Add API service to web/normogen-web/src/services/api.ts
// 3. Add Zustand store to web/normogen-web/src/store/useStore.ts
// 4. Create page in web/normogen-web/src/pages/
// 5. Add route in App.tsx
```

## Before Committing Checklist

- [ ] All tests pass (`cargo test`)
- [ ] No clippy warnings (`cargo clippy`)
- [ ] Code formatted (`cargo fmt`)
- [ ] Documentation updated
- [ ] Commit message follows conventions
- [ ] No hardcoded values (use env vars)
- [ ] Authentication required for protected routes
- [ ] Error handling implemented

## Important Notes

1. **Never** hardcode configuration values - use environment variables
2. **Always** check if similar code exists before implementing
3. **Always** run tests before committing
4. **Never** skip error handling - use Result types
5. **Always** consider security implications
6. **Never** expose sensitive data in API responses

## Current Status

- **Phase**: 2.8 (Drug Interactions & Advanced Features)
- **Backend**: ~91% complete
- **Frontend**: ~10% complete
- **Testing**: Comprehensive test coverage
- **Deployment**: Docker on Solaria

## Documentation

- **[AI Agent Guide](docs/AI_AGENT_GUIDE.md)** - Comprehensive guide
- **[AI Quick Reference](docs/AI_QUICK_REFERENCE.md)** - Essential commands
- **[Documentation Index](docs/README.md)** - All documentation
- **[Product Status](docs/product/STATUS.md)** - Current progress

---

**Generated for**: AI Agents (Cursor, Copilot, Goose, etc.)  
**Last Updated**: 2026-03-09  
**Project**: Normogen - Open-source health data platform
