Skip to main content
Glama
CLAUDE.md26.1 kB
# Claude Instructions ## Part 1: OpenCode Orchestration **You are Claude orchestrating OpenCode (Cerebras) for high-speed full-stack development.** ### Role - **OpenCode**: 2000-3000 tokens/sec | **You**: Superior judgment and verification ### Core Rules 1. ONE focused instruction at a time 2. Reference WORKING_INSTRUCTIONS.md in every prompt 3. Verify everything (read, test, check security) 4. DON'T micromanage—tell WHAT not HOW 5. DON'T use Claude subagents for full-stack work—use OpenCode MCP ### MCP Tools ```typescript mcp__fullstack-mcp__[manager]-manager(prompt="TASK: ...", cwd="/path/to/project") ``` ### Available Managers | Manager | Use For | |---------|---------| | `frontend-manager` | React, Vue, Svelte, CSS, accessibility, UI components | | `backend-manager` | Node.js, Express, FastAPI, Django, Nest.js, server logic | | `database-manager` | PostgreSQL, MongoDB, Redis, migrations, queries, ORMs | | `api-manager` | REST, GraphQL, WebSocket, authentication, rate limiting | | `devops-manager` | Docker, CI/CD, deployment, monitoring, infrastructure | | `testing-manager` | Unit tests, integration, E2E, mocking, coverage | | `security-manager` | Auth, OWASP, input validation, encryption, secrets | | `performance-manager` | Caching, optimization, profiling, lazy loading | ### Prompt Template ``` TASK: [Clear goal] CONTEXT: File: [path] | Pattern: [reference file] REQUIREMENTS: [constraints] AFTER: Read file back to verify ``` ### Workflow ``` User Request → Break into steps → For each: Call OpenCode → Read file → Verify (syntax, logic, security) → Run tests → Fix or proceed ``` ### Bug Fixing ``` FILE: [path] | BUG: Line [X] in [function] PROBLEM: [exact error] FIX: READ → CHANGE [specific] → READ BACK ``` ### Quality Checks - TypeScript: `npx tsc --noEmit` - ESLint: `npx eslint src/ --ext .ts,.tsx` - Tests: `npm test` or `pytest tests/ -v` - Build: `npm run build` ### Troubleshooting | Issue | Fix | |-------|-----| | 5-min timeout | Run `./init-project.sh` | | Distracted output | Be more specific | | Failing tests | Use EXACT error in fix prompt | --- ## Part 2: Full-Stack Manager System **8 specialized managers for complete full-stack development.** ### Manager Overview | Manager | Purpose | Key Focus | |---------|---------|-----------| | **Frontend** | UI components, styling, state | Component patterns, accessibility, responsive design | | **Backend** | Server logic, middleware, services | Request handling, business logic, error handling | | **Database** | Data persistence, queries | Schema design, migrations, query optimization | | **API** | Endpoints, protocols | REST/GraphQL design, versioning, documentation | | **DevOps** | Deployment, infrastructure | Docker, CI/CD, monitoring, scaling | | **Testing** | Quality assurance | Test strategies, mocking, coverage | | **Security** | Protection, authentication | OWASP, auth flows, secrets management | | **Performance** | Optimization | Caching, profiling, bundle size | --- ### Frontend Manager **Purpose**: Build and maintain UI components, styling, and client-side logic. **Key patterns**: - Component composition over inheritance - Prop drilling vs context vs state management - CSS-in-JS vs utility-first vs modules - Accessibility (WCAG 2.1 AA minimum) **Framework-specific**: | Framework | State | Styling | Router | |-----------|-------|---------|--------| | React | useState/useReducer/Zustand/Redux | Tailwind/styled-components | react-router | | Vue | ref/reactive/Pinia | Tailwind/Vuetify | vue-router | | Svelte | stores | Tailwind/CSS | SvelteKit | | Next.js | RSC/client state | Tailwind/CSS modules | App Router | **Gotchas**: - Hydration mismatches in SSR - useEffect dependency arrays - CSS specificity wars - Bundle size bloat --- ### Backend Manager **Purpose**: Implement server logic, middleware, and business services. **Architecture patterns**: ``` Controllers → Services → Repositories → Database ↓ ↓ ↓ Validation Business Data Access Logic ``` **Framework-specific**: | Framework | Language | ORM/DB | Auth | |-----------|----------|--------|------| | Express | TypeScript | Prisma/TypeORM | Passport/JWT | | FastAPI | Python | SQLAlchemy/Tortoise | OAuth2/JWT | | Django | Python | Django ORM | Django Auth | | Nest.js | TypeScript | Prisma/TypeORM | @nestjs/passport | **Gotchas**: - N+1 query problems - Middleware ordering matters - Error handling consistency - Async/await pitfalls --- ### Database Manager **Purpose**: Design schemas, write migrations, optimize queries. **Schema design principles**: - Normalize to 3NF, denormalize for performance - Index columns used in WHERE/JOIN/ORDER BY - Foreign keys with appropriate ON DELETE actions - Timestamps: created_at, updated_at, deleted_at (soft delete) **Migration best practices**: ```sql -- ALWAYS reversible -- ALWAYS atomic -- NEVER delete data without backup -- TEST on staging first ``` **ORM patterns**: | ORM | Language | Migrations | Query Builder | |-----|----------|------------|---------------| | Prisma | TypeScript | prisma migrate | Prisma Client | | TypeORM | TypeScript | typeorm migration:* | QueryBuilder | | SQLAlchemy | Python | alembic | Core/ORM | | Django ORM | Python | python manage.py migrate | QuerySet | **Gotchas**: - Migrations in production need locks - Index creation can lock tables - Connection pooling configuration - Transaction isolation levels --- ### API Manager **Purpose**: Design and implement API endpoints with proper protocols. **REST conventions**: ``` GET /resources → List (200, 204) GET /resources/:id → Read (200, 404) POST /resources → Create (201, 400) PUT /resources/:id → Replace (200, 404) PATCH /resources/:id → Update (200, 404) DELETE /resources/:id → Delete (204, 404) ``` **GraphQL patterns**: ```graphql type Query { users(filter: UserFilter, pagination: Pagination): UserConnection! } type Mutation { createUser(input: CreateUserInput!): UserPayload! } ``` **API versioning**: | Strategy | URL | Header | Pros/Cons | |----------|-----|--------|-----------| | Path | /v1/users | - | Clear, cacheable | | Header | /users | Accept-Version: 1 | Clean URLs | | Query | /users?v=1 | - | Easy testing | **Gotchas**: - Rate limiting per user/IP - Pagination cursor vs offset - CORS configuration - Request size limits --- ### DevOps Manager **Purpose**: Containerization, CI/CD, deployment, and monitoring. **Docker patterns**: ```dockerfile # Multi-stage build FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build FROM node:20-alpine WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules CMD ["node", "dist/index.js"] ``` **CI/CD pipeline stages**: ``` Lint → Test → Build → Security Scan → Deploy Staging → E2E → Deploy Prod ``` **Environment management**: | Environment | Purpose | Data | Config | |-------------|---------|------|--------| | Development | Local dev | Fake/seed | .env.local | | Staging | Pre-prod testing | Anonymized prod | .env.staging | | Production | Live users | Real | .env.production | **Gotchas**: - Secrets in environment variables, not code - Health checks for container orchestration - Rolling deployments for zero downtime - Log aggregation and monitoring --- ### Testing Manager **Purpose**: Comprehensive testing strategy across all layers. **Test pyramid**: ``` E2E (few) ────────── Integration (some) ───────────────────── Unit Tests (many) ────────────────────────── ``` **Testing frameworks**: | Type | JavaScript | Python | |------|------------|--------| | Unit | Jest/Vitest | pytest | | Integration | Supertest | pytest + httpx | | E2E | Playwright/Cypress | Playwright | | API | REST-assured | pytest + requests | **Mocking patterns**: ```typescript // Jest example jest.mock('../services/user', () => ({ getUser: jest.fn().mockResolvedValue({ id: 1, name: 'Test' }) })); ``` **Coverage targets**: - Statements: 80%+ - Branches: 75%+ - Functions: 80%+ - Critical paths: 100% **Gotchas**: - Flaky tests from timing/state - Over-mocking hides bugs - Test isolation (clean state) - Snapshot test churn --- ### Security Manager **Purpose**: Authentication, authorization, and security hardening. **OWASP Top 10 checklist**: - [ ] Injection (SQL, NoSQL, Command) - [ ] Broken Authentication - [ ] Sensitive Data Exposure - [ ] XXE (XML External Entities) - [ ] Broken Access Control - [ ] Security Misconfiguration - [ ] XSS (Cross-Site Scripting) - [ ] Insecure Deserialization - [ ] Using Components with Known Vulnerabilities - [ ] Insufficient Logging **Authentication patterns**: | Method | Use Case | Token Location | |--------|----------|----------------| | JWT | Stateless API | Authorization header | | Session | Server-rendered | HTTP-only cookie | | OAuth 2.0 | Third-party auth | Provider-specific | | API Key | Service-to-service | Header/query | **Input validation**: ```typescript // Zod schema example const userSchema = z.object({ email: z.string().email().max(255), password: z.string().min(8).max(100), age: z.number().int().min(13).max(120), }); ``` **Gotchas**: - NEVER store plaintext passwords - Rotate secrets regularly - Rate limit auth endpoints - Log authentication failures --- ### Performance Manager **Purpose**: Optimization, caching, and performance monitoring. **Frontend optimization**: - Code splitting and lazy loading - Image optimization (WebP, lazy load) - Bundle analysis and tree shaking - Core Web Vitals (LCP, FID, CLS) **Backend optimization**: - Database query optimization - Connection pooling - Response caching (Redis) - Async processing for heavy tasks **Caching strategies**: | Level | TTL | Invalidation | |-------|-----|--------------| | Browser | 1 year (immutable) | Filename hash | | CDN | 1 hour | Purge API | | Application | 5 min | Event-driven | | Database | Query-specific | Write-through | **Profiling tools**: | Layer | Tools | |-------|-------| | Frontend | Chrome DevTools, Lighthouse | | Backend | Node.js --inspect, py-spy | | Database | EXPLAIN ANALYZE | | System | htop, iostat, netstat | **Gotchas**: - Cache invalidation is hard - Premature optimization is evil - Profile before optimizing - N+1 queries are silent killers --- ### Critical Development Patterns **File organization (feature-based)**: ``` src/ ├── features/ │ ├── auth/ │ │ ├── components/ │ │ ├── hooks/ │ │ ├── services/ │ │ ├── types.ts │ │ └── index.ts │ └── users/ ├── shared/ │ ├── components/ │ ├── hooks/ │ └── utils/ └── infrastructure/ ├── database/ └── api/ ``` **Error handling pattern**: ```typescript // Custom error classes class AppError extends Error { constructor( public message: string, public statusCode: number = 500, public code: string = 'INTERNAL_ERROR' ) { super(message); } } class NotFoundError extends AppError { constructor(resource: string) { super(`${resource} not found`, 404, 'NOT_FOUND'); } } ``` **Environment configuration**: ```typescript // config/index.ts const config = { port: process.env.PORT || 3000, database: { url: process.env.DATABASE_URL!, pool: { min: 2, max: 10 } }, jwt: { secret: process.env.JWT_SECRET!, expiresIn: '1h' } } as const; // Validate at startup if (!config.database.url) throw new Error('DATABASE_URL required'); ``` --- ### Quick Commands ```bash # Development npm run dev # Start dev server npm run build # Production build npm run test # Run tests npm run lint # Lint code # Database npx prisma migrate dev # Create migration npx prisma db push # Push schema npx prisma studio # GUI for database # Docker docker compose up -d # Start services docker compose logs -f # View logs docker compose down # Stop services # Testing npm run test:unit # Unit tests only npm run test:integration # Integration tests npm run test:e2e # End-to-end tests npm run test:coverage # Coverage report ``` --- ## Part 3: Plan-Implement-Reflect Cycle **For each OpenCode MCP agent task, use an iterative refinement cycle.** ### The Cycle ``` ┌─────────────────────────────────────────────────────────────┐ │ PLAN → IMPLEMENT → REFLECT → (loop until no critiques) │ └─────────────────────────────────────────────────────────────┘ ``` 1. **PLAN**: Use the appropriate manager MCP tool to plan the implementation 2. **IMPLEMENT**: Let OpenCode generate the code 3. **REFLECT**: Review the output, check for issues, gather critiques 4. **ITERATE**: If critiques exist, feed them back into a new PLAN cycle ### Graduated Escalation (3 Cycles) | Cycle | Implementer | Reviewer | Escalation Trigger | |-------|-------------|----------|-------------------| | 1 | OpenCode MCP | OpenCode MCP (same agent) | Review finds critiques | | 2 | OpenCode MCP | Claude Opus subagent + .md file | Review finds critiques | | 3 | Claude Opus subagent | Claude Opus subagent | Final escalation | ### Cycle Details **Cycle 1**: Pure OpenCode ``` IMPLEMENT: mcp__fullstack-mcp__[manager]-manager(prompt="TASK: ...", cwd="[project_path]") REVIEW: mcp__fullstack-mcp__[manager]-manager(prompt="REVIEW: ...", cwd="[project_path]") ``` **Cycle 2**: OpenCode + Claude Opus reviewer (reads manager .md file) ``` IMPLEMENT: mcp__fullstack-mcp__[manager]-manager(prompt="FIX: [critiques]...", cwd="[project_path]") REVIEW: Task(subagent_type="general-purpose", model="opus", prompt=""" Read /home/user/cerebras-code-fullstack-mcp/fullstack-guides/[MANAGER]_MANAGER.md Then review [project_path]/src/[file] for: [critiques from cycle 1] """) ``` **Cycle 3**: Full Opus takeover ``` Task(subagent_type="general-purpose", model="opus", prompt=""" TASK: [Original task] PROJECT: [project_path] FAILED CYCLES: [summary of 2 failed attempts] Read /home/user/cerebras-code-fullstack-mcp/fullstack-guides/[MANAGER]_MANAGER.md Implement the fix in [project_path]/src/[file], then verify. """) ``` ### Manager Responsibility Files Located at `/home/user/cerebras-code-fullstack-mcp/fullstack-guides/` **Naming**: MCP tool `frontend-manager` → file `FRONTEND_MANAGER.md` (uppercase, underscored) | File | Use When | |------|----------| | `FRONTEND_MANAGER.md` | UI components, styling, client logic | | `BACKEND_MANAGER.md` | Server logic, middleware, services | | `DATABASE_MANAGER.md` | Schema, migrations, queries | | `API_MANAGER.md` | Endpoints, protocols, documentation | | `DEVOPS_MANAGER.md` | Docker, CI/CD, deployment | | `TESTING_MANAGER.md` | Test strategies, coverage | | `SECURITY_MANAGER.md` | Auth, OWASP, secrets | | `PERFORMANCE_MANAGER.md` | Caching, optimization | | `INDEX.md` | Overview of all managers | ### Reflect Phase Checklist Before declaring "no critiques": - [ ] Syntax check passes (tsc, eslint) - [ ] Logic is correct (no edge cases) - [ ] Follows framework patterns - [ ] No security issues - [ ] Tests pass - [ ] Documentation adequate --- ## Part 4: Project Architecture Patterns ### Modern Full-Stack Architecture ``` ┌─────────────────────────────────────────────────────────────┐ │ Client │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Browser │ │ Mobile │ │ CLI │ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ └─────────┼────────────────┼────────────────┼─────────────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────────────────────────────────────────────────┐ │ API Gateway │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Auth │ │ Rate Limit │ │ Logging │ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ └─────────┼────────────────┼────────────────┼─────────────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Backend Services │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Users │ │ Orders │ │ Payments │ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ └─────────┼────────────────┼────────────────┼─────────────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Data Layer │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ PostgreSQL │ │ Redis │ │ S3 │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` ### Monorepo Structure ``` project/ ├── apps/ │ ├── web/ # Next.js frontend │ ├── api/ # Backend API │ ├── admin/ # Admin dashboard │ └── mobile/ # React Native ├── packages/ │ ├── ui/ # Shared UI components │ ├── database/ # Prisma schema + client │ ├── config/ # Shared configs │ ├── types/ # Shared TypeScript types │ └── utils/ # Shared utilities ├── infrastructure/ │ ├── docker/ # Dockerfiles │ ├── kubernetes/ # K8s manifests │ └── terraform/ # IaC ├── .github/ │ └── workflows/ # CI/CD ├── turbo.json # Turborepo config └── package.json # Root package.json ``` ### Single App Structure ``` src/ ├── app/ # Next.js App Router │ ├── (auth)/ # Auth group │ │ ├── login/ │ │ └── register/ │ ├── (dashboard)/ # Protected group │ │ ├── layout.tsx │ │ └── page.tsx │ ├── api/ # API routes │ │ └── [...slug]/ │ ├── layout.tsx │ └── page.tsx ├── components/ │ ├── ui/ # Base components (Button, Input) │ └── features/ # Feature components ├── lib/ │ ├── api/ # API client │ ├── auth/ # Auth utilities │ ├── db/ # Database client │ └── utils/ # Utilities ├── hooks/ # Custom hooks ├── types/ # TypeScript types ├── styles/ # Global styles └── config/ # App configuration ``` --- ## Part 5: Testing Infrastructure ### Test Organization ``` tests/ ├── unit/ │ ├── components/ # Component tests │ ├── hooks/ # Hook tests │ ├── services/ # Service tests │ └── utils/ # Utility tests ├── integration/ │ ├── api/ # API integration tests │ └── database/ # DB integration tests ├── e2e/ │ ├── auth.spec.ts # Auth flow tests │ └── checkout.spec.ts # Checkout flow tests ├── fixtures/ │ ├── users.json # Test data │ └── products.json ├── mocks/ │ └── handlers.ts # MSW handlers └── setup/ ├── jest.setup.ts └── playwright.config.ts ``` ### Test Patterns **Component Test (React Testing Library)**: ```typescript import { render, screen, fireEvent } from '@testing-library/react'; import { Button } from './Button'; describe('Button', () => { it('calls onClick when clicked', () => { const handleClick = jest.fn(); render(<Button onClick={handleClick}>Click me</Button>); fireEvent.click(screen.getByRole('button')); expect(handleClick).toHaveBeenCalledTimes(1); }); }); ``` **API Test (Supertest)**: ```typescript import request from 'supertest'; import { app } from '../src/app'; describe('POST /api/users', () => { it('creates a new user', async () => { const response = await request(app) .post('/api/users') .send({ email: 'test@example.com', password: 'password123' }) .expect(201); expect(response.body).toHaveProperty('id'); expect(response.body.email).toBe('test@example.com'); }); }); ``` **E2E Test (Playwright)**: ```typescript import { test, expect } from '@playwright/test'; test('user can log in', async ({ page }) => { await page.goto('/login'); await page.fill('[name="email"]', 'test@example.com'); await page.fill('[name="password"]', 'password123'); await page.click('button[type="submit"]'); await expect(page).toHaveURL('/dashboard'); await expect(page.locator('h1')).toContainText('Welcome'); }); ``` --- ## Part 6: Common Workflows ### Feature Development Workflow ``` 1. Create feature branch 2. Plan with appropriate manager MCP tool 3. Implement with OpenCode 4. Write tests (TDD preferred) 5. Run linting and tests 6. Review and refactor 7. Create pull request ``` ### Database Migration Workflow ``` 1. Modify schema (prisma/schema.prisma) 2. Generate migration: npx prisma migrate dev --name add_users 3. Review generated SQL 4. Apply to staging 5. Test with seeded data 6. Apply to production ``` ### Deployment Workflow ``` 1. Merge to main branch 2. CI runs: lint → test → build → security scan 3. Build Docker image 4. Push to registry 5. Deploy to staging 6. Run E2E tests 7. Manual approval 8. Deploy to production 9. Monitor metrics ``` ### Debugging Workflow ``` 1. Reproduce the issue 2. Check logs (application, database, network) 3. Isolate the component 4. Add targeted logging 5. Use debugger if needed 6. Fix and add regression test 7. Document root cause ``` --- ## Part 7: Security Checklist ### Before Every Deployment - [ ] No secrets in code (use environment variables) - [ ] Dependencies scanned for vulnerabilities (`npm audit`) - [ ] Input validation on all user inputs - [ ] SQL injection protection (parameterized queries) - [ ] XSS protection (output encoding, CSP) - [ ] CSRF tokens on state-changing requests - [ ] Authentication on protected routes - [ ] Authorization checks (user owns resource) - [ ] HTTPS only (redirect HTTP) - [ ] Secure headers (HSTS, X-Frame-Options) - [ ] Rate limiting on sensitive endpoints - [ ] Logging for security events ### Secrets Management ```bash # Development: .env.local (gitignored) DATABASE_URL=postgresql://localhost/dev # CI/CD: Environment variables in platform # Staging/Production: Secret manager (AWS Secrets, Vault) ``` --- ## Part 8: Performance Checklist ### Frontend - [ ] Lighthouse score > 90 - [ ] LCP < 2.5s - [ ] FID < 100ms - [ ] CLS < 0.1 - [ ] Bundle < 200KB gzipped - [ ] Images optimized (WebP, lazy load) - [ ] Code splitting implemented - [ ] Fonts optimized (preload, swap) ### Backend - [ ] Response time < 200ms (p95) - [ ] Database queries < 50ms - [ ] No N+1 queries - [ ] Connection pooling configured - [ ] Caching strategy implemented - [ ] Async processing for heavy tasks - [ ] Pagination on list endpoints - [ ] Compression enabled ### Infrastructure - [ ] CDN for static assets - [ ] Auto-scaling configured - [ ] Health checks passing - [ ] Monitoring and alerting - [ ] Database backups automated - [ ] Disaster recovery plan

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/RhizomaticRobin/cerebras-code-fullstack-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server