# CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## ๐Ÿšจ CRITICAL: MANDATORY MCP SERVER USAGE ๐Ÿšจ **YOU MUST USE MCP SERVERS PROACTIVELY AND EXTENSIVELY**. This codebase requires heavy use of MCP tools for all operations. Never work blind - always use the appropriate MCP servers BEFORE making any decisions or changes. ### โšก INSTANT MCP TRIGGERS FOR HARBORSMITH **These MUST happen automatically without asking:** | User Says | Immediate MCP Response | Full Chain | |-----------|----------------------|------------| | "charter" or "booking" | `Serena:find_symbol("*charter*")` | โ†’ Zen:analyze โ†’ Edit โ†’ Test | | "yacht" or "vessel" | `Serena:search_for_pattern("yacht\|vessel")` | โ†’ Understand โ†’ Modify โ†’ Verify | | "payment" or "stripe" | `Context7:resolve-library-id("stripe")` | โ†’ Docs โ†’ Implement โ†’ Review | | "auth" or "login" | `Zen:secaudit` + `Serena:find_symbol("*auth*")` | โ†’ Security check โ†’ Fix โ†’ Test | | "slow" or "performance" | `Browser-tools:runPerformanceAudit()` | โ†’ Zen:analyze โ†’ Optimize โ†’ Verify | | "error" or "bug" | `Zen:debug` + `Browser-tools:getConsoleErrors()` | โ†’ Investigate โ†’ Fix โ†’ Validate | | "deploy" | `Zen:precommit` | โ†’ Validate โ†’ Build โ†’ Deploy | | "test" | `Zen:testgen` + `Playwright:automate` | โ†’ Generate โ†’ Run โ†’ Report | | ANY code edit | `IDE:getDiagnostics()` | โ†’ Fix errors โ†’ Zen:review | | New feature | `Zen:planner` | โ†’ Plan โ†’ Research โ†’ Implement | ### ๐ŸŽฏ MCP Server Quick Reference **Copy-paste these patterns:** ```typescript // Debug pattern await zen.debug({ step: "Investigating charter booking issue", confidence: "medium" }) await browserTools.getConsoleErrors() await serena.find_symbol("CharterBooking") // Review pattern await zen.codereview({ relevant_files: ["apps/api/*"], review_type: "security" }) // Performance pattern await browserTools.runPerformanceAudit() await zen.thinkdeep({ focus_areas: ["performance"] }) await serena.search_for_pattern("SELECT.*FROM", context_lines_after: 5) ``` ### Available MCP Servers and When to Use Them #### 1. **Zen** - ALWAYS USE FOR COMPLEX TASKS - **MANDATORY for**: Debugging, code review, architecture decisions, planning - **Tools**: `thinkdeep`, `debug`, `codereview`, `consensus`, `planner`, `precommit` - **Usage**: ANY complex problem, architecture decision, or code quality check - **Example**: `mcp__zen__debug` for any bug, `mcp__zen__codereview` after writing code #### 2. **Serena** - ALWAYS USE FOR CODE NAVIGATION - **MANDATORY for**: Reading/understanding code, refactoring, symbol search - **Tools**: `find_symbol`, `get_symbols_overview`, `search_for_pattern`, `replace_symbol_body` - **Usage**: NEVER read files directly without first using Serena's semantic tools - **Example**: Always use `find_symbol` before editing, `get_symbols_overview` before understanding a file #### 3. **Context7** - ALWAYS USE FOR LIBRARIES - **MANDATORY for**: Any external library usage or documentation - **Tools**: `resolve-library-id`, `get-library-docs` - **Usage**: Before implementing ANY library feature, get its documentation - **Example**: Using Stripe? First: `resolve-library-id("stripe")` then `get-library-docs` #### 4. **Playwright** - USE FOR ALL UI TESTING - **Tools**: `browser_navigate`, `browser_click`, `browser_snapshot`, `browser_fill_form` - **Usage**: Testing user flows, capturing UI state, form validation #### 5. **21st-dev Magic** - USE FOR UI COMPONENTS - **Tools**: `21st_magic_component_builder`, `logo_search` - **Usage**: When user requests UI components or logos ### MCP Usage Rules 1. **ALWAYS chain MCP tools** - One tool's output should trigger the next 2. **NEVER make assumptions** - Use tools to verify everything 3. **Parallel execution** - Run independent MCP calls simultaneously 4. **Use Zen for thinking** - Complex reasoning MUST go through Zen 5. **Verify with tools** - After changes, ALWAYS run verification tools ## Project Overview **Harborsmith** is a comprehensive yacht charter and maintenance management platform for the San Francisco Bay Area, built with a microservices architecture using Docker containers behind nginx. ### Technology Stack **Frontend:** - Nuxt 3 (SSG for website, SPA for webapp, SSR/SPA for admin portal) - Tailwind CSS v4, Nuxt UI v3, Tremor (dashboards), Motion.dev (animations) - Pinia (state management), VueUse (utilities) - Uppy (file uploads, 10GB+ support), hls.js (video streaming) **Backend:** - Fastify + tRPC (type-safe APIs) - Prisma ORM with PostgreSQL 16 - BullMQ (job queues), Socket.io (real-time) - Redis (caching), PgBouncer (connection pooling) **Infrastructure:** - Docker Compose orchestration - nginx reverse proxy (host level) - External MinIO for object storage - Keycloak (authentication), Directus (CMS) - Multiple service replicas for high availability ## Architecture Pattern ``` nginx (host) โ†’ Docker Containers โ†’ Services โ”œโ”€โ”€ API (3 replicas) โ†’ PostgreSQL/Redis โ”œโ”€โ”€ Website (2 replicas) โ”œโ”€โ”€ WebApp (2 replicas) โ””โ”€โ”€ Portal (2 replicas) ``` ## Essential Commands ```bash # Start all services docker-compose up -d # Stop all services docker-compose down # View logs docker-compose logs -f [service_name] # Run database migrations docker-compose run --rm api npx prisma migrate deploy # Database operations docker exec harborsmith_postgres pg_dump -U $DB_USER harborsmith > backup.sql docker exec -i harborsmith_postgres psql -U $DB_USER harborsmith < backup.sql # Deploy to production ./deploy.sh # Check service health ./scripts/wait-for-healthy.sh # Rebuild specific service docker-compose up -d --no-deps --build api-1 ``` ## Service Ports - **3000, 3010, 3020**: API replicas - **3001-3002**: Website replicas - **3003-3004**: WebApp replicas - **3005-3006**: Portal replicas - **5432**: PostgreSQL (via PgBouncer on 6432) - **6379**: Redis - **9000**: MinIO (external) - **8080**: Keycloak ## Environment Configuration Critical environment variables that MUST be set: ```bash # Database DB_USER=harborsmith DB_PASSWORD= # External MinIO (already running separately) MINIO_ENDPOINT= MINIO_PORT=9000 MINIO_USE_SSL=true MINIO_ACCESS_KEY= MINIO_SECRET_KEY= # Authentication KEYCLOAK_URL=https://auth.harborsmith.com KEYCLOAK_REALM=harborsmith KEYCLOAK_CLIENT_ID=harborsmith-webapp # Payments STRIPE_SECRET_KEY=sk_live_ CAL_API_KEY=cal_live_ ``` ## Critical Implementation Details ### WebSocket Scaling - nginx uses `ip_hash` for sticky sessions - Socket.io configured with Redis adapter - Connection state recovery enabled ### Database Optimization - PgBouncer for connection pooling (transaction mode) - Proper indexes on all foreign keys - PostgreSQL performance tuning applied ### Security Configuration - CORS with origin validation - Application-level rate limiting - JWT refresh token rotation - All containers expose ports only to localhost ### Caching Strategy - Cache-aside pattern with Redis - TTL strategies per data type - Cache warming for popular content ### Media Handling - Uppy for resumable uploads (10GB+) - Tus protocol implementation - FFmpeg for HLS video transcoding - MinIO for S3-compatible storage ## ๐Ÿ”ฅ Harborsmith-Specific MCP Workflows ### Charter Booking Flow Issues ```bash 1. Zen:debug("charter booking failing") 2. Serena:find_symbol("CharterService/createBooking") 3. Browser-tools:getNetworkErrors() 4. Context7:get-library-docs("/stripe/stripe-node", topic="payments") 5. Fix issue with Serena:replace_symbol_body 6. Playwright:test booking flow 7. Zen:codereview(review_type="security") ``` ### Yacht Maintenance Scheduling ```bash 1. Zen:planner("implement maintenance scheduling") 2. Serena:search_for_pattern("maintenance.*schedule") 3. Context7:resolve-library-id("node-cron") 4. Implement with BullMQ queues 5. Zen:testgen for maintenance service 6. Browser-tools:performance audit ``` ### Payment Integration ```bash 1. Context7:get-library-docs("/stripe/stripe-node", topic="webhooks") 2. Zen:secaudit(focus="payment-processing") 3. Serena:find_symbol("PaymentService") 4. Implement Stripe webhook handler 5. Zen:codereview(review_type="security", severity_filter="high") 6. Playwright:test payment flow with test cards ``` ### Admin Portal Dashboard ```bash 1. Zen:consensus("dashboard visualization library") 2. Context7:resolve-library-id("tremor") 3. Serena:find_symbol("AdminDashboard") 4. Implement with Tremor components 5. Browser-tools:runAccessibilityAudit() 6. Zen:codereview(focus="performance") ``` ## Development Workflow with MCP ### Before ANY Code Change: 1. **Use Serena** to understand current implementation - `find_symbol` to locate code - `find_referencing_symbols` to check impact 2. **Use Zen** to plan approach - `planner` for complex tasks - `thinkdeep` for architecture decisions ### During Implementation: 1. **Use Context7** for library documentation 2. **Use Serena** for code modifications 3. **Use Zen chat** for second opinions ### After Changes: 1. **ALWAYS run** `getDiagnostics()` via IDE tools 2. **Use Zen** `codereview` for quality check 3. **Use Zen** `precommit` before committing ### For Debugging: 1. **Start with Zen** `debug` for systematic investigation 2. **Use Browser-tools** for UI issues 3. **Use Serena** to navigate to problematic code ## Monorepo Structure (Planned) ``` harborsmith/ โ”œโ”€โ”€ apps/ โ”‚ โ”œโ”€โ”€ website/ # Public SSG site โ”‚ โ”œโ”€โ”€ webapp/ # Customer SPA โ”‚ โ”œโ”€โ”€ portal/ # Admin portal โ”‚ โ””โ”€โ”€ api/ # Main API โ”œโ”€โ”€ packages/ โ”‚ โ”œโ”€โ”€ shared/ # Shared types/utils โ”‚ โ”œโ”€โ”€ ui/ # UI components โ”‚ โ””โ”€โ”€ database/ # Prisma schema โ””โ”€โ”€ services/ # Microservices โ”œโ”€โ”€ charter/ โ”œโ”€โ”€ maintenance/ โ”œโ”€โ”€ payments/ โ””โ”€โ”€ notifications/ ``` ## ๐Ÿงช Automated Testing & Review Patterns ### MANDATORY Test Automation for Every Feature ```bash # 1. Generate comprehensive tests Zen:testgen(target="CharterService", confidence="high") # 2. Run unit tests npm run test:unit -- --coverage # 3. E2E automation Playwright:browser_navigate("/charter/new") Playwright:browser_fill_form([ {name: "vessel", value: "Yacht001"}, {name: "date", value: "2024-03-15"}, {name: "duration", value: "4"} ]) Playwright:browser_click("Book Charter") Playwright:browser_wait_for(text="Booking Confirmed") # 4. Validate UI Browser-tools:runAccessibilityAudit() Browser-tools:runPerformanceAudit() Browser-tools:getConsoleErrors() # 5. Security review Zen:secaudit(audit_focus="owasp", threat_level="high") ``` ### Code Review Automation ```bash # After EVERY significant change Zen:codereview( relevant_files=["apps/api/src/**"], review_type="full", severity_filter="medium", model="gemini-2.5-pro" ) # Security-focused review for auth/payment Zen:codereview( review_type="security", focus_on="authentication,authorization,payment", model="o3" ) # Performance review for critical paths Zen:codereview( review_type="performance", focus_on="database queries,caching,api response time", model="gemini-2.5-flash" ) ``` ### Continuous Testing Pattern ```bash # Watch mode during development npm run test:watch # After each code change IDE:getDiagnostics() npm run lint npm run typecheck # Before commit Zen:precommit( focus_on="security,completeness,tests", severity_filter="high" ) # Full validation before deploy ./scripts/run-all-tests.sh Zen:codereview(review_type="full") Browser-tools:runAuditMode() ``` ## MCP-First Development Principles 1. **NEVER work without MCP tools** - Always gather context first 2. **Chain operations** - Each MCP output informs the next action 3. **Parallel when possible** - Run independent MCP calls simultaneously 4. **Verify constantly** - Use diagnostic tools after every change 5. **Think through Zen** - Complex reasoning must use Zen tools 6. **Document in memories** - Use Serena to persist important decisions ## ๐Ÿš€ Harborsmith Feature Implementation Patterns ### Crew Management Feature ```bash # Planning Zen:planner("crew management system with scheduling") Zen:consensus([{model:"o3",stance:"for"},{model:"gemini-2.5-pro",stance:"neutral"}]) # Research Context7:get-library-docs("/prisma/prisma", topic="relations") Serena:search_for_pattern("crew|staff|employee") # Implementation Serena:insert_after_symbol("YachtModel", "crew relation") Serena:create CrewService with CRUD operations Implement crew scheduling with BullMQ # Validation Zen:testgen("CrewService", confidence="high") Playwright:test crew assignment flow Zen:codereview(review_type="full") ``` ### Real-time Vessel Tracking ```bash # Architecture Zen:thinkdeep("real-time vessel tracking architecture") Context7:get-library-docs("/socketio/socket.io", topic="namespaces") # Implementation Serena:find_symbol("SocketService") Implement vessel namespace in Socket.io Add Redis adapter for scaling Integrate with AIS data provider # Testing Playwright:browser_navigate("/vessel-tracker") Browser-tools:getNetworkLogs() # Check WebSocket Zen:codereview(focus="real-time-performance") ``` ### Weather Integration ```bash # Research Context7:resolve-library-id("openweather") Zen:consensus("weather API provider selection") # Implementation Serena:create WeatherService Implement caching with Redis (1hr TTL) Add weather alerts for charters # Validation Zen:testgen("WeatherService") Browser-tools:runPerformanceAudit() Zen:precommit() ``` ## Common MCP Workflows ### Bug Investigation ``` 1. Zen debug (start investigation) 2. Browser-tools (gather symptoms) 3. Serena find_symbol (locate code) 4. Zen debug (refine hypothesis) 5. Serena replace_symbol_body (fix) 6. Zen codereview (verify fix) ``` ### Feature Implementation ``` 1. Zen planner (break down task) 2. Context7 (get library docs) 3. Serena find_symbol (understand current code) 4. Implement changes 5. Zen codereview (quality check) 6. Playwright (test user flow) ``` ### Performance Optimization ``` 1. Browser-tools audits (baseline) 2. Zen thinkdeep (analyze bottlenecks) 3. Serena search_for_pattern (find issues) 4. Optimize code 5. Browser-tools audits (verify improvement) ``` ## IMPORTANT: External MinIO Integration MinIO runs in a SEPARATE Docker Compose stack. The application connects via: - `MINIO_ENDPOINT`: External MinIO host/IP - `MINIO_PORT`: Usually 9000 - Ensure network connectivity between Docker containers and MinIO ## ๐Ÿš€ Production Deployment & Monitoring Workflows ### Pre-Deployment MCP Validation ```bash # 1. Comprehensive security audit Zen:secaudit( audit_focus="comprehensive", threat_level="high", compliance_requirements=["PCI DSS", "GDPR"] ) # 2. Performance baseline Browser-tools:runPerformanceAudit() Browser-tools:runBestPracticesAudit() # 3. Final code review Zen:codereview( review_type="full", review_validation_type="external", model="o3" ) # 4. Pre-commit validation Zen:precommit( precommit_type="external", severity_filter="medium", include_staged=true, include_unstaged=true ) ``` ### Deployment Automation ```bash # 1. Build and test docker-compose build docker-compose run --rm api npm test docker-compose run --rm api npm run test:e2e # 2. Database migration docker-compose run --rm api npx prisma migrate deploy # 3. Rolling deployment ./scripts/deploy.sh --strategy=rolling # 4. Health verification ./scripts/wait-for-healthy.sh # 5. Post-deployment validation Playwright:browser_navigate("https://harborsmith.com") Browser-tools:runAuditMode() ``` ### Monitoring & Alerting Patterns ```bash # Container health monitoring docker-compose ps docker-compose logs -f --tail=100 # Performance monitoring Browser-tools:runPerformanceAudit() # Every hour Zen:analyze(analysis_type="performance") # Daily # Error tracking Browser-tools:getConsoleErrors() # Real-time Zen:debug(confidence="exploring") # On error spike # Security monitoring Zen:secaudit(audit_focus="dependencies") # Weekly Browser-tools:runBestPracticesAudit() # Daily ``` ### Incident Response Workflow ```bash # 1. Immediate assessment Zen:debug( step="Production incident: [description]", confidence="exploring", model="o3" ) # 2. Gather evidence Browser-tools:getConsoleErrors() Browser-tools:getNetworkErrors() docker-compose logs --tail=1000 api # 3. Root cause analysis Zen:thinkdeep( focus_areas=["performance", "security", "architecture"], thinking_mode="high" ) # 4. Implement fix Serena:find_symbol("[problematic code]") Serena:replace_symbol_body() Zen:codereview(review_type="quick") # 5. Deploy hotfix ./scripts/deploy-hotfix.sh Zen:precommit(precommit_type="internal") ``` ### Backup & Recovery ```bash # Database backup docker exec harborsmith_postgres pg_dump -U $DB_USER harborsmith > backup_$(date +%Y%m%d_%H%M%S).sql # MinIO data sync rclone sync harborsmith-minio:/ backup/minio/ # Configuration backup cp -r .env* docker-compose.yml nginx.conf backup/config/ # Recovery validation docker-compose down docker-compose up -d ./scripts/wait-for-healthy.sh Playwright:test critical user flows ``` ## Security Checklist Before ANY commit: - [ ] Run Zen `precommit` validation - [ ] No secrets in code - [ ] CORS properly configured - [ ] Rate limiting implemented - [ ] Input validation with Zod - [ ] SQL injection prevented (Prisma) ## Performance Targets - Page load: < 1 second - API response: < 200ms - Database queries: < 50ms - Upload support: 10GB+ files - Concurrent users: 10,000+ ## ๐Ÿ”ด MANDATORY MCP CHECKLIST **BEFORE responding to ANY request:** - [ ] Did user mention a file/function? โ†’ `Serena:find_symbol()` NOW - [ ] Is this about a library? โ†’ `Context7:docs` FIRST - [ ] Any UI/browser mentioned? โ†’ `Browser-tools/Playwright` IMMEDIATELY - [ ] Did I write/change code? โ†’ `IDE:getDiagnostics()` MANDATORY - [ ] Is this complex? โ†’ `Zen:analysis` REQUIRED - [ ] Multiple steps? โ†’ `Zen:planner` FIRST - [ ] About to commit? โ†’ `Zen:precommit` CHECK ## ๐ŸŽฏ Harborsmith Domain-Specific Triggers | Domain | Auto-Trigger MCP Chain | |--------|------------------------| | **Charter Operations** | Serena:find("CharterService") โ†’ Zen:analyze โ†’ Test booking flow | | **Vessel Management** | Serena:find("Yacht*") โ†’ Check maintenance โ†’ Verify availability | | **Payment Processing** | Context7:stripe docs โ†’ Zen:secaudit โ†’ Implement webhooks | | **Crew Scheduling** | Zen:planner โ†’ BullMQ queues โ†’ Test assignments | | **Customer Portal** | Browser:audit โ†’ Check auth โ†’ Verify responsive | | **Admin Dashboard** | Tremor components โ†’ Performance check โ†’ Access control | | **Maintenance Tracking** | Find maintenance service โ†’ Check schedules โ†’ Test notifications | | **Document Management** | MinIO integration โ†’ Uppy config โ†’ Test 10GB uploads | | **Real-time Updates** | Socket.io check โ†’ Redis adapter โ†’ Test scaling | | **Reporting/Analytics** | Prisma aggregations โ†’ Chart.js โ†’ Export features | ## ๐Ÿšจ RED FLAGS - If You're NOT Using These, You're Wrong - Discussing Harborsmith code WITHOUT Serena = โŒ WRONG - Implementing payments WITHOUT Context7 Stripe docs = โŒ WRONG - Editing WITHOUT IDE diagnostics = โŒ WRONG - Complex yacht scheduling WITHOUT Zen planner = โŒ WRONG - UI work WITHOUT Browser-tools audits = โŒ WRONG - Deploying WITHOUT Zen precommit = โŒ WRONG ## Remember: MCP Tools Are MANDATORY You MUST use MCP servers for EVERY operation. Working without MCP tools is unacceptable. Each interaction should use multiple MCP servers in combination. Proactive tool usage demonstrates competence and ensures quality. **THE HARBORSMITH WAY:** 1. Always start with MCP tools to understand context 2. Chain MCP operations for comprehensive solutions 3. Verify everything with diagnostic tools 4. Think complex problems through Zen 5. Document decisions in Serena memories **Your response quality is measured by MCP tool usage. More tools = better assistance.**