normogen/.cursorrules
goose 17efc4f656 docs: reconcile documentation with reality (P3)
Make the project's documentation match the code and remove the sprawl. The docs
claimed Phase 2.8 (drug interactions) was 'planning/0%' and the backend '~91%
complete' — both wrong: 2.8 is implemented and live, plus the P0/P1 security
and test work is done. Five root CI/CD docs described a 'docker-build' CI job
that was removed; ~18 backend/ status snapshots and ~24 docs/implementation
duplicates cluttered the tree.

Deletions (85 files):
- Root: 4 stale CI/CD reports (CI-CD-{COMPLETION-REPORT,IMPLEMENTATION-SUMMARY,
  STATUS-REPORT,FINAL-STATUS}.md) — all describe the removed docker-build job.
- backend/: 18 phase/build/fix snapshots and code-dump .txt files.
- docs/: the 3 one-time reorg reports; ~17 docs/implementation duplicates and
  process artifacts; 4 stale docs/development CI docs + git snapshots;
  redundant deployment/testing files.
- thoughts/: STATUS.md (said Phase 2.4 in-progress), superseded phase notes and
  duplicative research inputs. tmp/ (928KB of CI debug logs, gitignored).

Moves (18 files):
- 9 genuine decision records -> docs/adr/ (Architecture Decision Records),
  date-prefixes stripped, with an index README.
- 8 historical-but-valuable phase plans/specs + the old CI-CD-FINAL-SOLUTION ->
  docs/archive/ (now-populated, with a README explaining it's superseded
  material). thoughts/ tree removed.

Rewrites (13 files) to match reality:
- Drop the fake '% complete' figures everywhere in favor of Implemented /
  In-Progress / Planned with concrete endpoint/feature lists.
- Phase 2.8 -> Implemented; add /api/interactions/* and /api/auth/{refresh,
  logout} to the endpoint lists; fix 'Rust 1.93' -> edition 2021.
- Add a Security section (token_version validation, hashed refresh-token
  persistence, fail-fast config, real-IP audit) and correct the test-coverage
  and deployment claims to reality.
- New canonical docs/development/CI-CD.md (4 jobs: format/clippy/build/test,
  mongo service, no docker-build + why).
- README, docs/README, product/{STATUS,ROADMAP,PROGRESS,README,introduction},
  implementation/README, development/README, testing/README, AI_AGENT_GUIDE,
  .cursorrules, .gooserules all updated.

Verified: greps for 'Phase 2.8 (Planning)', 'PLANNING (0%)', 'Rust 1.93',
'91%/10%/85% complete', and 'docker-build' return nothing outside docs/archive;
all internal doc links resolve; backend/src untouched (cargo build clean).
2026-06-27 16:02:16 -03:00

243 lines
7.2 KiB
Text

# 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) implemented; open work is the frontend (Phase 3)
## Technology Stack
### Backend
- **Language**: Rust (edition 2021)
- **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) implemented
- **Backend**: Phase 2.x feature-complete; security-hardened (token_version validation, hashed refresh tokens, fail-fast config, real-IP audit)
- **Frontend**: Early stage (Login/Register + API/store layer; router not wired)
- **Testing**: 18 unit + 13 integration (auth + medication), CI-gated with MongoDB
- **Deployment**: Docker on Solaria (image built manually — not in CI)
## 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